text:
"""
LLDB AppKit formatters

part of The LLVM Compiler Infrastructure
This file is distributed under the University of Illinois Open Source
License. See LICENSE.TXT for details.
"""
# summary provider for CF(Mutable)BitVector
import lldb
import ctypes
import lldb.runtime.objc.objc_runtime
import lldb.formatters.metrics
import lldb.formatters.Logger

# first define some utility functions

def byte_index(abs_pos):
    logger = lldb.formatters.Logger.Logger()
    return abs_pos / 8

def bit_index(abs_pos):
    logger = lldb.formatters.Logger.Logger()
    return abs_pos & 7

def get_bit(byte, index):
    logger = lldb.formatters.Logger.Logger()
    if index < 0 or index > 7:
        return None
    return (byte >> (7 - index)) & 1

def grab_array_item_data(pointer, index):
    logger = lldb.formatters.Logger.Logger()
    return pointer.GetPointeeData(index, 1)

statistics = lldb.formatters.metrics.Metrics()
statistics.add_metric('invalid_isa')
statistics.add_metric('invalid_pointer')
statistics.add_metric('unknown_class')
statistics.add_metric('code_notrun')

# despite the similary to synthetic children providers, these classes are not
# trying to provide anything but a summary for a CF*BitVector, so they need not
# obey the interface specification for synthetic children providers

class CFBitVectorKnown_SummaryProvider:

    def adjust_for_architecture(self):
        logger = lldb.formatters.Logger.Logger()
        self.uiint_size = self.sys_params.types_cache.NSUInteger.GetByteSize()
        pass

    def __init__(self, valobj, params):
        logger = lldb.formatters.Logger.Logger()
        self.valobj = valobj
        self.sys_params = params
        if not(self.sys_params.types_cache.NSUInteger):
            if self.sys_params.is_64_bit:
                self.sys_params.types_cache.NSUInteger = self.valobj.GetType(
                ).GetBasicType(lldb.eBasicTypeUnsignedLong)
            else:
                self.sys_params.types_cache.NSUInteger = self.valobj.GetType(
                ).GetBasicType(lldb.eBasicTypeUnsignedInt)
        if not(self.sys_params.types_cache.charptr):
            self.sys_params.types_cache.charptr = self.valobj.GetType(
            ).GetBasicType(lldb.eBasicTypeChar).GetPointerType()
        self.update()

    def update(self):
        logger = lldb.formatters.Logger.Logger()
        self.adjust_for_architecture()

    # we skip the CFRuntimeBase
    # then the next CFIndex is the count
    # then we skip another CFIndex and then we get at a byte array
    # that wraps the individual bits

    def contents(self):
        logger = lldb.formatters.Logger.Logger()
        count_vo = self.valobj.CreateChildAtOffset(
            "count",
            self.sys_params.cfruntime_size,
            self.sys_params.types_cache.NSUInteger)
        count = count_vo.GetValueAsUnsigned(0)
        if count == 0:
            return '(empty)'

        array_vo = self.valobj.CreateChildAtOffset(
            "data",
            self.sys_params.cfruntime_size +
            2 *
            self.uiint_size,
            self.sys_params.types_cache.charptr)

        data_list = []
        cur_byte_pos = None
        for i in range(0, count):
            if cur_byte_pos is None:
                cur_byte_pos = byte_index(i)
                cur_byte = grab_array_item_data(array_vo, cur_byte_pos)
                cur_byte_val = cur_byte.uint8[0]
            else:
                byte_pos = byte_index(i)
                # do not fetch the pointee data every single time through
                if byte_pos != cur_byte_pos:
                    cur_byte_pos = byte_pos
                    cur_byte = grab_array_item_data(array_vo, cur_byte_pos)
                    cur_byte_val = cur_byte.uint8[0]
            bit = get_bit(cur_byte_val, bit_index(i))
            if (i % 4) == 0:
                data_list.append(' ')
            if bit == 1:
                data_list.append('1')
            else:
                data_list.append('0')
        return ''.join(data_list)

class CFBitVectorUnknown_SummaryProvider:

    def adjust_for_architecture(self):
        pass

    def __init__(self, valobj, params):
        logger = lldb.formatters.Logger.Logger()
        self.valobj = valobj
        self.sys_params = params
        self.update()

    def update(self):
        logger = lldb.formatters.Logger.Logger()
        self.adjust_for_architecture()

    def contents(self):
        logger = lldb.formatters.Logger.Logger()
        return '<unable to summarize this CFBitVector>'

def GetSummary_Impl(valobj):
    logger = lldb.formatters.Logger.Logger()
    global statistics
    class_data, wrapper = lldb.runtime.objc.objc_runtime.Utilities.prepare_class_detection(
        valobj, statistics)
    if wrapper:
        return wrapper

    name_string = class_data.class_name()
    actual_name = name_string

    logger >> "name string got was " + \
        str(name_string) + " but actual name is " + str(actual_name)

    if class_data.is_cftype():
        # CFBitVectorRef does not expose an actual NSWrapper type, so we have to check that this is
        # an NSCFType and then check we are a pointer-to CFBitVectorRef
        valobj_type = valobj.GetType()
        if valobj_type.IsValid() and valobj_type.IsPointerType():
            valobj_type = valobj_type.GetPointeeType()
            if valobj_type.IsValid():
                actual_name = valobj_type.GetName()
        if actual_name == '__CFBitVector' or actual_name == '__CFMutableBitVector':
            wrapper = CFBitVectorKnown_SummaryProvider(
                valobj, class_data.sys_params)
            statistics.metric_hit('code_notrun', valobj)
        else:
            wrapper = CFBitVectorUnknown_SummaryProvider(
                valobj, class_data.sys_params)
            print actual_name
    else:
        wrapper = CFBitVectorUnknown_SummaryProvider(
            valobj, class_data.sys_params)
        print name_string
        statistics.metric_hit(
            'unknown_class',
            valobj.GetName() +
            " seen as " +
            name_string)
    return wrapper

def CFBitVector_SummaryProvider(valobj, dict):
    logger = lldb.formatters.Logger.Logger()
    provider = GetSummary_Impl(valobj)
    if provider is not None:
        if isinstance(
                provider,
                lldb.runtime.objc.objc_runtime.SpecialSituation_Description):
            return provider.message()
        try:
            summary = provider.contents()
        except:
            summary = None
        logger >> "summary got from provider: " + str(summary)
        if summary is None or summary == '':
            summary = '<variable is not CFBitVector>'
        return summary
    return 'Summary Unavailable'

def __lldb_init_module(debugger, dict):
    debugger.HandleCommand(
        "type summary add -F CFBitVector.CFBitVector_SummaryProvider CFBitVectorRef CFMutableBitVectorRef")


text:
'use strict';

// Prevent mocking these two functions
jest
  .dontMock('fs')
  .dontMock('vm')
  .dontMock('sinon-chrome');

// Mock out Chrome's extension APIs
import vm from 'vm';
import fs from 'fs';
import chrome from 'sinon-chrome';
beforeEach(() => {
  window.chrome = chrome;
  chrome.runtime.sendMessage.flush();
});
afterEach(() => {
  chrome.flush();
  delete window.chrome;
});

describe('background.js', function() {
  // test('should render Main component', () => {
  //   const getUrl = function() {
  //     return chrome.runtime.getURL('popup-content.html');
  //   };
  //   chrome.runtime.getURL.returns('http://localhost:1234/index.html');
  //   const { container } = render(<Main getUrl={getUrl} />);
  //   expect(container).toMatchSnapshot();
  // });

  test('initial install', function() {
    // 1. mock chrome.* APIs to return predefined response
    // chrome.runtime.getManifest = () => ({version: '1.0'});
    // chrome.tabs.query.yields([
    //   {id: 1, title: 'Tab 1'},
    //   {id: 2, title: 'Tab 2'}
    // ]);

    // 2. inject our mocked chrome.* api into some environment
    // const context = { chrome: chrome };
    //
    // // 3. run our extension code in this environment
    // const code = fs.readFileSync('./app/scripts/background.js');
    // vm.runInNewContext(code, context);
    //
    // // 4. assert that button badge equals to '2'
    // sinon.assert.calledOnce(chrome.browserAction.setBadgeText);
    // sinon.assert.calledWithMatch(chrome.browserAction.setBadgeText, {
    //   text: "2"
    // });
  });

  // // Test shortcut database version mismatch
  // function testVersionMismatch(completionBlock)
  // {
  //   console.log('testVersionMismatch');
  //
  //   chrome.storage.sync.get(null, function(data)
  //   {
  //     if (chrome.runtime.lastError) {	// Check for errors
  //       console.error(chrome.runtime.lastError);
  //     }
  //     else
  //     {
  //       // Set an older shortcut version and store it back
  //       data[SHORTCUT_VERSION_KEY] = '1.7.0';
  //
  //       chrome.storage.sync.set(data, function() {
  //         if (chrome.runtime.lastError) {	// Check for errors
  //           console.error(chrome.runtime.lastError);
  //         }
  //         else
  //         {
  //           console.log('test setup complete');
  //           if (completionBlock) {
  //             completionBlock();
  //           }
  //         }
  //       });
  //     }
  //   });
  // }
  //
  // // Test shortcut database loss
  // function testDataLoss(completionBlock)
  // {
  //   console.log('testDataLoss');
  //
  //   chrome.storage.sync.clear(function()
  //   {
  //     if (chrome.runtime.lastError) {	// Check for errors
  //       console.error(chrome.runtime.lastError);
  //     } else {
  //       chrome.storage.local.remove([APP_BACKUP_KEY, APP_BACKUP_TIMESTAMP_KEY], function()
  //       {
  //         if (chrome.runtime.lastError) {	// Check for errors
  //           console.error(chrome.runtime.lastError);
  //         } else {
  //           console.log('test setup complete');
  //           if (completionBlock) {
  //             completionBlock();
  //           }
  //         }
  //       });
  //     }
  //   });
  // }

});

redpajama_set_name: RedPajamaGithub


text:
```
layout: showcase
title: "Dinosaur-Ghost Rampage"
windows: http://dinoghost.tims-world.com/
flash: http://dinoghost.tims-world.com/
website: http://dinoghost.tims-world.com/
```


text:
class Npc : public Character
{
    public:
    Npc();

    Direction DecideDirection( const kuko::BaseEntity& target );

    //virtual void Setup( const std::string& name, SDL_Texture* texture, kuko::PositionRect position, bool center = false  );
    //virtual void Cleanup();

    virtual void Update( int maxX, int maxY );
    //virtual void Draw();
    //bool IsMoving();

    //void MoveUp();
    //void MoveDown();
    //void MoveLeft();
    //void MoveRight();

    //kuko::PositionRect MoveCheck( Direction dir );

    protected:
    //std::string m_id;
    //SDL_Rect m_position;
    //Sprite m_sprite;
    //void UpdateSprite();

    //void Move( Direction dir );
    //float m_speed;
    //float m_moveCounter;
    //Direction m_moveDirection;
    //float m_frameCounter;

};

#endif


text:
package org.mitre.mrald.taglib;

import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.mitre.mrald.control.MsgObject;
import org.mitre.mrald.util.*;

/**
 *  Description of the Class
 *
 *@author     jchoyt
 *@created    October 9, 2002
 */
public class ListUpdateValuesTag extends BodyTagSupport
{
    /**
     *  Description of the Field
     */
    protected ResultSet rs;
    /**
     *  Description of the Field
     */
    protected String schema;
    /**
     *  Description of the Field
     */
    protected String action;

    /**
     *  Constructor for the AllTablesListTag object
     */
    public ListUpdateValuesTag() { }

    /**
     *  Description of the Method
     *
     *@return                   Description of the Return Value
     *@exception  JspException  Description of the Exception
     */
    public int doStartTag()
        throws JspException
    {
        try
        {
        	//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Start " );

            ServletRequest request = pageContext.getRequest();
            String tableName = request.getParameter( "tableName" );
            String datasource = request.getParameter( "datasource" );

            if (datasource.equals(""))
    		    datasource= "main";

            DBMetaData md = MetaData.getDbMetaData( datasource );
            String tempTableName = tableName;

			TableMetaData tableInfo = md.getTableMetaDataNoCase(tempTableName);
			if (tableInfo == null)
			{
				// MraldOutFile.logToFile( "List Update values; doStartTag: Table: " + tableName + " not found in Database. " );

				throw new JspException("Table: " + tableName + " not found in Database. ");
			}

			Collection<String> primaryKeys = tableInfo.getPrimaryKeys();

			//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Got tableMetaData " + tableInfo );

            //add quotes around tablename if it has spaces
            String queryTableName = new String( tableName );
            if ( queryTableName.indexOf( ' ' ) != -1 )
            {
                queryTableName = "\"" + queryTableName + "\"";
            }
            int i = 1;
            //List of columns that are linked to Fk
            //fks is the column in the current table that contains a link to a fk
            String[] fks = request.getParameterValues( "fKey" + i );
            // MraldOutFile.logToFile("ListUpdateValuesTag : doStartTag: fkLinks: " + fks );
            HashMap<String, String[]> linkInfo = new HashMap<String, String[]>();
            while ( i < 100 )
            {
                if ( ( fks == null ) || ( fks.length == 0 ) )
                {
                    i++;
                    fks = request.getParameterValues( "fKey" + i );
                    continue;
                }
                String filterTable = request.getParameter( "fKeyFilterTable" + i );
                String filterColumn= request.getParameter( "fKeyFilterColumn" + i );
                String filterValue= request.getParameter( "fKeyFilterValue" + i );
                String dropDownDataSource= request.getParameter( "fKeyDataSource" + i );
                if (dropDownDataSource== null)
                	dropDownDataSource="main";

                if (filterTable == null)
                {
                	filterTable="";
                	filterColumn="";
                	filterValue="";

                }

                String[] fklink = new String[]{
                        request.getParameter( "fKeyTable" + i ),
                        request.getParameter( "fKeyId" + i ),
                        request.getParameter( "fKeyList" + i ),
                         dropDownDataSource ,
                        filterTable, filterColumn, filterValue};

                linkInfo.put( fks[0].toUpperCase(), fklink );
                i++;
                fks = request.getParameterValues( "fKey" + i );
            }

            // MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Number of foreign Links: " +  linkInfo.size());
			//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Got all Foreign Key Data " );

            Enumeration names = request.getParameterNames();
            StringBuffer whereClause = new StringBuffer();
            ArrayList<String> filters = new ArrayList<String>();
            ArrayList<String> pks = new ArrayList<String>();
            ArrayList<String> pksLowerCase = new ArrayList<String>();
            String whereAppend = " ";
            while ( names.hasMoreElements() )
            {
                String colName = names.nextElement().toString();
    			//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Getting data for column " + colName );

                if ( colName.equals( "tableName" ) || colName.startsWith( "fKey" ) || colName.equals( "datasource" ) || colName.equals( "SuccessUrl" ))
                {
                    continue;
                }

                //MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Check if column " + colName + " is a primary Key " );

                String newColName = colName;
                boolean isPrimaryKey = tableInfo.isPrimaryKeyNoCase(newColName);
                //MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: is column " + colName + " a primary Key?  " + isPrimaryKey );

                //Check To see if the column is a primary Key

                pks.add(colName.toLowerCase());

                //Additional check to make sure that all primary keys are
                //specified at least once
                if (isPrimaryKey)
                {
                	//Make sure that each Primary Key is only added once despite case differences
                	if (!pksLowerCase.contains(colName.toLowerCase()))
                		pksLowerCase.add( colName.toLowerCase() );
                }

            	//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: About to get value for Column " + colName + " " );

                String val = request.getParameter( colName );

                //MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag:Value for Column " + colName + " " +val );

                //Ignore any columns listed that are not in the table
                if (checkHasColumn(tableInfo, colName))
                {
                	whereClause.append( whereAppend );
                	//MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; column " + colName + " found in " + tableName );
                    whereAppend = " AND ";

                	whereClause.append( colName + "='" + val + "'" );
                	String pkStr = "Table" + FormTags.NAMEVALUE_TOKEN_STR + tableName + "~Field" + FormTags.NAMEVALUE_TOKEN_STR  + colName + "~Value" + FormTags.NAMEVALUE_TOKEN_STR  + val;
                	filters.add( pkStr );

                }

            }

            //Make sure that all unique parameters are specified to stop more data being returned than should be
            if (pksLowerCase.size() < primaryKeys.size())
            {
            	// MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Not all Primary Key Values have been specified " );
            	MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: Should have " +primaryKeys.size() +    " but actually have " + pks.size() );

            	throw new JspException("Not all Primary Key Values have been specified ");
            }
//	    Remove DISTINCT as this creates problems for complex datatypes.
            //String selectClause = "Select DISTINCT * from " + queryTableName;
            String selectClause = "Select * from " + queryTableName;
            if ( whereClause.length() > 0 )
            {
                selectClause = selectClause + " WHERE " + whereClause;
            }
            // MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; doStartTag: selectClause " + selectClause );

            //String valuesList = outputResults( datasource, selectClause, tableName, pks, linkInfo );
            String valuesList = outputResults( datasource, selectClause, tableName, pks, linkInfo );
            String filtersList = outputFilters( filters );
            pageContext.getOut().print( valuesList );
            pageContext.getOut().print( filtersList );
            return EVAL_BODY_AGAIN;
        }
        catch ( SQLException e )
        {
            throw new JspException( e );
        }
        catch ( IOException e )
        {
            throw new JspException( e );
        }
    }

    private boolean checkHasColumn(TableMetaData tableInfo,String colName )
    {
		// MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; checkHasColumn for " + colName );

    	Iterator<String> colIter = tableInfo.getColumnNames().iterator();
    	String lowerCaseColumn = colName.toLowerCase();
    	while (colIter.hasNext())
    	{
    		String listColumn = colIter.next().toLowerCase();
    		if (lowerCaseColumn.equals(listColumn))
    			return true;
    	}
    	return false;
    }

    /**
     *  SetAction
     *
     *@param  action  The new action value
     */
    public void setAction( String action )
    {
        this.action = action;
    }

    /**
     *  SetAction
     */
    // public String getAction()
    // {
    // return this.action;
    // }
    /**
     *  Initializes the streams and database connections.
     *
     *@param  selectClause      Description of the Parameter
     *@param  tableName         Description of the Parameter
     *@param  pks               Description of the Parameter
     *@param  fks               Description of the Parameter
     *@return                   Description of the Return Value
     *@exception  SQLException  Description of the Exception
     *@exception  JspException  Description of the Exception
     */
    public String outputResults( String datasource, String selectClause, String tableName, ArrayList pks, HashMap fks )
        throws JspException, SQLException
    {
        /*
         *  Opening a connection to the Database
         */

    	// MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; outputResults. Start "  );

        Connection conn = new MraldConnection(
            datasource,
            new MsgObject((HttpServletRequest)pageContext.getRequest(),
                (HttpServletResponse)pageContext.getResponse() ) )
            .getConnection();
        DBMetaData md = MetaData.getDbMetaData( datasource );

        String noValue="";
        /*
         *  Setting and executing the query with the database connection
         */
        schema = md.getDbProps().getProperty( "SCHEMA" );
        if ( schema == null || schema.equals( Config.EMPTY_STR ) )
        {
            RuntimeException e = new RuntimeException( "A SCHEMA value was not provided in the database configuration file." );
            throw e;
        }

        rs = conn.createStatement().executeQuery( selectClause );

        String CALENDAR = "\n\n<A HREF=\"#\" onClick=\"cal<:orderNo:>.select(document.FormUpdate.<:name:>[0],'anchor<:orderNo:>','MM/dd/yyyy'); return false;\" TITLE=\"cal<:orderNo:>.select(document.FormUpdate.<:name:>[0],'anchor<:orderNo:>','MM/dd/yyyy'); return false; \"  NAME=\"anchor<:orderNo:>\" ID=\"anchor<:orderNo:>\">\n";
        ResultSetMetaData rsmd = rs.getMetaData();
        int colCount = rsmd.getColumnCount();
        /*
         *  Produce the table names with the appropriately labeled checkboxs
         */
        StringBuffer buffer = new StringBuffer();
        buffer.append( "\n
" );
        buffer.append( "" + action + " Values:
" );
        while ( rs.next() )
        {
            for ( int i = 0; i < colCount; i++ )
            {
                String value = rs.getString( i + 1 );
                if( value == null || value.equals("null") )
                {
                    value = noValue;
                }
                String colName = rsmd.getColumnName( i + 1 );
                int type = rsmd.getColumnType( i + 1 );
                String niceName = FBUtils.getColumnName(tableName + "." + colName);
                if (niceName == null)
				{
                	niceName=colName;
				}
                boolean isDate = false;
                String calendar;
                if ( ( type == Types.TIME ) || ( type == Types.DATE ) || ( type == Types.TIMESTAMP ) )
                {
                    isDate = true;
                }
                buffer.append( "\n
" + niceName + "	" );
                int textSize = 0;
                if ( value != null )
                {
                    textSize = value.length();
                }
                else
                {
                }
                //If the value is greater than 100 make a text area
                if ( textSize > 100 )
                {
                    buffer.append( "<textarea cols='100' rows='" + ( textSize / 100 + 1 ) + "' name='" + action + ( i + 1 ) + "'>" );
                    buffer.append( value + "</textarea>" );
                }
                else
                {

                	// MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; outputResults. Checking if fkeys contain  " + colName  );

                	String upperCaseColName = colName.toUpperCase();
                	if ( fks.containsKey( upperCaseColName ) )
                    {

                    	// MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; outputResults. Fkeys do contain  " + colName  );

                        DropDownListTag ddl = new DropDownListTag();
                        buffer.append( "<select" );
                        buffer.append( " name='" + action + ( i + 1 ) + "'>" );
                        String[] fkInfo = ( String[] ) fks.get( upperCaseColName );
                        ddl.setTable( fkInfo[0] );
                        ddl.setPkColumn( fkInfo[1] );
                        ddl.setListColumn( fkInfo[2] );
                        ddl.setValue( value );
                        ddl.setDatasource( fkInfo[3] );

                        if (!fkInfo[4].equals(""))
                        {
                          	ddl.setFilterTable(fkInfo[4]);
                          	ddl.setFilterColumn(fkInfo[5]);
                          	ddl.setFilterColumnValue(fkInfo[6]);

                        }

                        MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; outputResults. About to get Drop down data for : " +  colName  );

                        buffer.append( ddl.getDropDown() + "</select>\n" );
                        MraldOutFile.logToFile(Config.getProperty("LOGFILE"), "List Update values; outputResults. Finished Drop Down Retrieval for: " + colName  );

                    }
                    else if ( pks.contains( colName.toLowerCase() ) )
                    {

                        buffer.append( value + "	<input type=\"hidden\" name='" + action + ( i + 1 ) + "' value=\"" + value + "\">" );
                    }
                    else
                    {
                        buffer.append( "<input type='text' size='" + textSize );
                        buffer.append( "' name='" + action + ( i + 1 ) + "' " );
                        if ( isDate )
                        {
                        	if (!value.equals(noValue))
                        	{
                        		SimpleDateFormat df = new SimpleDateFormat( "yyyy-mm-dd"  );
                        		java.util.Date date;
                        		try
                        		{
                        			date = df.parse( value );

                        			df.applyPattern( "mm/dd/yyyy" );
                        			String dateVal = df.format( date );
                        			buffer.append( "value=\"" + dateVal + "\">" );
                        		} catch (ParseException e) {
                        			// TODO Auto-generated catch block
                        			RuntimeException re = new RuntimeException( "A date value could not be formatted." );
                        			throw re;
                        		}
                        		calendar = CALENDAR.replaceAll( "<:name:>", action + ( i + 1 ) );
                        		calendar = calendar.replaceAll( "<:orderNo:>", ( new Integer( i + 1 ) ).toString() );
                        		buffer.append( calendar );
                        	}
                        }
                        else
                        {
                        	 buffer.append( "value=\"" + value + "\">" );

                        }
                        buffer.append( "	" );
                    }
                }
                String typeName = FBUtils.isDateType(type)   ? "Date" :
								  FBUtils.isNumberType(type) ? "Numeric" :
								  FBUtils.isBinaryType(type) ? "Binary" :
									  						      "String";

                buffer.append( "<input type='hidden' name='" + action + ( i + 1 ) + "' value=\"Table" + FormTags.NAMEVALUE_TOKEN_STR  + tableName + "~Field" + FormTags.NAMEVALUE_TOKEN_STR  + colName + "~Type" + FormTags.NAMEVALUE_TOKEN_STR  + typeName + "\">
" );
            }
        }
        rs.close();
        conn.close();
        return buffer.toString();
    }

    /**
     *  Initializes the streams and database connections.
     *
     *@param  filters           Description of the Parameter
     *@return                   Description of the Return Value
     *@exception  SQLException  Description of the Exception
     */
    public String outputFilters( ArrayList filters )
        throws SQLException
    {
        /*
         *  Produce the table names with the appropriately labeled checkboxs
         */
        StringBuffer buffer = new StringBuffer();
        for ( int i = 0; i < filters.size(); i++ )
        {
            buffer.append( "\n<input type='hidden' name='Filter" + ( i + 1 ) + "' value=\"" + filters.get( i ) + "\" >" );
        }
        return buffer.toString();
    }
}


text:
package org.duracloud.snapshot.dto.task;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
import static org.junit.matchers.JUnitMatchers.containsString;

import org.duracloud.snapshot.error.SnapshotDataException;
import org.junit.Test;

/**
 * @author Bill Branan
 * Date: 7/30/14
 */
public class RestoreSnapshotTaskParametersTest {

    @Test
    public void testSerialize() {
        String snapshotId = "snapshot-id";
        String userEmail = "user-email";

        RestoreSnapshotTaskParameters taskParams =
            new RestoreSnapshotTaskParameters();
        taskParams.setSnapshotId(snapshotId);
        taskParams.setUserEmail(userEmail);

        String result = taskParams.serialize();
        String cleanResult = result.replaceAll("\\s+", "");
        assertThat(cleanResult,
                   containsString("\"snapshotId\":\"" + snapshotId + "\""));
        assertThat(cleanResult,
                   containsString("\"userEmail\":\"" + userEmail + "\""));
    }

    @Test
    public void testDeserialize() {
        // Verify valid params
        String taskParamsSerialized =
            "{\"snapshotId\" : \"snapshot-id\"," +
            " \"userEmail\" : \"yo@myemail.com\"}";

        RestoreSnapshotTaskParameters taskParams =
            RestoreSnapshotTaskParameters.deserialize(taskParamsSerialized);
        assertEquals("snapshot-id", taskParams.getSnapshotId());
        assertEquals("yo@myemail.com", taskParams.getUserEmail());

        // Verify that empty params throw
        taskParamsSerialized =
            "{\"snapshotId\" : \"\"," +
            " \"userEmail\" : \"\"}";

        try {
            RestoreSnapshotTaskParameters.deserialize(taskParamsSerialized);
            fail("Exception expected: Invalid params");
        } catch (SnapshotDataException e) {
            // Expected exception
        }

        // Verify that empty params throw
        try {
            RestoreSnapshotTaskParameters.deserialize("");
            fail("Exception expected: Invalid params");
        } catch (SnapshotDataException e) {
            // Expected exception
        }
    }

}


text:
import get from './get'
import post from './post'
import patch from './patch'

export default {
  get,
  post,
  patch
}


text:
require 'test_helper'
require 'generators/generators_test_helper'
require "generators/pbw/install/install_generator"
require 'mocha'

class InstallGeneratorTest < Rails::Generators::TestCase
  include GeneratorsTestHelper
  tests Pbw::Generators::InstallGenerator

  def setup
    mkdir_p "#{destination_root}/app/assets/javascripts"
    cp fixture("application.js"), "#{destination_root}/app/assets/javascripts"
    Rails.application.class.stubs(:name).returns("Dummy::Application")

    super
  end

  test "Assert application coffeescript file is created" do
    run_generator

    assert_file "#{backbone_path}/dummy.js.coffee", /window\.Dummy/
  end

  test "Assert application coffeescript file is created for two word application name" do
    Rails.application.class.stubs(:name).returns("FooBar::Application")
    run_generator

    assert_file "#{backbone_path}/foo_bar.js.coffee", /window\.FooBar/
  end

  test "Assert application require is properly setup for two word application name" do
    Rails.application.class.stubs(:name).returns("FooBar::Application")
    run_generator

    assert_file "app/assets/javascripts/application.js", /require backbone\/foo_bar/
  end

  test "Assert backbone directory structure is created" do
    run_generator

    %W{routers models views templates}.each do |dir|
      assert_directory "#{backbone_path}/#{dir}"
      assert_file "#{backbone_path}/#{dir}/.gitkeep"
    end
  end

  test "Assert no gitkeep files are created when skipping git" do
    run_generator [destination_root, "--skip-git"]

    %W{routers models views templates}.each do |dir|
      assert_directory "#{backbone_path}/#{dir}"
      assert_no_file "#{backbone_path}/#{dir}/.gitkeep"
    end
  end

  test "Assert application.js require underscore, backbone and backbone_rails_sync and dummy.js" do
    run_generator

    assert_file "app/assets/javascripts/application.js" do |application|
      assert_match /require backbone\/dummy/, application

      %W{underscore backbone backbone_rails_sync backbone_datalink}.each do |require|
        assert_match /#{require}/, application
      end
    end
  end

  def fixture(file)
    File.expand_path("fixtures/#{file}", File.dirname(__FILE__))
  end

end


text:
'use strict';

require('./_create-mfr.scss');

module.exports = {
  template: require('./create-mfr.html'),
  controller: ['$log', 'mfrService', CreateMfrController],
  controllerAs: 'createMfrCtrl',
  bindings: {
    mfr: '<'
  }
};

function CreateMfrController($log, mfrService){
  $log.debug('createMfrController');

  this.mfr = {};

  this.createMfr = function(){
    $log.debug('createMfrCtrl.createMfr');
    mfrService.createMfr(this.mfr)
    .then( () => {
      this.mfr.name = null;
      this.mfr.website = null;
    });
  };
}


text:
![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png)![0 stars](../../images/ic_star_border_black_18dp_1x.png) 0

To use the Snow Report for Alpine Mountain skill, try saying...

* *Alexa, open Alpine Mountain*

* *Alexa, ask Alpine Mountain for the snow report*

* *Alexa, ask Alpine Mountain for latest conditions*

The Alpine Mountain Snow Report brought to you by SnoCountry brings you the latest snow fall, snow surface conditions,  base depth, trail, and lift operations information.

***

### Skill Details

* **Invocation Name:** alpine mountain
* **Category:** null
* **ID:** amzn1.ask.skill.a9457c2f-3689-4ba0-adda-edda951c6bcd
* **ASIN:** B01M3YQ564
* **Author:** SnoCountry
* **Release Date:** November 4, 2016 @ 08:14:33
* **In-App Purchasing:** No


text:
#ifndef XGBINPUTCONNS_H
#define XGBINPUTCONNS_H

#include "csvinputfileconn.h"
#include "txtinputfileconn.h"

#define DMLC_THROW_EXCEPTION noexcept(false)
#define DMLC_NO_EXCEPTION  noexcept(true)

#include <dmlc/base.h>
#include <data/parser.h> // dmlc
#include <xgboost/data.h>

namespace dd
{
  class XGBInputInterface
  {
  public:
    XGBInputInterface() {}
    XGBInputInterface(const XGBInputInterface &xii)
      :_missing(xii._missing),_ids(xii._ids) {}
    ~XGBInputInterface()
      {
      }

  public:
    std::shared_ptr<xgboost::DMatrix>_m;
    std::shared_ptr<xgboost::DMatrix> _mtest;

    // parameters
    float _missing;// = std::NAN; /**< represents missing values. */
    std::vector<std::string> _ids; /**< input ids. */
  };

  class CSVXGBInputFileConn : public CSVInputFileConn, public XGBInputInterface
  {
  public:
    CSVXGBInputFileConn()
      :CSVInputFileConn() {}
    CSVXGBInputFileConn(const CSVXGBInputFileConn &i)
      :CSVInputFileConn(i),XGBInputInterface(i),_direct_csv(i._direct_csv) {}
    ~CSVXGBInputFileConn() {}

    void init(const APIData &ad)
    {
      if (ad.has("direct_csv") && ad.get("direct_csv").get<bool>())
	_direct_csv = true;
      CSVInputFileConn::init(ad);
    }

    void transform(const APIData &ad);

    xgboost::DMatrix* create_from_mat(const std::vector<CSVline> &csvl);

  public:
    bool _direct_csv = false; /**< whether to use the xgboost built-in CSV reader. */
  };

  class SVMXGBInputFileConn : public InputConnectorStrategy, public XGBInputInterface
  {
  public:
    SVMXGBInputFileConn()
      :InputConnectorStrategy() {}
    SVMXGBInputFileConn(const SVMXGBInputFileConn &i)
      :InputConnectorStrategy(i),XGBInputInterface(i) {}
    ~SVMXGBInputFileConn() {}

    void fillup_parameters(const APIData &ad_input)
    {
      if (ad_input.has("shuffle"))
	_shuffle = ad_input.get("shuffle").get<bool>();
      if (ad_input.has("seed"))
	_seed = ad_input.get("seed").get<int>();
      if (ad_input.has("test_split"))
	_test_split = ad_input.get("test_split").get<double>();
    }

    void init(const APIData &ad)
    {
      fillup_parameters(ad);
    }

    void transform(const APIData &ad);

  public:
    bool _shuffle = false;
    int _seed = -1;
    double _test_split = -1;
  };

  class TxtXGBInputFileConn : public TxtInputFileConn, public XGBInputInterface
  {
  public:
    TxtXGBInputFileConn()
      :TxtInputFileConn() {}
    TxtXGBInputFileConn(const TxtXGBInputFileConn &i)
      :TxtInputFileConn(i),XGBInputInterface(i) {}
    ~TxtXGBInputFileConn() {}

    void init(const APIData &ad)
    {
      TxtInputFileConn::init(ad);
    }

    void transform(const APIData &ad);

    xgboost::DMatrix* create_from_mat(const std::vector<TxtEntry<double>*> &txt);

  };

}

#endif


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: dcm4chee-exportmanager-service.xml 2852 2006-10-13 09:39:45Z gunterze $ -->
<server>
  <classpath codebase="lib" archives="dcm4chee.jar"/>

  <mbean code="org.jboss.mq.server.jmx.Queue"
	 name="dcm4chee.archive:service=Queue,name=ExportManager">
     <depends optional-attribute-name="DestinationManager">
     	jboss.mq:service=DestinationManager
     </depends>
  </mbean>

  <mbean code="org.dcm4chex.archive.tce.ExportManagerService"
	     name="dcm4chee.archive:service=ExportManager"
	     xmbean-dd="xmdesc/dcm4chee-exportmanager-xmbean.xml">
    <depends>dcm4chee.archive:service=AuditLogger</depends>
    <depends>dcm4chee.archive:service=StoreScp</depends>
    <depends>dcm4chee.archive:service=Queue,name=ExportManager</depends>
    <depends>dcm4chee.archive:service=JMS</depends>
  </mbean>
</server>


text:
package com.alibaba.json.bvt.parser.number;

import org.junit.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import junit.framework.TestCase;

public class NumberValueTest4 extends TestCase {

    public void test_0() throws Exception {
        String text = "{\"value\":21474836481}";
        JSONObject obj = (JSONObject) JSON.parse(text);
        Assert.assertEquals(Long.valueOf(21474836481L), obj.get("value"));

    }
}


text:
from __future__ import absolute_import

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'codearena.settings')

from celery import Celery

from django.conf import settings  # noqa

app = Celery('codearena')

app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))


text:
#ifdef OS_WINCE
#include <stdlib.h>
#endif
#include <log4cxx/logstring.h>
#include <log4cxx/helpers/fileoutputstream.h>
#include <log4cxx/helpers/exception.h>
#include <log4cxx/helpers/bytebuffer.h>
#include <apr_file_io.h>
#include <log4cxx/helpers/transcoder.h>
#if !defined(LOG4CXX)
#define LOG4CXX 1
#endif
#include <log4cxx/helpers/aprinitializer.h>

using namespace log4cxx;
using namespace log4cxx::helpers;

IMPLEMENT_LOG4CXX_OBJECT(FileOutputStream)

FileOutputStream::FileOutputStream(const LogString& filename,
    bool append) : pool(), fileptr(open(filename, append, pool)) {
}

FileOutputStream::FileOutputStream(const logchar* filename,
    bool append) : pool(), fileptr(open(filename, append, pool)) {
}

apr_file_t* FileOutputStream::open(const LogString& filename,
    bool append, Pool& pool) {
    apr_fileperms_t perm = APR_OS_DEFAULT;
    apr_int32_t flags = APR_WRITE | APR_CREATE;
    if (append) {
        flags |= APR_APPEND;
    } else {
        flags |= APR_TRUNCATE;
    }
    File fn;
    fn.setPath(filename);
    apr_file_t* fileptr = 0;
    apr_status_t stat = fn.open(&fileptr, flags, perm, pool);
    if (stat != APR_SUCCESS) {
      throw IOException(stat);
    }
    return fileptr;
}

FileOutputStream::~FileOutputStream() {
  if (fileptr != NULL && !APRInitializer::isDestructed) {
    apr_file_close(fileptr);
  }
}

void FileOutputStream::close(Pool& /* p */) {
  if (fileptr != NULL) {
    apr_status_t stat = apr_file_close(fileptr);
    if (stat != APR_SUCCESS) {
        throw IOException(stat);
    }
    fileptr = NULL;
  }
}

void FileOutputStream::flush(Pool& /* p */) {
}

void FileOutputStream::write(ByteBuffer& buf, Pool& /* p */ ) {
  if (fileptr == NULL) {
     throw IOException(-1);
  }
  size_t nbytes = buf.remaining();
  size_t pos = buf.position();
  const char* data = buf.data();
  while(nbytes > 0) {
    apr_status_t stat = apr_file_write(
      fileptr, data + pos, &nbytes);
    if (stat != APR_SUCCESS) {
      throw IOException(stat);
    }
    pos += nbytes;
    buf.position(pos);
    nbytes = buf.remaining();
  }
}


text:
package resources

import (
	"fmt"
	"strings"
)

const (
	keyPrefix   = "protoPayload"
	methodKey   = keyPrefix + ".methodName"
	serviceKey  = keyPrefix + ".serviceName"
	resourceKey = keyPrefix + ".resourceName"
	typeKey     = keyPrefix + ".\x22@type\x22"
	typeValue   = "type.googleapis.com/google.cloud.audit.AuditLog"
)

// Stackdriver query builder for querying audit logs. Currently
// supports querying by the AuditLog serviceName, methodName, and
// resourceName.
type FilterBuilder struct {
	serviceName  string
	methodName   string
	resourceName string
}

func (fb *FilterBuilder) WithServiceName(serviceName string) *FilterBuilder {
	fb.serviceName = serviceName
	return fb
}

func (fb *FilterBuilder) WithMethodName(methodName string) *FilterBuilder {
	fb.methodName = methodName
	return fb
}

func (fb *FilterBuilder) WithResourceName(resourceName string) *FilterBuilder {
	fb.resourceName = resourceName
	return fb
}

func (fb *FilterBuilder) GetFilterQuery() string {
	var filters []string
	if fb.methodName != "" {
		filters = append(filters, filter{methodKey, fb.methodName}.String())
	}

	if fb.serviceName != "" {
		filters = append(filters, filter{serviceKey, fb.serviceName}.String())
	}

	if fb.resourceName != "" {
		filters = append(filters, filter{resourceKey, fb.resourceName}.String())
	}

	filters = append(filters, filter{typeKey, typeValue}.String())
	filter := strings.Join(filters, " AND ")
	return filter
}

type filter struct {
	key   string
	value string
}

func (f filter) String() string {
	return fmt.Sprintf("%s=%q", f.key, f.value)
}


text:
//Plugin Notifications and defines..
enum { EX_DDA , EX_VMS, EX_COMMAND, EX_SPINON, EX_SPINOFF, EX_SPINSPEED, EX_MOTORTUNED
       , EX_SETUP, EX_FEEDHOLD, EX_RUN, EX_ESTOP , EX_CONFIG };

main()
{
	int message = persist.UserData[0];  // Mach3 message ID
	int Direction = persist.UserData[1];  // Mach3 Spindle Direction
	float speed = *(float *)&persist.UserData[2];  // value stored is actually a float

	printf("Mach3 Notify Message=%d, Direction=%2d, Spindle Set to %f\n",message,Direction,speed);

	switch (message)
	{
		case EX_SPINSPEED:
			printf("Spindle Speed Set to %f\n",speed);
			break;

		case EX_SPINON:
			if (Direction==0)
			{
				printf("Spindle CW ON\n");
			}
			else if (Direction==1)
			{
				printf("Spindle CCW ON\n");
			}
			break;

		case EX_SPINOFF:
			printf("Spindle Stop\n");
			break;
	}
}


text:
@interface LTLoadingView : UIView

@property(nonatomic,assign)NSString *detailMessage;

- (void)startAnimating;
- (void)stopAnimating;

@end


text:
package br.alfa.sales.vo;

import java.math.BigDecimal;

public class ItemPedidoVO {

	private Long produtoId;

	private BigDecimal valorUnitario;

	private Integer quantidadeItens;

	public Long getProdutoId() {
		return produtoId;
	}

	public void setProdutoId(Long produtoId) {
		this.produtoId = produtoId;
	}

	public BigDecimal getValorUnitario() {
		return valorUnitario;
	}

	public void setValorUnitario(BigDecimal valorUnitario) {
		this.valorUnitario = valorUnitario;
	}

	public Integer getQuantidadeItens() {
		return quantidadeItens;
	}

	public void setQuantidadeItens(Integer quantidade) {
		this.quantidadeItens = quantidade;
	}

}


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

<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>DateFormatterFactory</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.jetel.util.formatter

Class DateFormatterFactory

java.lang.Object

org.jetel.util.formatter.DateFormatterFactory

public final class DateFormatterFactory
extends java.lang.Object

Factory for internally used date formatters.

Method Summary

Methods

Modifier and Type
Method and Description

static DateFormatter
getFormatter()

static DateFormatter
getFormatter(java.util.Locale locale)

static DateFormatter
getFormatter(java.lang.String formatString)

static DateFormatter
getFormatter(java.lang.String formatString,
            java.util.Locale locale)

static DateFormatter
getFormatter(java.lang.String formatString,
            java.util.Locale locale,
            java.lang.String timeZoneId)

static DateFormatter
getFormatter(java.lang.String formatString,
            java.util.Locale locale,
            TimeZoneProvider timeZoneProvider)

static DateFormatter
getFormatter(java.lang.String formatString,
            java.lang.String localeString)

static DateFormatter
getFormatter(java.lang.String formatString,
            java.lang.String localeString,
            java.lang.String timeZoneString)

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getFormatter

public static DateFormatter getFormatter(java.lang.String formatString,
                         java.util.Locale locale,
                         TimeZoneProvider timeZoneProvider)

getFormatter

public static DateFormatter getFormatter(java.lang.String formatString,
                         java.util.Locale locale,
                         java.lang.String timeZoneId)

getFormatter

public static DateFormatter getFormatter(java.lang.String formatString,
                         java.util.Locale locale)

getFormatter

public static DateFormatter getFormatter(java.lang.String formatString,
                         java.lang.String localeString)

getFormatter

public static DateFormatter getFormatter(java.lang.String formatString,
                         java.lang.String localeString,
                         java.lang.String timeZoneString)

getFormatter

public static DateFormatter getFormatter(java.lang.String formatString)

getFormatter

public static DateFormatter getFormatter(java.util.Locale locale)

getFormatter

public static DateFormatter getFormatter()

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

				<address>Copyright © 2002-2015 Javlin a.s.</address>


text:
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package org.apache.tapestry5.internal.webresources;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.commons.Resource;
import org.apache.tapestry5.commons.util.CollectionFactory;
import org.apache.tapestry5.http.TapestryHttpSymbolConstants;
import org.apache.tapestry5.internal.TapestryInternalUtils;
import org.apache.tapestry5.internal.services.assets.BytestreamCache;
import org.apache.tapestry5.ioc.IOOperation;
import org.apache.tapestry5.ioc.OperationTracker;
import org.apache.tapestry5.ioc.annotations.PostInjection;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.services.assets.ResourceDependencies;
import org.apache.tapestry5.services.assets.ResourceTransformer;
import org.apache.tapestry5.webresources.WebResourcesSymbols;
import org.slf4j.Logger;

import java.io.*;
import java.util.Map;

public class ResourceTransformerFactoryImpl implements ResourceTransformerFactory
{
    private final Logger logger;

    private final OperationTracker tracker;

    private final boolean productionMode;

    private final File cacheDir;

    public ResourceTransformerFactoryImpl(Logger logger, OperationTracker tracker,
                                          @Symbol(TapestryHttpSymbolConstants.PRODUCTION_MODE)
                                          boolean productionMode,
                                          @Symbol(WebResourcesSymbols.CACHE_DIR)
                                          String cacheDir)
    {
        this.logger = logger;
        this.tracker = tracker;
        this.productionMode = productionMode;

        this.cacheDir = new File(cacheDir);

        if (!productionMode)
        {
            logger.info(String.format("Using %s to store compiled assets (development mode only).", cacheDir));
        }
    }

    @PostInjection
    public void createCacheDir(@Symbol(SymbolConstants.RESTRICTIVE_ENVIRONMENT) boolean restrictive)
    {
        if (!restrictive)
        {
            cacheDir.mkdirs();
        }
    }

    static class Compiled extends ContentChangeTracker
    {
        private BytestreamCache bytestreamCache;

        Compiled(Resource root)
        {
            addDependency(root);
        }

        void store(InputStream stream) throws IOException
        {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();

            TapestryInternalUtils.copy(stream, bos);

            stream.close();
            bos.close();

            this.bytestreamCache = new BytestreamCache(bos);
        }

        InputStream openStream()
        {
            return bytestreamCache.openStream();
        }
    }

    @Override
    public ResourceTransformer createCompiler(String contentType, String sourceName, String targetName, ResourceTransformer transformer, CacheMode cacheMode)
    {
        ResourceTransformer trackingCompiler = wrapWithTracking(sourceName, targetName, transformer);

        if (productionMode)
        {
            return trackingCompiler;
        }

        ResourceTransformer timingCompiler = wrapWithTiming(targetName, trackingCompiler);

        switch (cacheMode)
        {
            case NONE:

                return timingCompiler;

            case SINGLE_FILE:

                return wrapWithFileSystemCaching(timingCompiler, targetName);

            case MULTIPLE_FILE:

                return wrapWithInMemoryCaching(timingCompiler, targetName);

            default:

                throw new IllegalStateException();
        }
    }

    private ResourceTransformer wrapWithTracking(final String sourceName, final String targetName, ResourceTransformer core)
    {
        return new DelegatingResourceTransformer(core)
        {
            @Override
            public InputStream transform(final Resource source, final ResourceDependencies dependencies) throws IOException
            {
                final String description = String.format("Compiling %s from %s to %s", source, sourceName, targetName);

                return tracker.perform(description, new IOOperation<InputStream>()
                {
                    @Override
                    public InputStream perform() throws IOException
                    {
                        return delegate.transform(source, dependencies);
                    }
                });
            }
        };
    }

    private ResourceTransformer wrapWithTiming(final String targetName, ResourceTransformer coreCompiler)
    {
        return new DelegatingResourceTransformer(coreCompiler)
        {
            @Override
            public InputStream transform(final Resource source, final ResourceDependencies dependencies) throws IOException
            {
                final long startTime = System.nanoTime();

                InputStream result = delegate.transform(source, dependencies);

                final long elapsedTime = System.nanoTime() - startTime;

                logger.info(String.format("Compiled %s to %s in %.2f ms",
                        source, targetName,
                        ResourceTransformUtils.nanosToMillis(elapsedTime)));

                return result;
            }
        };
    }

    /**
     * Caching is not needed in production, because caching of streamable resources occurs at a higher level
     * (possibly after sources have been aggregated and minimized and gzipped). However, in development, it is
     * very important to avoid costly CoffeeScript compilation (or similar operations); Tapestry's caching is
     * somewhat primitive: a change to *any* resource in a given domain results in the cache of all of those resources
     * being discarded.
     */
    private ResourceTransformer wrapWithInMemoryCaching( ResourceTransformer core, final String targetName)
    {
        return new DelegatingResourceTransformer(core)
        {
            final Map<Resource, Compiled> cache = CollectionFactory.newConcurrentMap();

            @Override
            public InputStream transform(Resource source, ResourceDependencies dependencies) throws IOException
            {
                Compiled compiled = cache.get(source);

                if (compiled != null && !compiled.dirty())
                {
                    logger.info(String.format("Resource %s and dependencies are unchanged; serving compiled %s content from in-memory cache",
                            source, targetName));

                    return compiled.openStream();
                }

                compiled = new Compiled(source);

                InputStream is = delegate.transform(source, new ResourceDependenciesSplitter(dependencies, compiled));

                compiled.store(is);

                is.close();

                cache.put(source, compiled);

                return compiled.openStream();
            }
        };
    }

    private ResourceTransformer wrapWithFileSystemCaching( ResourceTransformer core, final String targetName)
    {
        return new DelegatingResourceTransformer(core)
        {
            @Override
            public InputStream transform(Resource source, ResourceDependencies dependencies) throws IOException
            {
                long checksum = ResourceTransformUtils.toChecksum(source);

                String fileName = Long.toHexString(checksum) + "-" + source.getFile();

                File cacheFile = new File(cacheDir, fileName);

                if (cacheFile.exists())
                {
                    logger.debug(String.format("Serving up compiled %s content for %s from file system cache", targetName, source));

                    return new BufferedInputStream(new FileInputStream(cacheFile));
                }

                InputStream compiled = delegate.transform(source, dependencies);

                // We need the InputStream twice; once to return, and once to write out to the cache file for later.

                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                TapestryInternalUtils.copy(compiled, bos);

                compiled.close();

                BytestreamCache cache = new BytestreamCache(bos);

                writeToCacheFile(cacheFile, cache.openStream());

                return cache.openStream();
            }
        };
    }

    private void writeToCacheFile(File file, InputStream stream) throws IOException
    {
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(file));

        TapestryInternalUtils.copy(stream, outputStream);

        outputStream.close();
    }
}


text:
from flask import json
from util import *
from flask import Flask
from flask import jsonify
from flask import json
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

@app.route("/buoys")
def getAllBuoys():
    return returnJson(["buoy1", "buoy2"])

@app.route("/buoys/<int:buoyId>")
def getBuoy(buoyId):
    return returnJson(["buoy%d" % buoyId])

if __name__ == "__main__":
    app.run(debug=True)


text:
<?php

declare(strict_types = 1);

namespace Apple\ApnPush\Jwt\SignatureGenerator;

use Apple\ApnPush\Jwt\JwtInterface;
use Jose\Factory\JWKFactory;
use Jose\Factory\JWSFactory;

/**
 * The signature generator with use "spomky-labs/jose" library.
 */
class SpomkyLabsJoseSignatureGenerator implements SignatureGeneratorInterface
{
    /**
     * {@inheritdoc}
     */
    public function generate(JwtInterface $jwt): string
    {
        $jwk = JWKFactory::createFromKeyFile($jwt->getPath(), '', [
            'kid' => $jwt->getKey(),
            'alg' => 'ES256',
            'use' => 'sig',
        ]);

        $payload = [
            'iss' => $jwt->getTeamId(),
            'iat' => \time(),
        ];

        $header = [
            'alg' => 'ES256',
            'kid' => $jwk->get('kid'),
        ];

        return JWSFactory::createJWSToCompactJSON(
            $payload,
            $jwk,
            $header
        );
    }
}


text:
package com.box.boxandroidlibv2.activities;

import org.apache.commons.lang.StringUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.http.SslError;
import android.os.Bundle;

import com.box.boxandroidlibv2.BoxAndroidClient;
import com.box.boxandroidlibv2.BoxAndroidConfigBuilder;
import com.box.boxandroidlibv2.R;
import com.box.boxandroidlibv2.dao.BoxAndroidOAuthData;
import com.box.boxandroidlibv2.viewlisteners.OAuthWebViewListener;
import com.box.boxandroidlibv2.views.OAuthWebView;
import com.box.boxjavalibv2.authorization.IAuthEvent;
import com.box.boxjavalibv2.authorization.IAuthFlowMessage;
import com.box.boxjavalibv2.events.OAuthEvent;

/**
 * Activity for OAuth. Use this activity by using the intent from createOAuthActivityIntent method. On completion, this activity will put the parcelable
 * BoxAndroidClient into activity result. In case of failing, the activity result will be {@link Activity#RESULT_CANCELED} together will a error message in
 * intent extra.
 */
public class OAuthActivity extends Activity {

    public static final String ERROR_MESSAGE = "exception";
    public static final String BOX_CLIENT_OAUTH = "boxAndroidClient_oauth";
    public static final String BOX_DEVICE_ID = "boxdeviceid";
    public static final String BOX_DEVICE_NAME = "boxdevicename";

    protected static final String CLIENT_ID = "clientId";
    protected static final String CLIENT_SECRET = "clientSecret";
    protected static final String REDIRECT_URL = "redirecturl";
    protected static final String ALLOW_LOAD_REDIRECT_PAGE = "allowloadredirectpage";

    private OAuthWebView oauthView;

    @Override
    public void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        Intent intent = getIntent();
        String clientId = intent.getStringExtra(CLIENT_ID);
        String clientSecret = intent.getStringExtra(CLIENT_SECRET);
        String deviceId = intent.getStringExtra(BOX_DEVICE_ID);
        String deviceName = intent.getStringExtra(BOX_DEVICE_NAME);
        String redirectUrl = intent.getStringExtra(REDIRECT_URL);
        boolean allowShowRedirect = getIntent().getBooleanExtra(ALLOW_LOAD_REDIRECT_PAGE, true);
        startOAuth(clientId, clientSecret, redirectUrl, allowShowRedirect, deviceId, deviceName);
    }

    protected int getContentView() {
        return R.layout.boxandroidlibv2_activity_oauth;
    }

    protected boolean shouldAutoRefreshOAuth() {
        return true;
    }

    protected void startOAuth(final String clientId, final String clientSecret, String redirectUrl, boolean allowShowRedirect, String deviceId,
        String deviceName) {
        BoxAndroidClient boxClient = createBoxClientForOAuth(clientId, clientSecret, redirectUrl);
        oauthView = createOAuthWebView(allowShowRedirect, deviceId, deviceName);
        getOAuthWebView().initializeAuthFlow(this, clientId, clientSecret, redirectUrl, boxClient);

        boxClient.authenticate(oauthView, shouldAutoRefreshOAuth(), getOAuthFlowListener());
    }

    protected BoxAndroidClient createBoxClientForOAuth(final String clientId, final String clientSecret, String redirectUrl) {
        return new BoxAndroidClient(clientId, clientSecret, null, null, (new BoxAndroidConfigBuilder()).build());
    }

    protected OAuthWebView createOAuthWebView(boolean allowShowRedirect, String deviceId, String deviceName) {
        OAuthWebView ui = (OAuthWebView) findViewById(getOAuthWebViewRId());
        ui.setAllowShowingRedirectPage(allowShowRedirect);
        if (StringUtils.isNotEmpty(deviceId) && StringUtils.isNotEmpty(deviceName)) {
            ui.setDevice(deviceId, deviceName);
        }
        return ui;
    }

    protected int getOAuthWebViewRId() {
        return R.id.oauthview;
    }

    protected void setOAuthWebView(OAuthWebView view) {
        this.oauthView = view;
    }

    protected OAuthWebView getOAuthWebView() {
        return oauthView;
    }

    /**
     * Create intent to launch OAuthActivity,use this method only if you already set redirect url in box
     * dev console and you want to show the redirect page at the end of OAuth flow.
     *
     * @param context
     *            context
     * @param clientId
     *            your box client id
     * @param clientSecret
     *            your box client secret
     * @return
     */
    public static Intent createOAuthActivityIntent(final Context context, final String clientId, final String clientSecret) {
        Intent intent = new Intent(context, OAuthActivity.class);
        intent.putExtra(CLIENT_ID, clientId);
        intent.putExtra(CLIENT_SECRET, clientSecret);
        return intent;
    }

    /**
     * Create intent to launch OAuthActivity, use this method only if you already set redirect url in box dev console.
     *
     * @param context
     *            context
     * @param clientId
     *            your box client id
     * @param clientSecret
     *            your box client secret
     * @param allowShowRedirectPage
     *            Whether you want to load/show redirected page after OAuth flow is done.
     * @return
     */
    public static Intent createOAuthActivityIntent(final Context context, final String clientId, final String clientSecret, final boolean allowShowRedirectPage) {
        return createOAuthActivityIntent(context, clientId, clientSecret, allowShowRedirectPage, null);
    }

    /**
     * Create intent to launch OAuthActivity. Notes about redirect url parameter: If you already set redirect url in box dev console, you should pass in the same redirect url or use null for redirect url. If you
     * didn't set it in box dev console, you should pass in a url. In case you don't have a redirect server you can simply use "http://localhost".
     *
     * @param context
     *            context
     * @param clientId
     *            your box client id
     * @param clientSecret
     *            your box client secret
     * @param allowShowRedirectPage
     *            Whether you want to load/show redirected page after OAuth flow is done.
     * @param redirectUrl
     *            redirect url, if you already set redirect url in box dev console, leave this null
     *            or use the same url, otherwise this field is required. You can use "http://localhost" if you don't have a redirect server.
     * @return
     */
    public static Intent createOAuthActivityIntent(final Context context, final String clientId, final String clientSecret,
        final boolean allowShowRedirectPage, String redirectUrl) {
        Intent intent = new Intent(context, OAuthActivity.class);
        intent.putExtra(CLIENT_ID, clientId);
        intent.putExtra(CLIENT_SECRET, clientSecret);
        intent.putExtra(ALLOW_LOAD_REDIRECT_PAGE, allowShowRedirectPage);
        if (StringUtils.isNotEmpty(redirectUrl)) {
            intent.putExtra(REDIRECT_URL, redirectUrl);
        }
        return intent;
    }

    /**
     * Create a listener to listen to OAuth flow events.
     *
     * @return OAuthWebViewListener
     */
    protected OAuthWebViewListener getOAuthFlowListener() {
        return new OAuthWebViewListener() {

            @Override
            public void onAuthFlowException(final Exception e) {
                Intent intent = new Intent();
                intent.putExtra(ERROR_MESSAGE, e.getMessage());
                OAuthActivity.this.setResult(RESULT_CANCELED, intent);
                finish();
            }

            @Override
            public void onAuthFlowEvent(final IAuthEvent event, final IAuthFlowMessage message) {
                if (event == OAuthEvent.OAUTH_CREATED) {
                    Intent intent = new Intent();
                    intent.putExtra(BOX_CLIENT_OAUTH, (BoxAndroidOAuthData) message.getData());
                    OAuthActivity.this.setResult(RESULT_OK, intent);
                    finish();
                }
            }

            @Override
            public void onSslError(final SslError error, final boolean canceled) {
                Intent intent = new Intent();
                if (canceled) {
                    intent.putExtra(ERROR_MESSAGE, "ssl error:" + error.getPrimaryError());
                    OAuthActivity.this.setResult(RESULT_CANCELED, intent);
                    finish();
                }
            }

            @Override
            public void onError(final int errorCode, final String description, final String failingUrl) {
                Intent intent = new Intent();
                intent.putExtra(ERROR_MESSAGE, description);
                OAuthActivity.this.setResult(RESULT_CANCELED, intent);
                finish();
            }

            @Override
            public void onAuthFlowMessage(IAuthFlowMessage message) {
            }

        };
    }
}


text:
#import "AWSRequest.h"

@class NSString, NSNumber;

@interface AWSSTSGetSessionTokenRequest : AWSRequest {
	NSNumber* _durationSeconds;
	NSString* _serialNumber;
	NSString* _tokenCode;
}
@property(retain, nonatomic) NSNumber* durationSeconds;
@property(retain, nonatomic) NSString* serialNumber;
@property(retain, nonatomic) NSString* tokenCode;
+ (id)JSONKeyPathsByPropertyKey;
- (void).cxx_destruct;
@end