text:
'use strict';

import * as chai from 'chai';
import * as fs from 'fs-extra-promise';
import 'mocha';
import * as path from 'path';
import * as request from 'request';

import { Container } from 'typescript-ioc';
import { SDK } from '../../src/admin/config/sdk';
import { ApiConfig } from '../../src/config/api';
import { Configuration } from '../../src/configuration';
import { generateSecurityToken, getSwaggerHost, getSwaggerUrl } from '../../src/utils/config';

const expect = chai.expect;
// tslint:disable:no-unused-expression

let config: Configuration;
let adminRequest: any;
let adminToken: string;
let configToken: string;
let sdk: SDK = null;

const adminUser = {
    email: 'test@mail.com',
    login: 'admin',
    name: 'Admin user',
    password: '123test',
    roles: ['admin', 'config']
};

const configUser = {
    email: 'test@mail.com',
    login: 'config',
    name: 'Config user',
    password: '123test',
    roles: ['config']
};

const simpleUser = {
    email: 'test@mail.com',
    login: 'simple',
    name: 'Simple user',
    password: '123test',
    roles: [] as Array<string>
};

const getIdFromResponse = (response: any) => {
    const location = response.headers['location'];
    expect(location).to.exist;
    const parts = location ? location.split('/') : [];
    return parts.length > 0 ? parts[parts.length - 1] : null;
};

const createUsers = () => {
    return Promise.all([sdk.users.addUser(adminUser), sdk.users.addUser(configUser), sdk.users.addUser(simpleUser)]);
};

async function initialize() {
    adminRequest = request.defaults({ baseUrl: `http://localhost:${config.gateway.admin.protocol.http.listenPort}` });

    sdk = await SDK.initialize({
        defaultHost: getSwaggerHost(config.gateway),
        swaggerUrl: getSwaggerUrl(config.gateway),
        token: generateSecurityToken(config.gateway)
    });
    await createUsers();
}

describe('Gateway Admin Tasks', () => {
    before(async () => {
        config = Container.get(Configuration);
        if (config.loaded) {
            await initialize();
        } else {
            await new Promise<void>((resolve, reject) => {
                config.on('load', () => {
                    initialize().then(resolve).catch(reject);
                });
                config.on('error', (err) => {
                    reject(err);
                });
            });
        }
    });

    describe('/healthcheck', () => {
        it('should return OK', (done) => {
            adminRequest.get('/healthcheck', (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(200);
                expect(body).to.equal('OK');
                done();
            });
        });
    });

    describe('/users', () => {
        it('should reject unauthenticated requests', (done) => {
            adminRequest.get('/users/admin', (error: any, response: any, body: any) => {
                expect(response.statusCode).to.equal(401);
                done();
            });
        });
        it('should be able to sign admin users in', (done) => {
            const form = {
                'login': 'admin',
                'password': '123test'
            };
            adminRequest.post({
                form: form,
                url: '/users/authentication'
            }, (error: any, response: any, body: any) => {
                expect(response.statusCode).to.equal(200);
                adminToken = body;
                done();
            });
        });
        it('should be able to sign in editor users', (done) => {
            const form = {
                'login': 'config',
                'password': '123test'
            };
            adminRequest.post({
                form: form,
                url: '/users/authentication'
            }, (error: any, response: any, body: any) => {
                expect(response.statusCode).to.equal(200);
                configToken = body;
                done();
            });
        });
        it('should be able to sign in simple users', (done) => {
            const form = {
                'login': 'simple',
                'password': '123test'
            };
            adminRequest.post({
                form: form,
                url: '/users/authentication'
            }, (error: any, response: any, body: any) => {
                expect(response.statusCode).to.equal(200);
                done();
            });
        });

    });

    describe('/apis', () => {
        const apiMock = {
            description: 'API mock',
            name: 'apiMock',
            path: 'newApi',
            proxy: {
                target: { host: 'http://test.com' }
            },
            version: '1.0'
        } as ApiConfig;

        it('should be able to create a new API', (done) => {
            adminRequest.post('/apis', {
                body: apiMock,
                headers: { 'authorization': `Bearer ${configToken}` },
                json: true
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(201);
                apiMock.id = getIdFromResponse(response);
                expect(apiMock.id).to.exist;
                done();
            });
        });

        it('should reject unauthenticated request to admin apis', (done) => {
            adminRequest.post('/apis', {
                body: apiMock, json: true
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(401);
                done();
            });
        });

        it('should reject an invalid API', (done) => {
            adminRequest.post('/apis', {
                body: {},
                headers: { 'authorization': `Bearer ${configToken}` },
                json: true
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(403);
                done();
            });
        });

        it('should be able to list all APIs', (done) => {
            adminRequest.get({
                headers: { 'authorization': `Bearer ${configToken}` },
                url: '/apis'
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(200);
                done();
            });
        });

        it('should be able to update an API', (done) => {
            apiMock.description = 'Updated api';

            adminRequest.put(`/apis/${apiMock.id}`, {
                body: apiMock,
                headers: { 'authorization': `Bearer ${configToken}` },
                json: true
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(204);
                done();
            });
        });

        it('should be able to get an API', (done) => {
            adminRequest.get({
                headers: { 'authorization': `Bearer ${configToken}` },
                url: `/apis/${apiMock.id}`
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(200);
                const api = JSON.parse(body);
                expect(api.description).to.equal('Updated api');
                done();
            });
        });

        it('should be able to delete an API', (done) => {
            adminRequest.delete({
                headers: { 'authorization': `Bearer ${configToken}` },
                url: `/apis/${apiMock.id}`
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(204);
                done();
            });
        });
    });

    describe('/users', () => {
        it('should reject requests with low privileges', (done) => {
            adminRequest.delete({
                headers: { 'authorization': `Bearer ${configToken}` },
                url: `/users/simple`
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(403);
                done();
            });
        });
        it('should be able to add users', (done) => {
            const simpleUser2 = {
                email: 'test2@mail.com',
                login: 'simple2',
                name: 'Simple user 2',
                password: '123test',
                roles: [] as Array<string>
            };

            adminRequest.post({
                body: simpleUser2,
                headers: { 'authorization': `Bearer ${adminToken}` },
                json: true,
                url: `/users`
            }, (error: any, response: any, body: any) => {
                expect(error).to.not.exist;
                expect(response.statusCode).to.equal(201);
                done();
            });
        });
    });

    describe('users SDK', () => {
        it('should be able to change password', () => {
            return sdk.users.changeUserPassword(simpleUser.login, 'newPassword');
        });

        it('should be able to update user properties', async () => {
            const updatedUser = Object.assign({}, simpleUser);
            updatedUser.name = 'New updated Name';
            await sdk.users.updateUser(simpleUser.login, updatedUser);
            const user = await sdk.users.getUser(simpleUser.login);
            expect(user.name).to.equals('New updated Name');
        });
        it('should be able to create new user', async () => {
            const newUser = Object.assign({}, simpleUser);
            newUser.login = simpleUser.login + '_sdk';
            await sdk.users.addUser(newUser);
        });
        it('should be able to remove users', async () => {
            await sdk.users.removeUser(simpleUser.login + '_sdk');
        });
        it('should be able to list users', async () => {
            const users = await sdk.users.list({});
            const logins = users.map(user => user.login);
            expect(logins).to.have.length(4);
            expect(logins).to.have.members(['admin', 'config', 'simple', 'simple2']);
        });
    });

    describe('gateway SDK', () => {
        it('should be able to set configuration for gateway', async () => {
            const newConfig = fs.readJSONSync(path.join(process.cwd(), 'test/data/tree-gateway.json')).gateway;
            await sdk.gateway.updateConfig(newConfig);
            await timeout(5000); // wait gateway restart after a gateway config change
        });
        it('should be able to retrieve configuration for gateway', async () => {
            const dbConfig = await sdk.gateway.getConfig();
            expect(dbConfig.logger.level).to.equals('debug');
        });
        it('should be able to remove configuration for gateway', async () => {
            await sdk.gateway.removeConfig();
            await timeout(5000); // wait gateway restart after a gateway config change
        });
    });

    function timeout(ms: number) {
        return new Promise<void>(resolve => setTimeout(resolve, ms));
    }
});


text:
'''Create the dmg for MacOS deployment'''

import atexit, copy, glob, os, re, shutil, subprocess, sys, tempfile

thisFolder = os.path.dirname(os.path.realpath(__file__))
sys.path.append(thisFolder)
import dmgbuild

# == defaults

scratchFolder = tempfile.mkdtemp()
uninstallAppName = 'Uninstall RethinkDB.app'

packagePosition = (470, 170)

defaultOptions = {
	'format': 'UDBZ',
	'badge_icon': os.path.join(thisFolder, 'Thinker.icns'),
	'files': [
		os.path.join(thisFolder, os.path.pardir, os.path.pardir, 'COPYRIGHT')
	],
	'icon_size': 64.0,
	'text_size': 14.0,
	'icon_locations': {
		uninstallAppName: (630, 170),
		'Release Notes.url': (470, 303),
		'COPYRIGHT': (630, 303)
	},
	'background': os.path.join(thisFolder, 'dmg_background.png'),
	'window_rect': ((200, 200), (739, 420)),
	'default_view': 'icon-view',
	'show_icon_preview': True
}

# ==

def removeAtExit(removePath):
	if os.path.exists(removePath):
		try:
			if os.path.isfile(removePath):
				os.unlink(removePath)
			elif os.path.isdir(removePath):
				shutil.rmtree(removePath, ignore_errors=True)
		except Exception as e:
			sys.stderr.write('Unable to delete item: %s -- %s\n' % (removePath, str(e)))
atexit.register(removeAtExit, scratchFolder)

identityRegex = re.compile(r'^\s+\d+\) (?P<id>\w{40}) "Developer ID (?P<type>Application|Installer): (?P<name>[^"]+)"')
def getSigningIdentity(signingName, signingType):
	assert signingType in ("Application", "Installer")
	command = ['/usr/bin/security', 'find-identity', '-p', 'macappstore', '-v']
	process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	output, _ = process.communicate()
	if process.returncode != 0:
	   raise subprocess.CalledProcessError(process.returncode, command)
	for line in output.splitlines():
		res = identityRegex.match(line)
		if res and res.group('type') == signingType and res.group('name') == signingName:
			return res.group('id')
	else:
		raise ValueError('Could not find the requested signingName: "%s" for type: "%s"\n%s' % (signingName, signingType, output))

def compileUninstallApp(signingName=None):
	outputPath = os.path.join(scratchFolder, uninstallAppName)

	# - compile the app

	logFile = open(os.path.join(scratchFolder, 'uninstall-compile.log'), 'w+')
	try:
		subprocess.check_call(['/usr/bin/osacompile', '-o', outputPath, os.path.join(thisFolder, 'uninstall.scpt')], stdout=logFile, stderr=logFile)
	except Exception as e:
		logFile.seek(0)
		sys.stderr.write('Failed while compiling %s: %s\n%s' % (uninstallAppName, str(e), logFile.read()))
		raise

	# - change the icon - ToDo: re-do this once an icon is chosen

	#iconPath = os.path.join(outputPath, 'Contents', 'Resources', 'applet.icns')
	#os.unlink(iconPath)
	#os.symlink('/System/Library/CoreServices/CoreTypes.bundle/Contents/Resources/Unsupported.icns', iconPath)

	# - codesign

	if signingName is not None:
		signingIdentity = getSigningIdentity(signingName, 'Application')
		try:
			subprocess.check_call(['/usr/bin/codesign', '-s', signingIdentity, outputPath], stdout=logFile, stderr=logFile)
		except Exception as e:
			logFile.seek(0)
			sys.stderr.write('Failed while signing %s: %s\n%s' % (uninstallAppName, str(e), logFile.read()))
			raise

	# -

	return outputPath

def makeReleaseNotesLink(version):
	notesPath = os.path.join(scratchFolder, 'Release Notes.url')
	with open(notesPath, 'w') as outputFile:
		outputFile.write('[InternetShortcut]\nURL=https://github.com/rethinkdb/rethinkdb/releases/tag/v%s\n' % version)
	return notesPath

def buildPackage(versionString, serverRootPath, installPath=None, signingName=None):
	'''Generate a .pkg with all of our customizations'''

	# == build the component packages

	# - make the server package

	packageFolder = os.path.join(scratchFolder, 'packages')
	if not os.path.isdir(packageFolder):
		os.mkdir(packageFolder)

	serverPackagePath = os.path.join(packageFolder, 'rethinkdb_server.pkg')
	logFile = open(os.path.join(scratchFolder, 'rethinkdb_server_pkg.log'), 'w+')

	pkgCommand = ['/usr/bin/pkgbuild', serverPackagePath, '--root', serverRootPath, '--identifier', 'com.rethinkdb.server', '--version', versionString]
	if installPath:
		pkgCommand += ['--install-location', str(installPath)]

	try:
		subprocess.check_call(pkgCommand, stdout=logFile, stderr=logFile)
	except Exception as e:
		logFile.seek(0)
		sys.stderr.write('Failed while building server package: %s\n%s' % (str(e), logFile.read()))
		raise

	# - installer_resources

	installerResourcesPath = os.path.join(scratchFolder, 'installer_resources')
	os.mkdir(installerResourcesPath)
	logFile = open(os.path.join(scratchFolder, 'installer_background-assemble.log'), 'w+')
	try:
		subprocess.check_call(
			['/usr/bin/tiffutil',
			'-cathidpicheck'] + glob.glob(os.path.join(thisFolder, 'installer_resources', 'installer_background*.png')) +
			['-out', os.path.join(installerResourcesPath, 'installer_background.tiff')],
			stdout=logFile, stderr=subprocess.STDOUT
		)
	except Exception as e:
		logFile.seek(0)
		sys.stderr.write('Failed while building installer background: %s\n%s' % (str(e), logFile.read()))
		raise

	# == assemble the archive

	distributionPath = os.path.join(scratchFolder, 'rethinkdb-%s.pkg' % versionString)

	productBuildCommand = [
		'/usr/bin/productbuild',
		'--distribution', os.path.join(thisFolder, 'Distribution.xml'),
		'--package-path', packageFolder,
		'--resources', installerResourcesPath,
		distributionPath
	]

	if signingName is not None:
		signingIdentity = getSigningIdentity(signingName, 'Installer')
		productBuildCommand += ['--sign', signingIdentity]

	logFile = open(os.path.join(scratchFolder, 'rethinkdb_pkg.log'), 'w+')
	try:
		subprocess.check_call(productBuildCommand, stdout=logFile, stderr=logFile)
	except Exception as e:
		logFile.seek(0)
		sys.stderr.write('Failed while compiling %s: %s\n%s' % (os.path.join(thisFolder, 'uninstall.scpt'), str(e), logFile.read()))
		raise
	return distributionPath

def main():
	'''Parse command line input and run'''

	global scratchFolder

	# == process input

	import optparse
	parser = optparse.OptionParser()
	parser.add_option('-s', '--server-root',     dest='serverRoot',    default=None,        help='path to the server component')
	parser.add_option('-i', '--install-path',    dest='installPath',   default=None,        help='path to install to')
	parser.add_option('-o', '--ouptut-location', dest='outputPath',                         help='location for the output file')
	parser.add_option(      '--rethinkdb-name',  dest='binaryName',    default='rethinkdb', help='name of the rethinkdb server binary')
	parser.add_option(      '--signing-name',    dest='signingName',   default=None,        help='signing identifier')
	parser.add_option(      '--scratch-folder',  dest='scratchFolder', default=None,        help='folder for intermediate products')
	options, args = parser.parse_args()

	if len(args) > 0:
		parser.error('no non-keyword options are allowed')

	# = -s/--server-root

	if options.serverRoot is None:
		parser.error('-s/--server-root is required')
	if not os.path.isdir(options.serverRoot):
		parser.error('-s/--server-root must be a folder: %s' % options.serverRoot)
	options.serverRoot = os.path.realpath(options.serverRoot)

	# = get the version of rethinkdb

	# find the binary

	rethinkdbPath = os.path.join(options.serverRoot, options.binaryName)
	if not os.access(rethinkdbPath, os.X_OK):
		parser.error('No runnable RethinkDB executable at: %s' % rethinkdbPath)

	# get the version string

	versionString = ''
	try:
        command = [rethinkdbPath, '--version']
        process = subprocess.Popen(command, shell=shell, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        output, _ = process.communicate()
        if process.returncode != 0:
            raise Exception()
		versionString = output.strip().split()[1].decode('utf-8')
	except Exception as e:
		print(e)
        parser.error('the executable given is not a valid RethinkDB executable: %s' % rethinkdbPath)

	strictVersion = re.match('^(\d+\.?)+(-\d+)?', versionString)
	if strictVersion is None:
		parser.error('version string from executable does not have a regular version string: %s' % versionString)
	strictVersion = strictVersion.group()

	# = -o/--ouptut-location

	if options.outputPath is None:
		options.outputPath = os.path.join(thisFolder, 'RethinkDB ' + versionString + '.dmg')
	elif os.path.isdir(options.outputPath):
		options.outputPath = os.path.join(options.outputPath, 'RethinkDB ' + versionString + '.dmg')
	elif not os.path.isdir(os.path.dirname(options.outputPath)):
		parser.error('the output path given is not valid: %s' % options.outputPath)

	# = --scratch-folder

	if options.scratchFolder is not None:
		options.scratchFolder = os.path.realpath(options.scratchFolder)
		parentDir = os.path.dirname(options.scratchFolder)
		if not os.path.isdir(parentDir):
			parser.error('The parent folder of --scratch-folder is not an existing folder: %s' % options.scratchFolder)
		if os.path.exists(options.scratchFolder) and not os.path.isdir(options.scratchFolder):
			parser.error('The --scratch-folder is not a folder: %s' % options.scratchFolder)
		elif not os.path.exists(options.scratchFolder):
			os.mkdir(options.scratchFolder)
		scratchFolder = options.scratchFolder

	# == build the pkg

	pkgPath = buildPackage(versionString, options.serverRoot, installPath=options.installPath, signingName=options.signingName)

	# == add dynamic content to settings

	dmgOptions = copy.deepcopy(defaultOptions)

	# = package

	dmgOptions['files'].append(pkgPath)
	dmgOptions['icon_locations'][os.path.basename(pkgPath)] = packagePosition

	# = uninstall script

	uninstallAppPath = compileUninstallApp(signingName=options.signingName)
	dmgOptions['files'].append(uninstallAppPath)

	# = release notes

	dmgOptions['files'].append(makeReleaseNotesLink(strictVersion))

	# == dmg creation

	dmgbuild.build_dmg(options.outputPath, 'RethinkDB ' + versionString, defines=dmgOptions)

if __name__ == '__main__':
	main()

redpajama_set_name: RedPajamaGithub


text:
package org.apache.commons.jrcs.rcs;

import java.util.Iterator;
import java.util.TreeMap;

/**
 * A set of "new phrases" for an Archive.
 * Phrases are keyed lists of symbols. An Archive stores the keys
 * it doesn't recognizes in a Phrases set to preserve them. Unrecognized
 * keys probably belong to archive extensions.
 *
 * @see Archive
 *
 * @author Juanco Anez
 * @version $Id: Phrases.java 145971 2002-05-28 16:45:41Z jvanzyl $
 */
class Phrases
        extends TreeMap
{
    public void toString(StringBuffer s, String EOL)
    {
        Iterator i = keySet().iterator();
        while (i.hasNext())
        {
            String key = i.next().toString();
            String value = get(key).toString();
            s.append(key.toString());
            s.append(" ");
            s.append(value);
            s.append(EOL);
        }
    }

    public String toString()
    {
        StringBuffer s = new StringBuffer();
        toString(s, "\n");
        return s.toString();
    }
}


text:
import org.apache.commons.lang.StringUtils;
import org.wso2.carbon.apimgt.samples.utils.Constants;
import org.wso2.carbon.apimgt.samples.utils.SampleUtils;
import org.wso2.carbon.apimgt.samples.utils.TenantUtils;
import org.wso2.carbon.apimgt.samples.utils.WebAppDeployUtils;
import org.wso2.carbon.apimgt.samples.utils.publisher.rest.client.ApiException;
import org.wso2.carbon.apimgt.samples.utils.publisher.rest.client.ApiResponse;
import org.wso2.carbon.apimgt.samples.utils.publisher.rest.client.model.API;

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

/**
 * This class is used to populate sample data to represent the sample eight business scenario.
 */
public class CreateSampleEightRawData {

    private static final String hostname = "localhost";
    private static final String port = "9443";
    private static final String serviceEndpoint = "https://" + hostname + ":" + port + "/services/";
    private static final String warFileName = "sample-data-backend";
    private static final String warFileLocation =
            System.getProperty("user.dir") + File.separator + "resources" + File.separator + "sample-data-backend.war";
    private static String clientTrustStore =
            System.getProperty("user.dir") + File.separator + ".." + File.separator + "repository" + File.separator
                    + "resources" + File.separator + "security" + File.separator + "client-truststore.jks";

    /**
     * This main method will be called when running sample eight.
     *
     * @throws ApiException throws if an exception is thrown when API creation.
     * @throws IOException  throws when if an error occurred when reading the api definition file.
     */
    public static void main(String[] args) throws ApiException, IOException {

        if (StringUtils.isEmpty(System.getProperty(Constants.JAVAX_NET_SSL_TRUST_STORE))) {
            System.setProperty(Constants.JAVAX_NET_SSL_TRUST_STORE, clientTrustStore);
        }
        if (StringUtils.isEmpty(System.getProperty(Constants.JAVAX_NET_SSL_TRUST_STORE_PASSWORD))) {
            System.setProperty(Constants.JAVAX_NET_SSL_TRUST_STORE_PASSWORD, Constants.WSO2_CARBON);
        }
        if (StringUtils.isEmpty(System.getProperty(Constants.JAVAX_NET_SSL_TRUST_STORE_TYPE))) {
            System.setProperty(Constants.JAVAX_NET_SSL_TRUST_STORE_TYPE, Constants.JKS);
        }

        System.out.println("Deploying sample back end");
        WebAppDeployUtils.deployWebApp(serviceEndpoint, "admin", "admin", warFileLocation, warFileName);

        String oldApiId = SampleUtils
                .createApi("Mobile_stock_API", "1.0.0", "/stocks", new ArrayList<String>(), new ArrayList<String>(),
                        API.SubscriptionAvailabilityEnum.SPECIFIC_TENANTS, hostname, port, new ArrayList<String>());
        SampleUtils.publishAPI(oldApiId);
        SampleUtils.deprecateAPI(oldApiId);

        String newApiId =  SampleUtils.createNewAPIVersion("2.0.0", oldApiId);
        SampleUtils.publishAPI(newApiId);
    }

}


text:
import BaseStore from './BaseStore'

class ConfirmStore extends BaseStore {
    constructor() {
        super()
        this.subscribe(() => this._registerToActions.bind(this))

        this._state = {
            showModal: false,
            message: undefined
        }
    }

    get state() {
        return this._state
    }

    SHOW_CONFIRM(action) {
        this._state.showModal = true
        this._state.message = action.message

        this._state.resolve = (value) => {
            this._state.showModal = false
            this.emitChange()
            action.resolve(value)
        }

        this._state.reject = (error) => {
            this._state.showModal = false
            this.emitChange()
            action.reject(error)
        }

        this.emitChange()
    }

    _registerToActions(action) {
        if (this[action.actionType]) {
            this[action.actionType](action)
        }
    }
}

export default new ConfirmStore()


text:
Edit Template {{ name }}

<form class="form-horizontal">
    <fieldset>

        Name

            <input type="text" class="input-xlarge" id="name" name="name" value="{{ name }}">

        Source

            <textarea class="input-xlarge" style="width: 700px; font-family: courier new" id="source" name="source" rows="20">{{ source }}</textarea>

LaTeX documents are generated using the Razor template engine. Click here learn more about Razor syntax.

        Template File

                <input class="input-file" id="file" name="file" type="file">

        <button type="submit" class="btn btn-primary save">Save</button>
        Cancel

    </fieldset>
    </form>


text:
#include <cstring>

#include "xenia/base/logging.h"
#include "xenia/base/math.h"
#include "xenia/kernel/kernel_state.h"
#include "xenia/kernel/util/shim_utils.h"
#include "xenia/kernel/xboxkrnl_private.h"
#include "xenia/xbox.h"

namespace xe {
namespace kernel {

uint32_t ToXdkProtectFlags(uint32_t protect) {
  uint32_t result = 0;
  if (!(protect & kMemoryProtectRead) && !(protect & kMemoryProtectWrite)) {
    result = X_PAGE_NOACCESS;
  } else if ((protect & kMemoryProtectRead) &&
             !(protect & kMemoryProtectWrite)) {
    result = X_PAGE_READONLY;
  } else {
    result = X_PAGE_READWRITE;
  }
  if (protect & kMemoryProtectNoCache) {
    result = X_PAGE_NOCACHE;
  }
  if (protect & kMemoryProtectWriteCombine) {
    result = X_PAGE_WRITECOMBINE;
  }
  return result;
}

uint32_t FromXdkProtectFlags(uint32_t protect) {
  uint32_t result = 0;
  if ((protect & X_PAGE_READONLY) | (protect & X_PAGE_EXECUTE_READ)) {
    result |= kMemoryProtectRead;
  } else if ((protect & X_PAGE_READWRITE) |
             (protect & X_PAGE_EXECUTE_READWRITE)) {
    result |= kMemoryProtectRead | kMemoryProtectWrite;
  }
  if (protect & X_PAGE_NOCACHE) {
    result |= kMemoryProtectNoCache;
  }
  if (protect & X_PAGE_WRITECOMBINE) {
    result |= kMemoryProtectWriteCombine;
  }
  return result;
}

SHIM_CALL NtAllocateVirtualMemory_shim(PPCContext* ppc_context,
                                       KernelState* kernel_state) {
  uint32_t base_addr_ptr = SHIM_GET_ARG_32(0);
  uint32_t base_addr_value = SHIM_MEM_32(base_addr_ptr);
  uint32_t region_size_ptr = SHIM_GET_ARG_32(1);
  uint32_t region_size_value = SHIM_MEM_32(region_size_ptr);
  uint32_t alloc_type = SHIM_GET_ARG_32(2);    // X_MEM_* bitmask
  uint32_t protect_bits = SHIM_GET_ARG_32(3);  // X_PAGE_* bitmask
  uint32_t unknown = SHIM_GET_ARG_32(4);

  XELOGD("NtAllocateVirtualMemory(%.8X(%.8X), %.8X(%.8X), %.8X, %.8X, %.8X)",
         base_addr_ptr, base_addr_value, region_size_ptr, region_size_value,
         alloc_type, protect_bits, unknown);

  // NTSTATUS
  // _Inout_  PVOID *BaseAddress,
  // _Inout_  PSIZE_T RegionSize,
  // _In_     ULONG AllocationType,
  // _In_     ULONG Protect
  // ? handle?

  // I've only seen zero.
  assert_true(unknown == 0);

  // This allocates memory from the kernel heap, which is initialized on startup
  // and shared by both the kernel implementation and user code.
  // The xe_memory_ref object is used to actually get the memory, and although
  // it's simple today we could extend it to do better things in the future.

  // Must request a size.
  if (!region_size_value) {
    SHIM_SET_RETURN_32(X_STATUS_INVALID_PARAMETER);
    return;
  }
  // Check allocation type.
  if (!(alloc_type & (X_MEM_COMMIT | X_MEM_RESET | X_MEM_RESERVE))) {
    SHIM_SET_RETURN_32(X_STATUS_INVALID_PARAMETER);
    return;
  }
  // If MEM_RESET is set only MEM_RESET can be set.
  if (alloc_type & X_MEM_RESET && (alloc_type & ~X_MEM_RESET)) {
    SHIM_SET_RETURN_32(X_STATUS_INVALID_PARAMETER);
    return;
  }
  // Don't allow games to set execute bits.
  if (protect_bits & (X_PAGE_EXECUTE | X_PAGE_EXECUTE_READ |
                      X_PAGE_EXECUTE_READWRITE | X_PAGE_EXECUTE_WRITECOPY)) {
    XELOGW("Game setting EXECUTE bit on allocation");
  }

  // Adjust size.
  uint32_t page_size = 4096;
  if (alloc_type & X_MEM_LARGE_PAGES) {
    page_size = 64 * 1024;
  }
  if (int32_t(region_size_value) < 0) {
    // Some games pass in negative sizes.
    region_size_value = -int32_t(region_size_value);
  }
  uint32_t adjusted_size = xe::round_up(region_size_value, page_size);

  // Allocate.
  uint32_t allocation_type = 0;
  if (alloc_type & X_MEM_RESERVE) {
    allocation_type |= kMemoryAllocationReserve;
  }
  if (alloc_type & X_MEM_COMMIT) {
    allocation_type |= kMemoryAllocationCommit;
  }
  if (alloc_type & X_MEM_RESET) {
    XELOGE("X_MEM_RESET not implemented");
    assert_always();
  }
  uint32_t protect = FromXdkProtectFlags(protect_bits);
  uint32_t address = 0;
  if (base_addr_value) {
    auto heap = kernel_state->memory()->LookupHeap(base_addr_value);
    if (heap->AllocFixed(base_addr_value, adjusted_size, page_size,
                         allocation_type, protect)) {
      address = base_addr_value;
    }
  } else {
    bool top_down = !!(alloc_type & X_MEM_TOP_DOWN);
    auto heap = kernel_state->memory()->LookupHeapByType(false, page_size);
    heap->Alloc(adjusted_size, page_size, allocation_type, protect, top_down,
                &address);
  }
  if (!address) {
    // Failed - assume no memory available.
    SHIM_SET_RETURN_32(X_STATUS_NO_MEMORY);
    return;
  }

  // Zero memory, if needed.
  if (address && !(alloc_type & X_MEM_NOZERO)) {
    if (alloc_type & X_MEM_COMMIT) {
      kernel_state->memory()->Zero(address, adjusted_size);
    }
  }

  XELOGD("NtAllocateVirtualMemory = %.8X", address);

  // Stash back.
  // Maybe set X_STATUS_ALREADY_COMMITTED if MEM_COMMIT?
  SHIM_SET_MEM_32(base_addr_ptr, address);
  SHIM_SET_MEM_32(region_size_ptr, adjusted_size);
  SHIM_SET_RETURN_32(X_STATUS_SUCCESS);
}

SHIM_CALL NtFreeVirtualMemory_shim(PPCContext* ppc_context,
                                   KernelState* kernel_state) {
  uint32_t base_addr_ptr = SHIM_GET_ARG_32(0);
  uint32_t base_addr_value = SHIM_MEM_32(base_addr_ptr);
  uint32_t region_size_ptr = SHIM_GET_ARG_32(1);
  uint32_t region_size_value = SHIM_MEM_32(region_size_ptr);
  // X_MEM_DECOMMIT | X_MEM_RELEASE
  uint32_t free_type = SHIM_GET_ARG_32(2);
  uint32_t unknown = SHIM_GET_ARG_32(3);

  XELOGD("NtFreeVirtualMemory(%.8X(%.8X), %.8X(%.8X), %.8X, %.8X)",
         base_addr_ptr, base_addr_value, region_size_ptr, region_size_value,
         free_type, unknown);

  // NTSTATUS
  // _Inout_  PVOID *BaseAddress,
  // _Inout_  PSIZE_T RegionSize,
  // _In_     ULONG FreeType
  // ? handle?

  // I've only seen zero.
  assert_true(unknown == 0);

  if (!base_addr_value) {
    SHIM_SET_RETURN_32(X_STATUS_MEMORY_NOT_ALLOCATED);
    return;
  }

  auto heap = kernel_state->memory()->LookupHeap(base_addr_value);
  bool result = false;
  if (free_type == X_MEM_DECOMMIT) {
    // If zero, we may need to query size (free whole region).
    assert_not_zero(region_size_value);

    region_size_value = xe::round_up(region_size_value, heap->page_size());
    result = heap->Decommit(base_addr_value, region_size_value);
  } else {
    result = heap->Release(base_addr_value, &region_size_value);
  }
  if (!result) {
    SHIM_SET_RETURN_32(X_STATUS_UNSUCCESSFUL);
    return;
  }

  SHIM_SET_MEM_32(base_addr_ptr, base_addr_value);
  SHIM_SET_MEM_32(region_size_ptr, region_size_value);
  SHIM_SET_RETURN_32(X_STATUS_SUCCESS);
}

struct X_MEMORY_BASIC_INFORMATION {
  be<uint32_t> base_address;
  be<uint32_t> allocation_base;
  be<uint32_t> allocation_protect;
  be<uint32_t> region_size;
  be<uint32_t> state;
  be<uint32_t> protect;
  be<uint32_t> type;
};

SHIM_CALL NtQueryVirtualMemory_shim(PPCContext* ppc_context,
                                    KernelState* kernel_state) {
  uint32_t base_address = SHIM_GET_ARG_32(0);
  uint32_t memory_basic_information_ptr = SHIM_GET_ARG_32(1);
  auto memory_basic_information =
      SHIM_STRUCT(X_MEMORY_BASIC_INFORMATION, memory_basic_information_ptr);

  XELOGD("NtQueryVirtualMemory(%.8X, %.8X)", base_address,
         memory_basic_information_ptr);

  auto heap = kernel_state->memory()->LookupHeap(base_address);
  HeapAllocationInfo alloc_info;
  if (heap == nullptr || !heap->QueryRegionInfo(base_address, &alloc_info)) {
    SHIM_SET_RETURN_32(X_STATUS_INVALID_PARAMETER);
    return;
  }

  memory_basic_information->base_address =
      static_cast<uint32_t>(alloc_info.base_address);
  memory_basic_information->allocation_base =
      static_cast<uint32_t>(alloc_info.allocation_base);
  memory_basic_information->allocation_protect =
      ToXdkProtectFlags(alloc_info.allocation_protect);
  memory_basic_information->region_size =
      static_cast<uint32_t>(alloc_info.region_size);
  uint32_t x_state = 0;
  if (alloc_info.state & kMemoryAllocationReserve) {
    x_state |= X_MEM_RESERVE;
  }
  if (alloc_info.state & kMemoryAllocationCommit) {
    x_state |= X_MEM_COMMIT;
  }
  memory_basic_information->state = x_state;
  memory_basic_information->protect = ToXdkProtectFlags(alloc_info.protect);
  memory_basic_information->type = alloc_info.type;

  SHIM_SET_RETURN_32(X_STATUS_SUCCESS);
}

SHIM_CALL MmAllocatePhysicalMemoryEx_shim(PPCContext* ppc_context,
                                          KernelState* kernel_state) {
  uint32_t type = SHIM_GET_ARG_32(0);
  uint32_t region_size = SHIM_GET_ARG_32(1);
  uint32_t protect_bits = SHIM_GET_ARG_32(2);
  uint32_t min_addr_range = SHIM_GET_ARG_32(3);
  uint32_t max_addr_range = SHIM_GET_ARG_32(4);
  uint32_t alignment = SHIM_GET_ARG_32(5);

  XELOGD("MmAllocatePhysicalMemoryEx(%d, %.8X, %.8X, %.8X, %.8X, %.8X)", type,
         region_size, protect_bits, min_addr_range, max_addr_range, alignment);

  // Type will usually be 0 (user request?), where 1 and 2 are sometimes made
  // by D3D/etc.

  // Check protection bits.
  if (!(protect_bits & (X_PAGE_READONLY | X_PAGE_READWRITE))) {
    XELOGE("MmAllocatePhysicalMemoryEx: bad protection bits");
    SHIM_SET_RETURN_32(0);
    return;
  }

  // Either may be OR'ed into protect_bits:
  // X_PAGE_NOCACHE
  // X_PAGE_WRITECOMBINE
  // We could use this to detect what's likely GPU-synchronized memory
  // and let the GPU know we're messing with it (or even allocate from
  // the GPU). At least the D3D command buffer is X_PAGE_WRITECOMBINE.

  // Calculate page size.
  // Default            = 4KB
  // X_MEM_LARGE_PAGES  = 64KB
  // X_MEM_16MB_PAGES   = 16MB
  uint32_t page_size = 4 * 1024;
  if (protect_bits & X_MEM_LARGE_PAGES) {
    page_size = 64 * 1024;
  } else if (protect_bits & X_MEM_16MB_PAGES) {
    page_size = 16 * 1024 * 1024;
  }

  // Round up the region size and alignment to the next page.
  uint32_t adjusted_size = xe::round_up(region_size, page_size);
  uint32_t adjusted_alignment = xe::round_up(alignment, page_size);

  // Callers can pick an address to allocate with min_addr_range/max_addr_range
  // and the memory must be allocated there. I haven't seen a game do this,
  // and instead they all do min=0 / max=-1 to indicate the system should pick.
  // If we have to suport arbitrary placement things will get nasty.

  uint32_t allocation_type = kMemoryAllocationReserve | kMemoryAllocationCommit;
  uint32_t protect = FromXdkProtectFlags(protect_bits);
  bool top_down = true;
  auto heap = kernel_state->memory()->LookupHeapByType(true, page_size);
  uint32_t base_address;
  if (!heap->AllocRange(min_addr_range, max_addr_range, adjusted_size,
                        adjusted_alignment, allocation_type, protect, top_down,
                        &base_address)) {
    // Failed - assume no memory available.
    SHIM_SET_RETURN_32(0);
    return;
  }
  XELOGD("MmAllocatePhysicalMemoryEx = %.8X", base_address);

  SHIM_SET_RETURN_32(base_address);
}

SHIM_CALL MmFreePhysicalMemory_shim(PPCContext* ppc_context,
                                    KernelState* kernel_state) {
  uint32_t type = SHIM_GET_ARG_32(0);
  uint32_t base_address = SHIM_GET_ARG_32(1);

  XELOGD("MmFreePhysicalAddress(%d, %.8X)", type, base_address);

  // base_address = result of MmAllocatePhysicalMemory.

  assert_true((base_address & 0x1F) == 0);

  auto heap = kernel_state->memory()->LookupHeap(base_address);
  heap->Release(base_address);
}

SHIM_CALL MmQueryAddressProtect_shim(PPCContext* ppc_context,
                                     KernelState* kernel_state) {
  uint32_t base_address = SHIM_GET_ARG_32(0);

  XELOGD("MmQueryAddressProtect(%.8X)", base_address);

  auto heap = kernel_state->memory()->LookupHeap(base_address);
  uint32_t access;
  if (!heap->QueryProtect(base_address, &access)) {
    access = 0;
  }
  access = ToXdkProtectFlags(access);

  SHIM_SET_RETURN_32(access);
}

void MmSetAddressProtect(lpvoid_t base_address, dword_t region_size,
                         dword_t protect_bits) {
  uint32_t protect = FromXdkProtectFlags(protect_bits);
  auto heap = kernel_memory()->LookupHeap(base_address);
  heap->Protect(base_address.guest_address(), region_size, protect);
}
DECLARE_XBOXKRNL_EXPORT(MmSetAddressProtect, ExportTag::kMemory);

SHIM_CALL MmQueryAllocationSize_shim(PPCContext* ppc_context,
                                     KernelState* kernel_state) {
  uint32_t base_address = SHIM_GET_ARG_32(0);

  XELOGD("MmQueryAllocationSize(%.8X)", base_address);

  auto heap = kernel_state->memory()->LookupHeap(base_address);
  uint32_t size;
  if (!heap->QuerySize(base_address, &size)) {
    size = 0;
  }

  SHIM_SET_RETURN_32(size);
}

// https://code.google.com/p/vdash/source/browse/trunk/vdash/include/kernel.h
struct X_MM_QUERY_STATISTICS_SECTION {
  xe::be<uint32_t> available_pages;
  xe::be<uint32_t> total_virtual_memory_bytes;
  xe::be<uint32_t> reserved_virtual_memory_bytes;
  xe::be<uint32_t> physical_pages;
  xe::be<uint32_t> pool_pages;
  xe::be<uint32_t> stack_pages;
  xe::be<uint32_t> image_pages;
  xe::be<uint32_t> heap_pages;
  xe::be<uint32_t> virtual_pages;
  xe::be<uint32_t> page_table_pages;
  xe::be<uint32_t> cache_pages;
};

struct X_MM_QUERY_STATISTICS_RESULT {
  xe::be<uint32_t> size;
  xe::be<uint32_t> total_physical_pages;
  xe::be<uint32_t> kernel_pages;
  X_MM_QUERY_STATISTICS_SECTION title;
  X_MM_QUERY_STATISTICS_SECTION system;
  xe::be<uint32_t> highest_physical_page;
};
static_assert_size(X_MM_QUERY_STATISTICS_RESULT, 104);

SHIM_CALL MmQueryStatistics_shim(PPCContext* ppc_context,
                                 KernelState* kernel_state) {
  uint32_t stats_ptr = SHIM_GET_ARG_32(0);

  XELOGD("MmQueryStatistics(%.8X)", stats_ptr);

  if (stats_ptr == 0) {
    SHIM_SET_RETURN_32(X_STATUS_INVALID_PARAMETER);
    return;
  }

  const uint32_t size = sizeof(X_MM_QUERY_STATISTICS_RESULT);

  auto stats = (X_MM_QUERY_STATISTICS_RESULT*)SHIM_MEM_ADDR(stats_ptr);
  if (stats->size != size) {
    SHIM_SET_RETURN_32(X_STATUS_BUFFER_TOO_SMALL);
    return;
  }

  // Zero out the struct.
  std::memset(stats, 0, size);

  // Set the constants the game is likely asking for.
  // These numbers are mostly guessed. If the game is just checking for
  // memory, this should satisfy it. If it's actually verifying things
  // this won't work :/
  stats->size = size;

  stats->total_physical_pages = 0x00020000;
  stats->kernel_pages = 0x00000300;

  stats->title.available_pages = 0x00013300;
  stats->title.total_virtual_memory_bytes = 0x2FFF0000;
  stats->title.reserved_virtual_memory_bytes = 0x00160000;
  stats->title.physical_pages = 0x00001000;
  stats->title.pool_pages = 0x00000010;
  stats->title.stack_pages = 0x00000100;
  stats->title.image_pages = 0x00000100;
  stats->title.heap_pages = 0x00000100;
  stats->title.virtual_pages = 0x00000100;
  stats->title.page_table_pages = 0x00000100;
  stats->title.cache_pages = 0x00000100;

  stats->system.available_pages = 0x00000000;
  stats->system.total_virtual_memory_bytes = 0x00000000;
  stats->system.reserved_virtual_memory_bytes = 0x00000000;
  stats->system.physical_pages = 0x00000000;
  stats->system.pool_pages = 0x00000000;
  stats->system.stack_pages = 0x00000000;
  stats->system.image_pages = 0x00000000;
  stats->system.heap_pages = 0x00000000;
  stats->system.virtual_pages = 0x00000000;
  stats->system.page_table_pages = 0x00000000;
  stats->system.cache_pages = 0x00000000;

  stats->highest_physical_page = 0x0001FFFF;

  SHIM_SET_RETURN_32(X_STATUS_SUCCESS);
}

// http://msdn.microsoft.com/en-us/library/windows/hardware/ff554547(v=vs.85).aspx
SHIM_CALL MmGetPhysicalAddress_shim(PPCContext* ppc_context,
                                    KernelState* kernel_state) {
  uint32_t base_address = SHIM_GET_ARG_32(0);

  XELOGD("MmGetPhysicalAddress(%.8X)", base_address);

  // PHYSICAL_ADDRESS MmGetPhysicalAddress(
  //   _In_  PVOID BaseAddress
  // );
  // base_address = result of MmAllocatePhysicalMemory.

  uint32_t physical_address = base_address & 0x1FFFFFFF;
  if (base_address >= 0xE0000000) {
    physical_address += 0x1000;
  }

  SHIM_SET_RETURN_32(physical_address);
}

SHIM_CALL MmMapIoSpace_shim(PPCContext* ppc_context,
                            KernelState* kernel_state) {
  uint32_t unk0 = SHIM_GET_ARG_32(0);
  uint32_t src_address = SHIM_GET_ARG_32(1);  // from MmGetPhysicalAddress
  uint32_t size = SHIM_GET_ARG_32(2);
  uint32_t flags = SHIM_GET_ARG_32(3);

  XELOGD("MmMapIoSpace(%.8X, %.8X, %d, %.8X)", unk0, src_address, size, flags);

  // I've only seen this used to map XMA audio contexts.
  // The code seems fine with taking the src address, so this just returns that.
  // If others start using it there could be problems.
  assert_true(unk0 == 2);
  assert_true(size == 0x40);
  assert_true(flags == 0x404);

  SHIM_SET_RETURN_32(src_address);
}

SHIM_CALL ExAllocatePoolTypeWithTag_shim(PPCContext* ppc_context,
                                         KernelState* kernel_state) {
  uint32_t size = SHIM_GET_ARG_32(0);
  uint32_t tag = SHIM_GET_ARG_32(1);
  uint32_t zero = SHIM_GET_ARG_32(2);

  XELOGD("ExAllocatePoolTypeWithTag(%d, %.8X, %d)", size, tag, zero);

  uint32_t alignment = 8;
  uint32_t adjusted_size = size;
  if (adjusted_size < 4 * 1024) {
    adjusted_size = xe::round_up(adjusted_size, 4 * 1024);
  } else {
    alignment = 4 * 1024;
  }

  uint32_t addr =
      kernel_state->memory()->SystemHeapAlloc(adjusted_size, alignment);

  SHIM_SET_RETURN_32(addr);
}

SHIM_CALL ExFreePool_shim(PPCContext* ppc_context, KernelState* kernel_state) {
  uint32_t base_address = SHIM_GET_ARG_32(0);

  XELOGD("ExFreePool(%.8X)", base_address);

  kernel_state->memory()->SystemHeapFree(base_address);
}

SHIM_CALL KeLockL2_shim(PPCContext* ppc_context, KernelState* kernel_state) {
  // Ignored for now. This is just a perf optimization, I think.
  // It may be useful as a hint for CPU-GPU transfer.

  XELOGD("KeLockL2(?)");

  SHIM_SET_RETURN_32(0);
}

SHIM_CALL KeUnlockL2_shim(PPCContext* ppc_context, KernelState* kernel_state) {
  XELOGD("KeUnlockL2(?)");
}

SHIM_CALL MmCreateKernelStack_shim(PPCContext* ppc_context,
                                   KernelState* kernel_state) {
  auto stack_size = SHIM_GET_ARG_32(0);
  auto unk1 = SHIM_GET_ARG_32(1);

  XELOGD("MmCreateKernelStack(%.8X, %.8X)", stack_size, unk1);

  stack_size = (stack_size + 0xFFF) & 0xFFFFF000;
  uint32_t stack_alignment = (stack_size & 0xF000) ? 0x1000 : 0x10000;

  uint32_t stack_address;
  kernel_state->memory()
      ->LookupHeap(0x70000000)
      ->AllocRange(0x70000000, 0x7FFFFFFF, stack_size, stack_alignment,
                   kMemoryAllocationReserve | kMemoryAllocationCommit,
                   kMemoryProtectRead | kMemoryProtectWrite, false,
                   &stack_address);
  SHIM_SET_RETURN_32(stack_address + stack_size);
}

SHIM_CALL MmDeleteKernelStack_shim(PPCContext* ppc_context,
                                   KernelState* kernel_state) {
  auto unk0 = SHIM_GET_ARG_32(0);
  auto unk1 = SHIM_GET_ARG_32(1);

  XELOGD("MmDeleteKernelStack(%.8X, %.8X)", unk0, unk1);

  assert_always();
  SHIM_SET_RETURN_32(0);
}

}  // namespace kernel
}  // namespace xe

void xe::kernel::xboxkrnl::RegisterMemoryExports(
    xe::cpu::ExportResolver* export_resolver, KernelState* kernel_state) {
  SHIM_SET_MAPPING("xboxkrnl.exe", NtAllocateVirtualMemory, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", NtFreeVirtualMemory, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", NtQueryVirtualMemory, state);
  // SHIM_SET_MAPPING("xboxkrnl.exe", MmAllocatePhysicalMemory, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmAllocatePhysicalMemoryEx, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmFreePhysicalMemory, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmQueryAddressProtect, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmQueryAllocationSize, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmQueryStatistics, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmGetPhysicalAddress, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmMapIoSpace, state);

  SHIM_SET_MAPPING("xboxkrnl.exe", ExAllocatePoolTypeWithTag, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", ExFreePool, state);

  SHIM_SET_MAPPING("xboxkrnl.exe", KeLockL2, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", KeUnlockL2, state);

  SHIM_SET_MAPPING("xboxkrnl.exe", MmCreateKernelStack, state);
  SHIM_SET_MAPPING("xboxkrnl.exe", MmDeleteKernelStack, state);
}


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/background_repeat"
    android:descendantFocusability="beforeDescendants"
    android:focusableInTouchMode="true"
    android:orientation="vertical"
    android:padding="5dip"
    tools:context=".CharacterActivity" >

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
        <fragment
            android:name="br.augustoicaro.pathfindercombat.CharacterInfoFragment"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            tools:layout="@layout/character_info" />

        <fragment
            android:name="br.augustoicaro.pathfindercombat.CharacterCombatFragment"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            tools:layout="@layout/character_combat" />
    </LinearLayout>

</ScrollView>


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace UIDemos.Attributes
{
	[AttributeUsage(AttributeTargets.Property)]
	public class PastDateOnlyAttribute : ValidationAttribute, IClientValidatable
	{
		private const string DefaultErrorMessage = "Date must be earlier than today.";

		public override string FormatErrorMessage(string name)
		{
			return DefaultErrorMessage;
		}

		protected override ValidationResult IsValid(object value, ValidationContext validationContext)
		{
			if (value == null) return ValidationResult.Success;

			var now = DateTime.Now.Date;
			var dte = (DateTime)value;

			return now <= dte ? new ValidationResult(FormatErrorMessage(validationContext.DisplayName)) : ValidationResult.Success;
		}

		public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
		{
			var rule = new ModelClientValidationPastDateOnlyRule(FormatErrorMessage(metadata.GetDisplayName()));

			yield return rule;
		}
	}

	public class ModelClientValidationPastDateOnlyRule : ModelClientValidationRule
	{
		private const string PastOnlyValidateType = "pastdateonly";
		private const string MaxDate = "maxdate";

		public ModelClientValidationPastDateOnlyRule(
				string errorMessage)
		{
			ValidationType = PastOnlyValidateType;
			ErrorMessage = errorMessage;
			ValidationParameters.Add(MaxDate, DateTime.Now.Date.ToShortDateString());
		}
	}
}


text:
label > input{ /* HIDE RADIO */
    visibility: hidden; /* Makes input not-clickable */
    position: absolute; /* Remove input from document flow */
}
label > input + img{ /* IMAGE STYLES */
    cursor:pointer;
    border:2px solid transparent;
}
label > input:checked + img{ /* (RADIO CHECKED) IMAGE STYLES */
    height: 80px;

}

.starRating {
    height: 49px;
    width: auto;
}

#uppderDiv {
    margin-bottom: 35px;
}

#lowerDiv {
    margin-bottom: 15px;
}

#labelTitle{
    margin-top: 20px;
}

#labelTextArea {
    margin-top: 20px;
}

#addReviewButton {
    margin-bottom: 50px;
}


text:
<?php

require_once('../includes/base.php');
require_once('../database/Cabimentacoes.php');
require_once('../database/Centrocustos.php');
require_once('../database/Atividades.php');
require_once('../database/Funcionarios.php');

// check privileges
if ($s_user == NULL) {
  $_SESSION["s_errors"]["generic"][] = 'Não tem permissões';
  header("Location: list.php");
  die;
}

if ($s_values)
  $smarty->assign("cabimentacao1", $s_values);

if ($s_type != "user") {
	$centrocustos = Centrocustos::getAll();
	$atividades = Atividades::getAll();
	$funcionarios = Funcionarios::listEmployees();
}
else {
	$centrocustos = Centrocustos::getAllCCFuncionario((int) $_SESSION["s_user_id"]);
	$atividades = Atividades::getAllActivityFuncionario((int) $_SESSION["s_user_id"]);
	$funcionarios = (int) $_SESSION["s_user_id"];
}

$smarty->assign("centrocustos", $centrocustos);
$smarty->assign("atividades", $atividades);
$smarty->assign("funcionarios", $funcionarios);

$smarty->display('cabimentacoes/insert.tpl');

?>


text:
package sippy

import (
    "sippy/sdp"
    "sippy/types"
)

type SdpSession struct {
    last_origin *sippy_sdp.SdpOrigin
    origin      *sippy_sdp.SdpOrigin
}

func NewSdpSession() *SdpSession {
    return &SdpSession{
        origin      : sippy_sdp.NewSdpOrigin(),
    }
}

func (self *SdpSession) FixupVersion(body sippy_types.MsgBody) error {
    if body == nil {
        return nil
    }
    sdp, err := body.GetSdp()
    if err != nil {
        return err
    }
    new_origin := sdp.GetOHeader().GetCopy()
    if self.last_origin != nil {
        if self.last_origin.GetSessionId() != new_origin.GetSessionId() ||
                self.last_origin.GetVersion() != new_origin.GetVersion() {
            self.origin.IncVersion()
        }
    }
    self.last_origin = new_origin
    sdp.SetOHeader(self.origin.GetCopy())
    return nil
}


text:
<!DOCTYPE html>

<meta http-equiv="content-type" content="text/html;charset=UTF-8" />

<meta charset="UTF-8" />
<title>Speech Recognition Messages - WeChat Official Account Admin Platform</title>
<meta name="generator" content="MediaWiki 1.17.0" />
<link rel="shortcut icon" href="http://admin.wechat.com/favicon.ico" />
<link rel="search" type="application/opensearchdescription+xml" href="opensearch_desc.php" title="WeChat Official Account Admin Platform (en)" />
<link rel="alternate" type="application/atom+xml" title="WeChat Official Account Admin Platform Atom feed" href="index890f.php?title=Special:RecentChanges&feed=atom" />
<link rel="stylesheet" href="loadeb8e.css?debug=false&lang=en&modules=mediawiki.legacy.commonPrint%2Cshared%7Cskins.vector&only=styles&skin=vector&*" />
<meta name="ResourceLoaderDynamicStyles" content="" />

Speech Recognition Messages
Back

From WeChat Official Account Admin Platform

					Jump to: navigation,
					search

When the speech recognition feature is enabled, WeChat system adds a Recognition field in the XML data package of the pushed audio message each time a user sends audio messages to an official account.
Note: Enabling or disabling the speech recognition feature takes effect immediately for new followers and 24 hours for existing followers. Developers can unfollow and then follow in order to test this feature.
An example of an audio XML packet is shown as below after the speech recognition feature is enabled:

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1357290913</CreateTime>
<MsgType><![CDATA[voice]]></MsgType>
<MediaId><![CDATA[media_id]]></MediaId>
<Format><![CDATA[Format]]></Format>
<Recognition><![CDATA[WeChat Team]]></Recognition>
<MsgId>1234567890123456</MsgId>
</xml>

Parameter Description

Parameter

Description

 ToUserName

 Developer's WeChat ID

 FromUserName

 Unique sender ID (an OpenID)

 CreateTime

 Message creation time (Integer)

 MsgType

 Voice

 MediaID

 An audio message media ID that can call the download API to load the media file

 Format

 Audio format: amr

 Recognition

 Speech recognition result (UTF8)

 MsgID

 Message ID (64 bit integer)

Retrieved from "http://admin.wechat.com/wiki/index.php?title=Speech_Recognition_Messages"

				<form class="searchform">
        <input type="text"   name="search" placeholder="Search Keywords [alt-s]" accesskey="s" class="searchform_text"/>
        <input type="submit" name="fulltext" value="Search" title="Get page with keywords" class="searchform_btn"/>
				</form>

New Developers Guide

Getting Started

Developers Requirements

Basic Support

Access Token

IP Address List

Return Codes

API Call Limits

Transferring Multimedia Files

Receiving Messages

Message Authentication

Common Messages

Event Messages

Speech Recognition Messages

Sending Messages

Callback Messages

Customer Service Messages

Advanced Broadcast Interface

User Management

Group Management API

Name Remarks

User Profile

Follower List

User Location

User Profile via Web

Network Status

User-defined Menu

Create

Query

Delete

Event

Promotion Support

Generating Parametric QR Code

URL Shortening API

Data Statistics

Followers Data

Rich Media Data

User-Sent Messages Data

Callback Data

Wechat JS-SDK

Wechat JS-SDK document

About Tencent |

 Service Terms |

Contact Us

Copyright © 2012-2015 Tencent. All Rights Reserved.


text:
			Function(treeNode)zTreeObj.hideNode

			Overview[ depends on jquery.ztree.exhide js ]

To hide any node.

1. This feature can't support the
					'exedit' feature, so please don't use this feature in edit mode.

2. If you hide or show the nodes, it
					will effect the 'isFirstNode' and 'isLastNode' attribute.

3. Please use zTree object to executing
					the method.

Function Parameter Descriptions

				treeNodeJSON

JSON data object of the node which will be hidden

Please ensure that this data object is
				an internal node data object in zTree.

				Retrun none

no return value

Examples of function

1. hide the first root node.

			var treeObj = $.fn.zTree.getZTreeObj("tree");
var nodes = treeObj.getNodes();
treeObj.hideNode(nodes[0]);


text:
#ifndef _ATSPI_DEVICE_LISTENER_PRIVATE_H_
#define _ATSPI_DEVICE_LISTENER_PRIVATE_H_

#include "atspi-device-listener.h"

#include "dbus/dbus.h"

G_BEGIN_DECLS

DBusHandlerResult _atspi_dbus_handle_DeviceEvent (DBusConnection *bus, DBusMessage *message, void *data);

gchar *_atspi_device_listener_get_path (AtspiDeviceListener *listener);

G_END_DECLS

#endif	/* _ATSPI_DEVICE_LISTENER_H_ */


text:
package com.github.missioncriticalcloud.cosmic.metricscollector.repositories;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.List;

import com.github.missioncriticalcloud.cosmic.usage.core.model.Metric;

abstract class MetricsRepositoryIT {

    void assertMetrics(final List<Metric> metrics) {
        assertThat(metrics).isNotNull();
        assertThat(metrics).isNotEmpty();
        assertThat(metrics).hasSize(1);

        metrics.forEach(metric -> {
            assertThat(metric).isNotNull();
            assertThat(metric.getDomainUuid()).isNotNull();
            assertThat(metric.getResourceUuid()).isNotNull();
            assertThat(metric.getResourceType()).isNotNull();
            assertThat(metric.getTimestamp()).isNotNull();
            assertThat(metric.getPayload()).isNotNull();
            assertThat(metric.getPayload()).isNotEmpty();
        });
    }

    void assertMetricsWithoutPayload(final List<Metric> metrics) {
        assertThat(metrics).isNotNull();
        assertThat(metrics).isNotEmpty();
        assertThat(metrics).hasSize(1);

        metrics.forEach(metric -> {
            assertThat(metric).isNotNull();
            assertThat(metric.getDomainUuid()).isNotNull();
            assertThat(metric.getResourceUuid()).isNotNull();
            assertThat(metric.getResourceType()).isNotNull();
            assertThat(metric.getTimestamp()).isNotNull();
            assertThat(metric.getPayload()).isNotNull();
            assertThat(metric.getPayload()).isEmpty();
        });
    }

}


text:
// DATA_TEMPLATE: empty_table
oTest.fnStart( "oLanguage.sZeroRecords" );

$(document).ready( function () {
	/* Check the default */
	var oTable = $('#example').dataTable( {
		"sAjaxSource": "../../../examples/examples_support/json_source.txt"
	} );
	var oSettings = oTable.fnSettings();

	oTest.fnWaitTest(
		"Zero records language is 'No matching records found' by default",
		null,
		function () { return oSettings.oLanguage.sZeroRecords == "No matching records found"; }
	);

	oTest.fnTest(
		"Text is shown when empty table (after filtering)",
		function () { oTable.fnFilter('nothinghere'); },
		function () { return $('#example tbody tr td')[0].innerHTML == "No matching records found" }
	);

	oTest.fnWaitTest(
		"Zero records language can be defined",
		function () {
			oSession.fnRestore();
			oTable = $('#example').dataTable( {
				"sAjaxSource": "../../../examples/examples_support/json_source.txt",
				"oLanguage": {
					"sZeroRecords": "unit test"
				}
			} );
			oSettings = oTable.fnSettings();
		},
		function () { return oSettings.oLanguage.sZeroRecords == "unit test"; }
	);

	oTest.fnTest(
		"Text is shown when empty table (after filtering)",
		function () { oTable.fnFilter('nothinghere2'); },
		function () { return $('#example tbody tr td')[0].innerHTML == "unit test" }
	);

	oTest.fnComplete();
} );


text:
require "nokogiri"

module Xiami
  module Parser
    class SongHTMLParser
      def initialize(html_content)
        @html_content = html_content
      end

      def parse
        song = Song.new.tap do |song|
          doc = Nokogiri::HTML(@html_content)

          song.name = doc.at_css('#title h1').content.strip

          song.album = Album.new.tap do |album|
            album.id = doc.at_css('#albumCover')['href'].match(/album\/(\d+)/)[1].to_i
            album.name = doc.at_css('#albumCover')['title'].strip
            album.cover_url = doc.at_css('.cdCDcover185')['src']
          end

          song.artist = Artist.new.tap do |artist|
            artist_node = doc.at_css('#albums_info').css('a').select { |a| a['href'] =~ /^\/artist\/(\d+)/ }.first
            if artist_node
              artist.id = artist_node['href'].match(/^\/artist\/(\d+)/)[1].to_i rescue nil
              artist.name = artist_node.content.strip rescue nil
            else
              artist_node = doc.at_css('#albums_info').css('a').select { |a| a['href'] =~ /search/ }.first
              artist.name = artist_node.content.strip rescue nil
            end
          end

          song.temporary_url = nil
        end
      end

      module ClassMethods
        def parse(html_content)
          new(html_content).parse
        end
      end

      class << self; include ClassMethods; end
    end
  end
end


text:
[class^="bremen-"],
[class*=" bremen-"] {
  display: inline-block;
  width: 14px;
  height: 14px;
  margin-top: 1px;
  *margin-right: .3em;
  line-height: 14px;
  vertical-align: text-top;
  background-image: url("../img/bremen-icons.png");
  background-position: 14px 14px;
  background-repeat: no-repeat;
}

.bremen-white,
.nav-pills > .active > a > [class^="bremen-"],
.nav-pills > .active > a > [class*=" bremen-"],
.nav-list > .active > a > [class^="bremen-"],
.nav-list > .active > a > [class*=" bremen-"],
.navbar-inverse .nav > .active > a > [class^="bremen-"],
.navbar-inverse .nav > .active > a > [class*=" bremen-"],
.dropdown-menu > li > a:hover > [class^="bremen-"],
.dropdown-menu > li > a:focus > [class^="bremen-"],
.dropdown-menu > li > a:hover > [class*=" bremen-"],
.dropdown-menu > li > a:focus > [class*=" bremen-"],
.dropdown-menu > .active > a > [class^="bremen-"],
.dropdown-menu > .active > a > [class*=" bremen-"],
.dropdown-submenu:hover > a > [class^="bremen-"],
.dropdown-submenu:focus > a > [class^="bremen-"],
.dropdown-submenu:hover > a > [class*=" bremen-"],
.dropdown-submenu:focus > a > [class*=" bremen-"] {
  background-image: url("../img/bremen-icons.png");
}

.btn-large [class^="bremen-"],
.btn-large [class*=" bremen-"] {
  margin-top: 4px;
}

.btn-small [class^="bremen-"],
.btn-small [class*=" bremen-"] {
  margin-top: 0;
}

.btn-mini [class^="bremen-"],
.btn-mini [class*=" bremen-"] {
  margin-top: -1px;
}

.nav-list [class^="bremen-"],
.nav-list [class*=" bremen-"] {
  margin-right: 2px;
}

.navbar .btn-navbar .bremen-bar {
  display: block;
  width: 18px;
  height: 2px;
  background-color: #f5f5f5;
  -webkit-border-radius: 1px;
     -moz-border-radius: 1px;
          border-radius: 1px;
  -webkit-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25);
     -moz-box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25);
          box-shadow: 0 1px 0 rgba(0, 0, 0, 0.25);
}

.btn-navbar .bremen-bar + .bremen-bar {
  margin-top: 3px;
}

.bremen-address{ background-position: 0 0; width: 16px; height: 16px; }
.bremen-administrative-docs{ background-position: 0 -66px; width: 16px; height: 16px; }
.bremen-advertising{ background-position: 0 -132px; width: 16px; height: 16px; }
.bremen-archives{ background-position: 0 -198px; width: 16px; height: 16px; }
.bremen-attibutes{ background-position: 0 -264px; width: 16px; height: 16px; }
.bremen-bank{ background-position: 0 -330px; width: 16px; height: 16px; }
.bremen-basket{ background-position: 0 -396px; width: 16px; height: 16px; }
.bremen-bestseller{ background-position: 0 -462px; width: 16px; height: 16px; }
.bremen-billing{ background-position: 0 -528px; width: 16px; height: 16px; }
.bremen-bookmark{ background-position: 0 -594px; width: 16px; height: 16px; }
.bremen-brainstorming{ background-position: 0 -660px; width: 16px; height: 16px; }
.bremen-business-contact{ background-position: 0 -726px; width: 16px; height: 16px; }
.bremen-busy{ background-position: 0 -792px; width: 16px; height: 16px; }
.bremen-calendar{ background-position: 0 -858px; width: 16px; height: 16px; }
.bremen-category{ background-position: 0 -924px; width: 16px; height: 16px; }
.bremen-check{ background-position: 0 -990px; width: 16px; height: 16px; }
.bremen-collaboration{ background-position: 0 -1056px; width: 16px; height: 16px; }
.bremen-comment{ background-position: 0 -1122px; width: 16px; height: 16px; }
.bremen-communication{ background-position: 0 -1188px; width: 16px; height: 16px; }
.bremen-config{ background-position: 0 -1254px; width: 16px; height: 16px; }
.bremen-consulting{ background-position: 0 -1320px; width: 16px; height: 16px; }
.bremen-contact{ background-position: 0 -1386px; width: 16px; height: 16px; }
.bremen-cost{ background-position: 0 -1452px; width: 16px; height: 16px; }
.bremen-credit-card{ background-position: 0 -1518px; width: 16px; height: 16px; }
.bremen-credit{ background-position: 0 -1584px; width: 16px; height: 16px; }
.bremen-current-work{ background-position: 0 -1650px; width: 16px; height: 16px; }
.bremen-customers{ background-position: 0 -1716px; width: 16px; height: 16px; }
.bremen-cv{ background-position: 0 -1782px; width: 16px; height: 16px; }
.bremen-database{ background-position: 0 -1848px; width: 16px; height: 16px; }
.bremen-date{ background-position: 0 -1914px; width: 16px; height: 16px; }
.bremen-delicious{ background-position: -66px 0; width: 16px; height: 16px; }
.bremen-document-library{ background-position: -66px -66px; width: 16px; height: 16px; }
.bremen-donate{ background-position: -66px -132px; width: 16px; height: 16px; }
.bremen-drawings{ background-position: -66px -198px; width: 16px; height: 16px; }
.bremen-edit{ background-position: -66px -264px; width: 16px; height: 16px; }
.bremen-email{ background-position: -66px -330px; width: 16px; height: 16px; }
.bremen-featured{ background-position: -66px -396px; width: 16px; height: 16px; }
.bremen-feed{ background-position: -66px -462px; width: 16px; height: 16px; }
.bremen-finished-work{ background-position: -66px -528px; width: 16px; height: 16px; }
.bremen-flag{ background-position: -66px -594px; width: 16px; height: 16px; }
.bremen-folder{ background-position: -66px -660px; width: 16px; height: 16px; }
.bremen-free-for-job{ background-position: -66px -726px; width: 16px; height: 16px; }
.bremen-freelance{ background-position: -66px -792px; width: 16px; height: 16px; }
.bremen-full-time{ background-position: -66px -858px; width: 16px; height: 16px; }
.bremen-future-projects{ background-position: -66px -924px; width: 16px; height: 16px; }
.bremen-graphic-design{ background-position: -66px -990px; width: 16px; height: 16px; }
.bremen-heart{ background-position: -66px -1056px; width: 16px; height: 16px; }
.bremen-hire-me{ background-position: -66px -1122px; width: 16px; height: 16px; }
.bremen-home{ background-position: -66px -1188px; width: 16px; height: 16px; }
.bremen-illustration{ background-position: -66px -1254px; width: 16px; height: 16px; }
.bremen-invoice{ background-position: -66px -1320px; width: 16px; height: 16px; }
.bremen-issue{ background-position: -66px -1386px; width: 16px; height: 16px; }
.bremen-library{ background-position: -66px -1452px; width: 16px; height: 16px; }
.bremen-lightbulb{ background-position: -66px -1518px; width: 16px; height: 16px; }
.bremen-limited-edition{ background-position: -66px -1584px; width: 16px; height: 16px; }
.bremen-link{ background-position: -66px -1650px; width: 16px; height: 16px; }
.bremen-lock{ background-position: -66px -1716px; width: 16px; height: 16px; }
.bremen-login{ background-position: -66px -1782px; width: 16px; height: 16px; }
.bremen-logout{ background-position: -66px -1848px; width: 16px; height: 16px; }
.bremen-milestone{ background-position: -66px -1914px; width: 16px; height: 16px; }
.bremen-my-account{ background-position: -132px 0; width: 16px; height: 16px; }
.bremen-networking{ background-position: -132px -66px; width: 16px; height: 16px; }
.bremen-old-versions{ background-position: -132px -132px; width: 16px; height: 16px; }
.bremen-order-192{ background-position: -132px -198px; width: 16px; height: 16px; }
.bremen-order{ background-position: -132px -264px; width: 16px; height: 16px; }
.bremen-payment-card{ background-position: -132px -330px; width: 16px; height: 16px; }
.bremen-paypal{ background-position: -132px -396px; width: 16px; height: 16px; }
.bremen-pen{ background-position: -132px -462px; width: 16px; height: 16px; }
.bremen-pencil{ background-position: -132px -528px; width: 16px; height: 16px; }
.bremen-phone{ background-position: -132px -594px; width: 16px; height: 16px; }
.bremen-photography{ background-position: -132px -660px; width: 16px; height: 16px; }
.bremen-plus{ background-position: -132px -726px; width: 16px; height: 16px; }
.bremen-premium{ background-position: -132px -792px; width: 16px; height: 16px; }
.bremen-print{ background-position: -132px -858px; width: 16px; height: 16px; }
.bremen-process{ background-position: -132px -924px; width: 16px; height: 16px; }
.bremen-product-193{ background-position: -132px -990px; width: 16px; height: 16px; }
.bremen-product-design{ background-position: -132px -1056px; width: 16px; height: 16px; }
.bremen-product{ background-position: -132px -1122px; width: 16px; height: 16px; }
.bremen-project{ background-position: -132px -1188px; width: 16px; height: 16px; }
.bremen-publish{ background-position: -132px -1254px; width: 16px; height: 16px; }
.bremen-refresh{ background-position: -132px -1320px; width: 16px; height: 16px; }
.bremen-search{ background-position: -132px -1386px; width: 16px; height: 16px; }
.bremen-settings{ background-position: -132px -1452px; width: 16px; height: 16px; }
.bremen-shipping{ background-position: -132px -1518px; width: 16px; height: 16px; }
.bremen-showreel{ background-position: -132px -1584px; width: 16px; height: 16px; }
.bremen-sign-in{ background-position: -132px -1650px; width: 16px; height: 16px; }
.bremen-sign-out{ background-position: -132px -1716px; width: 16px; height: 16px; }
.bremen-sign-up{ background-position: -132px -1782px; width: 16px; height: 16px; }
.bremen-sitemap{ background-position: -132px -1848px; width: 16px; height: 16px; }
.bremen-special-offer{ background-position: -132px -1914px; width: 16px; height: 16px; }
.bremen-star{ background-position: -198px 0; width: 16px; height: 16px; }
.bremen-statistics{ background-position: -198px -66px; width: 16px; height: 16px; }
.bremen-suppliers{ background-position: -198px -132px; width: 16px; height: 16px; }
.bremen-tag{ background-position: -198px -198px; width: 16px; height: 16px; }
.bremen-ticket{ background-position: -198px -264px; width: 16px; height: 16px; }
.bremen-twitter{ background-position: -198px -330px; width: 16px; height: 16px; }
.bremen-upcoming-work{ background-position: -198px -396px; width: 16px; height: 16px; }
.bremen-user{ background-position: -198px -462px; width: 16px; height: 16px; }
.bremen-world{ background-position: -198px -528px; width: 16px; height: 16px; }
.bremen-zoom{ background-position: -198px -594px; width: 16px; height: 16px; }


text:
define(function(require, exports, module) {
    var TouchTracker = require('./TouchTracker');
    var EventHandler = require('../core/EventHandler');
    var OptionsManager = require('../core/OptionsManager');

    /**
     * Handles piped in touch events. Emits 'start', 'update', and 'events'
     *   events with delta, position, velocity, acceleration, clientX, clientY, count, and touch id.
     *   Useful for dealing with inputs on touch devices. Designed to be used either as standalone, or
     *   included in a GenericSync.
     *
     * @class TouchSync
     * @constructor
     *
     * @example
     *   var Surface = require('../core/Surface');
     *   var TouchSync = require('../inputs/TouchSync');
     *
     *   var surface = new Surface({ size: [100, 100] });
     *   var touchSync = new TouchSync();
     *   surface.pipe(touchSync);
     *
     *   touchSync.on('start', function (e) { // react to start });
     *   touchSync.on('update', function (e) { // react to update });
     *   touchSync.on('end', function (e) { // react to end });*
     *
     * @param [options] {Object}             default options overrides
     * @param [options.direction] {Number}   read from a particular axis
     * @param [options.rails] {Boolean}      read from axis with greatest differential
     * @param [options.velocitySampleLength] {Number}  Number of previous frames to check velocity against.
     * @param [options.scale] {Number}       constant factor to scale velocity output
     * @param [options.touchLimit] {Number}  touchLimit upper bound for emitting events based on number of touches
     */
    function TouchSync(options) {
        this.options =  Object.create(TouchSync.DEFAULT_OPTIONS);
        this._optionsManager = new OptionsManager(this.options);
        if (options) this.setOptions(options);

        this._eventOutput = new EventHandler();
        this._touchTracker = new TouchTracker({
            touchLimit: this.options.touchLimit
        });

        EventHandler.setOutputHandler(this, this._eventOutput);
        EventHandler.setInputHandler(this, this._touchTracker);

        this._touchTracker.on('trackstart', _handleStart.bind(this));
        this._touchTracker.on('trackmove', _handleMove.bind(this));
        this._touchTracker.on('trackend', _handleEnd.bind(this));

        this._payload = {
            delta    : null,
            position : null,
            velocity : null,
            clientX  : undefined,
            clientY  : undefined,
            count    : 0,
            touch    : undefined
        };

        this._position = null; // to be deprecated
    }

    TouchSync.DEFAULT_OPTIONS = {
        direction: undefined,
        rails: false,
        touchLimit: 1,
        velocitySampleLength: 10,
        scale: 1
    };

    TouchSync.DIRECTION_X = 0;
    TouchSync.DIRECTION_Y = 1;

    var MINIMUM_TICK_TIME = 8;

    /**
     *  Triggered by trackstart.
     *  @method _handleStart
     *  @private
     */
    function _handleStart(data) {
        var velocity;
        var delta;
        if (this.options.direction !== undefined){
            this._position = 0;
            velocity = 0;
            delta = 0;
        }
        else {
            this._position = [0, 0];
            velocity = [0, 0];
            delta = [0, 0];
        }

        var payload = this._payload;
        payload.delta = delta;
        payload.position = this._position;
        payload.velocity = velocity;
        payload.clientX = data.x;
        payload.clientY = data.y;
        payload.count = data.count;
        payload.touch = data.identifier;

        this._eventOutput.emit('start', payload);
    }

    /**
     *  Triggered by trackmove.
     *  @method _handleMove
     *  @private
     */
    function _handleMove(data) {
        var history = data.history;

        var currHistory = history[history.length - 1];
        var prevHistory = history[history.length - 2];

        var distantHistory = history[history.length - this.options.velocitySampleLength] ?
          history[history.length - this.options.velocitySampleLength] :
          history[history.length - 2];

        var distantTime = distantHistory.timestamp;
        var currTime = currHistory.timestamp;

        var diffX = currHistory.x - prevHistory.x;
        var diffY = currHistory.y - prevHistory.y;

        var velDiffX = currHistory.x - distantHistory.x;
        var velDiffY = currHistory.y - distantHistory.y;

        if (this.options.rails) {
            if (Math.abs(diffX) > Math.abs(diffY)) diffY = 0;
            else diffX = 0;

            if (Math.abs(velDiffX) > Math.abs(velDiffY)) velDiffY = 0;
            else velDiffX = 0;
        }

        var diffTime = Math.max(currTime - distantTime, MINIMUM_TICK_TIME);

        var velX = velDiffX / diffTime;
        var velY = velDiffY / diffTime;

        var scale = this.options.scale;
        var nextVel;
        var nextDelta;

        if (this.options.direction === TouchSync.DIRECTION_X) {
            nextDelta = scale * diffX;
            nextVel = scale * velX;
            this._position += nextDelta;
        }
        else if (this.options.direction === TouchSync.DIRECTION_Y) {
            nextDelta = scale * diffY;
            nextVel = scale * velY;
            this._position += nextDelta;
        }
        else {
            nextDelta = [scale * diffX, scale * diffY];
            nextVel = [scale * velX, scale * velY];
            this._position[0] += nextDelta[0];
            this._position[1] += nextDelta[1];
        }

        var payload = this._payload;
        payload.delta    = nextDelta;
        payload.velocity = nextVel;
        payload.position = this._position;
        payload.clientX  = data.x;
        payload.clientY  = data.y;
        payload.count    = data.count;
        payload.touch    = data.identifier;

        this._eventOutput.emit('update', payload);
    }

    /**
     *  Triggered by trackend.
     *  @method _handleEnd
     *  @private
     */
    function _handleEnd(data) {
        this._payload.count = data.count;
        this._eventOutput.emit('end', this._payload);
    }

    /**
     * Set internal options, overriding any default options
     *
     * @method setOptions
     *
     * @param [options] {Object}             default options overrides
     * @param [options.direction] {Number}   read from a particular axis
     * @param [options.rails] {Boolean}      read from axis with greatest differential
     * @param [options.scale] {Number}       constant factor to scale velocity output
     */
    TouchSync.prototype.setOptions = function setOptions(options) {
        return this._optionsManager.setOptions(options);
    };

    /**
     * Return entire options dictionary, including defaults.
     *
     * @method getOptions
     * @return {Object} configuration options
     */
    TouchSync.prototype.getOptions = function getOptions() {
        return this.options;
    };

    module.exports = TouchSync;
});


text:
@interface PCollectionCellBackgroundView  : UIView

@end


text:
namespace boost {
namespace beast {

class make_strand_test : public beast::unit_test::suite
{
public:
    void
    testFunction()
    {
        net::io_context ioc;
        net::make_strand(ioc);
        net::make_strand(ioc.get_executor());
        net::make_strand(net::make_strand(ioc));

        net::executor ex(ioc.get_executor());
        net::make_strand(ex);

        // this *should-not* compile
        //net::make_strand(ex.context());
    }

    void
    run() override
    {
        testFunction();
        pass();
    }
};

BEAST_DEFINE_TESTSUITE(beast,core,net::make_strand);

} // beast
} // boost


text:
package query.converter;

import java.util.Date;

import query.domain.FieldTypeConverter;

public enum FieldTypeConverterImpl implements FieldTypeConverter{
	SAME_CLASS{
		public Object convert(Object object) {
			return object;
		}
	},
	INTEGER_TO_BOOLEAN{
		public Object convert(Object object) {
			return ((Integer) object)==1;
		}
	},
	NUMBER_TO_LONG{
		public Object convert(Object object) {
			return ((Number) object).longValue();
		}
	},
	NUMBER_TO_INT{
		public Object convert(Object object) {
			return ((Number) object).intValue();
		}
	},
	BYTE_TO_BOOLEAN{
		public Object convert(Object object) {
			return ((Byte) object).intValue()==1;
		}
	},
	BIGINTEGER_TO_BOOLEAN{
		public Object convert(Object object) {
			return ((Number) object).intValue()==1;
		}
	},
	DATASQL_TO_DATE{
		public Object convert(Object object) {
			Date date = (Date) object;
			return date;
		}
	};
}


text:
/* ====================================================== */
/* = OUTLINES / BORDERS ================================= */
/* ====================================================== */
/**************
	LINKS
**************/
/* Errors */
.holmes-debug a:not([href]),
.holmes-debug a[href=""] {
  outline: 2px solid red;
}

.holmes-debug a[href="#"],
.holmes-debug a[href^="javascript"],
.holmes-debug a:not([title]),
.holmes-debug a[title=""] {
  outline: 2px solid #fd0;
}

/**************
	IMAGES
**************/
.holmes-debug img:not([alt]),
.holmes-debug img[alt=""] {
  outline: 2px solid red;
}

/*************************
	MISC ATTRIBUTES
**************************/
.holmes-debug label:not([for]),
.holmes-debug label[for=""],
.holmes-debug input:not([name]),
.holmes-debug input[name=""],
.holmes-debug select:not([name]),
.holmes-debug select[name=""],
.holmes-debug textarea:not([name]),
.holmes-debug textarea[name=""],
.holmes-debug abbr:not([title]),
.holmes-debug abbr[title=""],
.holmes-debug [class=""],
.holmes-debug [id=""],
.holmes-debug table:not([summary]),
.holmes-debug table[summary=""] {
  outline: 2px solid red;
}

/*
	Warnings here, for inline styles and event calls,
	ideally they should be external (CSS) and JS applied by JS scripts,
	keep markup purely presentational!
	(not sure about the js yet)
*/
.holmes-debug [style] {
  outline: 2px solid #fd0;
}

/*************************************************************************
	DEPRECATED & NON-W3C CONTENT ELEMENTS (darkgrey)
	Based largely on http://www.w3.org/TR/html5/obsolete.html#obsolete
*************************************************************************/
.holmes-debug applet,
.holmes-debug acronym,
.holmes-debug center,
.holmes-debug dir,
.holmes-debug font,
.holmes-debug strike,
.holmes-debug u,
.holmes-debug big,
.holmes-debug tt,
.holmes-debug marquee,
.holmes-debug plaintext,
.holmes-debug xmp {
  border: 2px solid darkgrey;
}

body.holmes-debug[bgproperties],
body.holmes-debug[topmargin],
body.holmes-debug[rightmargin],
body.holmes-debug[bottommargin],
body.holmes-debug[leftmargin] {
  outline: 2px solid darkgrey;
}

.holmes-debug *[bordercolor],
.holmes-debug *[bordercolordark],
.holmes-debug *[bordercolorlight],
.holmes-debug table[frame] {
  border: 2px solid darkgrey;
}

/*********************
	EMPTY ELEMENTS (warning level for now)
**********************/
.holmes-debug div:empty,
.holmes-debug span:empty,
.holmes-debug li:empty,
.holmes-debug p:empty,
.holmes-debug td:empty,
.holmes-debug th:empty {
  border: 2px solid #fd0;
}

/* ====================================================== */
/* = MESSAGES STYLES ==================================== */
/* ====================================================== */
/* ================== */
/* = Warning Style = */
/* ================== */
/* - LINKS - */
.holmes-debug a[href="#"]:hover::after,
.holmes-debug a[href^="javascript"]:hover::after,
.holmes-debug a:not([title]):hover::after,
.holmes-debug a[title=""]:hover::after,
.holmes-debug div:empty:hover::after,
.holmes-debug span:empty:hover::after,
.holmes-debug li:empty:hover::after,
.holmes-debug p:empty:hover::after,
.holmes-debug td:empty:hover::after,
.holmes-debug th:empty:hover::after,
.holmes-debug [style]:hover::after {
  border-radius: 0.5em;
  display: block;
  padding: 1em;
  margin: 1em;
  background: #fd0;
  position: fixed;
  color: #000;
  left: 0px;
  top: 0px;
  z-index: 9999;
}

/* =============== */
/* = Error Style = */
/* =============== */
/* - LINKS - */
.holmes-debug a:not([href]):hover::after,
.holmes-debug a[href=""]:hover::after,
.holmes-debug img:not([alt]):hover:after,
.holmes-debug img[alt=""]:hover::after,
.holmes-debug label:not([for]):hover::after,
.holmes-debug label[for=""]:hover::after,
.holmes-debug input:not([name]):hover::after,
.holmes-debug input[name=""]:hover::after,
.holmes-debug select:not([name]):hover::after,
.holmes-debug select[name=""]:hover::after,
.holmes-debug textarea:not([name]):hover::after,
.holmes-debug textarea[name=""]:hover::after,
.holmes-debug abbr:not([title]):hover::after,
.holmes-debug abbr[title=""]:hover::after,
.holmes-debug [class=""]:hover::after,
.holmes-debug [id=""]:hover::after,
.holmes-debug table:not([summary]):hover::after,
.holmes-debug table[summary=""]:hover::after {
  border-radius: 0.5em;
  display: block;
  padding: 1em;
  margin: 1em;
  background: red;
  position: fixed;
  color: #000;
  left: 0px;
  top: 0px;
  z-index: 9999;
  text-decoration: none;
}

/* ===================== */
/* = Deprecated Styles = */
/* ===================== */
/* - DEPRECATED & NON-W3C CONTENT ELEMENTS - */
.holmes-debug applet:hover::after,
.holmes-debug acronym:hover::after,
.holmes-debug center:hover::after,
.holmes-debug dir:hover::after,
.holmes-debug font:hover::after,
.holmes-debug strike:hover::after,
.holmes-debug u:hover::after,
.holmes-debug big:hover::after,
.holmes-debug tt:hover::after,
.holmes-debug marquee:hover::after,
.holmes-debug plaintext:hover::after,
.holmes-debug xmp:hover::after,
.holmes-debug *[bordercolor]:hover::after,
.holmes-debug *[bordercolordark]:hover::after,
.holmes-debug *[bordercolorlight]:hover::after,
.holmes-debug table[frame]:hover::after {
  border-radius: 0.5em;
  display: block;
  padding: 1em;
  margin: 1em;
  background: red;
  position: fixed;
  background: darkgrey;
  color: #000;
  left: 0px;
  top: 0px;
  z-index: 9999;
}

/* ================================ */
/* = Deprecated body style Styles = */
/* ================================ */
body.holmes-debug[bgproperties]:hover::after,
body.holmes-debug[topmargin]:hover::after,
body.holmes-debug[rightmargin]:hover::after,
body.holmes-debug[bottommargin]:hover::after,
body.holmes-debug[leftmargin]:hover::after {
  border-radius: 0.5em;
  display: block;
  padding: 1em;
  margin: 1em;
  background: red;
  position: fixed;
  background: darkgrey;
  color: #000;
  bottom: 0px;
  right: 0px;
  z-index: 9999;
  /* Bottom right due to whole body coverage */
}

/* Fixes the case where a table may contain both errors and warnings - potentially other cases of this elsewhere */
.holmes-debug td:empty:hover::after,
.holmes-debug th:empty:hover::after {
  top: 4em;
}

/* ====================================================== */
/* = MESSAGES CONTENT =================================== */
/* ====================================================== */
/**************
	LINKS
**************/
.holmes-debug a:not([href]):hover::after,
.holmes-debug a[href=""]:hover::after {
  content: 'Missing href attribute';
}

.holmes-debug a[href="#"]:hover:after {
  content: "href='#'";
}

.holmes-debug a[href^="javascript"]:hover:after {
  content: 'Href has javascript';
}

.holmes-debug a:not([title]):hover::after,
.holmes-debug a[title=""]:hover::after {
  content: 'Missing title attribute';
}

/**************
	IMAGES
**************/
.holmes-debug img:not([alt]):hover::after,
.holmes-debug img[alt=""]:hover::after {
  content: 'Missing alt attribute';
}

/*************************
	MISC ATTRIBUTES
**************************/
.holmes-debug label:not([for]):hover::after,
.holmes-debug label[for=""]:hover::after {
  content: 'Missing for attribute';
}

.holmes-debug input:not([name]):hover::after,
.holmes-debug input[name=""]:hover::after,
.holmes-debug select:not([name]):hover::after,
.holmes-debug select[name=""]:hover::after,
.holmes-debug textarea:not([name]):hover::after,
.holmes-debug textarea[name=""]:hover::after {
  content: 'Missing name attribute';
}

.holmes-debug abbr:not([title]):hover::after,
.holmes-debug abbr[title=""]:hover::after {
  content: 'Missing title attribute';
}

.holmes-debug [class=""]:hover::after {
  content: 'Blank class attribute';
}

.holmes-debug [id=""]:hover::after {
  content: 'Blank id attribute';
}

.holmes-debug table:not([summary]):hover::after,
.holmes-debug table[summary=""]:hover::after {
  content: 'Missing summary attribute';
}

.holmes-debug [style]:hover::after {
  content: 'Element has inline styles';
}

/*************************************************************************
	DEPRECATED & NON-W3C CONTENT ELEMENTS (darkgrey)
	Based largely on http://www.w3.org/TR/html5/obsolete.html#obsolete
*************************************************************************/
.holmes-debug applet:hover::after,
.holmes-debug acronym:hover::after,
.holmes-debug center:hover::after,
.holmes-debug dir:hover::after,
.holmes-debug font:hover::after,
.holmes-debug strike:hover::after,
.holmes-debug u:hover::after,
.holmes-debug big:hover::after,
.holmes-debug tt:hover::after,
.holmes-debug marquee:hover::after,
.holmes-debug plaintext:hover::after,
.holmes-debug xmp:hover::after {
  content: 'Deprecated or Non-W3C element';
}

/************************************************************************
	DEPRECATED NON-W3C ATTRIBUTES (darkgrey)
	Based largely on http://www.w3.org/TR/html5/obsolete.html#obsolete
************************************************************************/
body.holmes-debug[bgproperties]:hover::after {
  content: 'Deprecated or Non-W3C body attribute bgproperties';
}

body.holmes-debug[topmargin]:hover::after,
body.holmes-debug[rightmargin]:hover::after,
body.holmes-debug[bottommargin]:hover::after,
body.holmes-debug[leftmargin]:hover::after {
  content: 'Deprecated or Non-W3C body attribute *margin';
}

.holmes-debug *[bordercolor]:hover::after,
.holmes-debug *[bordercolordark]:hover::after,
.holmes-debug *[bordercolorlight]:hover::after,
.holmes-debug table[frame]:hover::after {
  content: 'Deprecated or Non-W3C body attribute bordercolor';
}

/*********************
	EMPTY ELEMENTS (warning level for now)
**********************/
.holmes-debug div:empty:hover::after,
.holmes-debug span:empty:hover::after,
.holmes-debug li:empty:hover::after,
.holmes-debug p:empty:hover::after,
.holmes-debug td:empty:hover::after,
.holmes-debug th:empty:hover::after {
  content: 'Empty element!';
}


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>
Uses of Interface com.hp.hpl.jena.ontology.QualifiedRestriction (Jena Framework)
</TITLE>

<META NAME="date" CONTENT="2010-06-01">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Uses of Interface
com.hp.hpl.jena.ontology.QualifiedRestriction

Packages that use QualifiedRestriction

com.hp.hpl.jena.ontology

                        Provides a set of abstractions and convenience classes for accessing and manipluating ontologies
                        represented in RDF.

Uses of QualifiedRestriction in com.hp.hpl.jena.ontology

Subinterfaces of QualifiedRestriction in com.hp.hpl.jena.ontology

 interface
CardinalityQRestriction

 Interface representing the ontology abstraction for a qualified cardinality
 restriction.

 interface
MaxCardinalityQRestriction

 Interface representing the ontology abstraction for a qualified maximum cardinality
 restriction.

 interface
MinCardinalityQRestriction

 Interface representing the ontology abstraction for a qualified minimum cardinality
 restriction.

Methods in com.hp.hpl.jena.ontology that return QualifiedRestriction

 QualifiedRestriction
OntModel.getQualifiedRestriction(java.lang.String uri)

          Answer a class description defined as the class of those individuals that have a property
 p, all values of which are members of a given class.

      Overview
      Package
      Class
    Use
      Tree
      Deprecated
      Index
      Help

 PREV
 NEXT

  FRAMES
 NO FRAMES

  All Classes

Copyright © 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 Hewlett-Packard Development Company, LP


text:
namespace SnowboyWeb
{
	// Google Cloud Speech Recognizer
	class GCSVoiceRecognizer : public VoiceRecognizer
	{
	public:
		GCSVoiceRecognizer(const AudioConfig& config);
		virtual ~GCSVoiceRecognizer();
		// Geerbt über VoiceRecognizer
		virtual void start(bool vad) override;
		virtual void processAudio(const std::string & data) override;
		virtual void end() override;
	private:
		class Data;
		std::unique_ptr<Data> _data;
	};
}