text:
"use strict";

let soajsUtils = require("soajs").utils;

const driver = {

	"check": function (req, context, lib, async, BL, callback) {
		//validate if ci schema is valid
		let template = context.template;

		let schema = {
			type: 'object',
			properties: {
				"label": {"type": "string", "required": true},
				"name": {"type": "string", "required": true, "format": "lowercase", "pattern": /[a-zA-Z0-9_\-]/},
				"type": {"type": "string", "required": true, "enum": ["service", "daemon", "custom"]},
				"category": {"type": "string", "required": true},
				"gitSource": {
					"type": "object",
					"required": true,
					"properties": {
						"provider": {"type": "string", "required": true},
						"owner": {"type": "string", "required": true},
						"repo": {"type": "string", "required": true}
					}
				},
				"deploy": {
					"type": "object"
				}
			}
		};

		let myValidator = new req.soajs.validator.Validator();

		//check if name exists
		if (template.content && template.content.deployments && template.content.deployments.repo && Object.keys(template.content.deployments.repo).length > 0) {
			let repos = Object.keys(template.content.deployments.repo);
			async.eachSeries(repos, (repoName, cb) => {
				let oneRepo = template.content.deployments.repo[repoName];

				async.series({
					"validateSchema": (mCb) => {
					if (oneRepo.type === 'daemon') {
						schema = soajsUtils.cloneObj(schema);
						schema['group'] = {"type" : "string", "required" : true}
					}
						let status = myValidator.validate(oneRepo, schema);
						if (!status.valid) {
							let errors = [];
							status.errors.forEach(function (err) {
								errors.push({code: 173, msg: `<b>${repoName}</b>: ` + err.stack, group: "Repositories"})
							});
							return mCb(errors);
						}
						return mCb(null, true);
					},
					"checkGitRepos": (mCb) => {
						let opts = {
							conditions: {
								"src.provider": oneRepo.gitSource.provider,
								"src.owner": oneRepo.gitSource.owner,
								"src.repo": oneRepo.gitSource.repo
							},
							collection: "services",
						};

						BL.model.countEntries(req.soajs, opts, function (error, count) {
							lib.checkReturnError(req, cb, {config: context.config, error: error, code: 600}, () => {
								if (!count || count === 0) {
									return mCb({
										"code": 173,
										"msg": `Activate Git Account for <b>${oneRepo.gitSource.owner}</b> or activate repo <b>${oneRepo.gitSource.repo}</b> in that account to enable importing its repo deployment template`, group: "Repositories"
									});
								}
								return mCb(null, true);
							});
						});
					},
                    'checkDeamonGroups': (mCb) => {
                        if (oneRepo.type === 'daemon') {
                            let opts = {
                                collection: "daemon_grpconf",
                            };
                            let daemonName = [];
                            async.series({
                                'mergeFromDb': (cb) => {
                                    BL.model.findEntries(req.soajs, opts, function (error, deamonGroups) {
                                        lib.checkReturnError(req, cb, {
                                            config: context.config,
                                            error: error,
                                            code: 600
                                        }, () => {
                                            if (deamonGroups && deamonGroups.length > 0) {
                                                async.forEach(deamonGroups, (oneGroup, mainCb) => {
                                                    daemonName.push(oneGroup.daemonConfigGroup);
                                                    return mainCb();
                                                }, () => {
                                                    return cb();
                                                })
                                            } else {
                                                return cb();
                                            }
                                        });
                                    });
                                },
                                'mergeFromTemplate': (cb) => {
                                    if (template.content.daemonGroups && template.content.daemonGroups.data && Array.isArray(template.content.daemonGroups.data) && template.content.daemonGroups.data.length > 0) {
                                        async.forEach(template.content.daemonGroups.data, (oneDaemonGroup, mainCb) => {
                                            if (daemonName.indexOf(oneDaemonGroup.groupName) === -1) {
                                                daemonName.push(oneDaemonGroup.groupName);
                                            }
                                            return mainCb();
                                        }, cb);
                                    } else {
                                        return cb();
                                    }
                                },
                                'checkGroups': (cb) => {
                                    if (daemonName.indexOf(oneRepo.group) === -1) {
                                        return mCb({
                                            "code": 173,
                                            "msg": `Repo <b>${oneRepo.name}</b> of type daemon has a Daemon Group <b>${oneRepo.group}</b> that does not exists`,
                                            "group": "Repositories"
                                        });
                                    }
									return mCb(null, true);
                                }
                            });
                        } else {
                            return mCb(null, true);
                        }
                    }
				}, (error) => {
					if (error) {
						context.errors.push(error);
					}

					return cb(null, true);
				});

			}, callback);
		} else {
			return callback();
		}
	}
};

module.exports = driver;


text:
Full default configuration
==========================

```yaml
fos_rest:
    access_denied_listener:

        # Prototype
        name:                   []
    param_fetcher_listener:     false
    cache_dir:                  %kernel.cache_dir%/fos_rest
    allowed_methods_listener:   false
    routing_loader:
        default_format:         ~
        include_format:         ~
    service:
        router:                 router
        templating:             templating
        serializer:             jms_serializer.serializer
        view_handler:           fos_rest.view_handler.default
    serializer:
        version:                ~
        groups:                 []
        serialize_null:         false
    view:
        default_engine:         twig
        force_redirects:

            # Prototype
            name:               []
        mime_types:

            # Prototype
            name:               []
        formats:

            # Prototype
            name:               []
        templating_formats:

            # Prototype
            name:               []
        view_response_listener: false
        failed_validation:      400
        empty_content:          204
        serialize_null:         false
        jsonp_handler:
            callback_param:     callback
            callback_filter:    /(^[a-z0-9_]+$)|(^YUI\.Env\.JSONP\._[0-9]+$)/i
            mime_type:          application/javascript
    exception:
        codes:

            # Prototype
            name:               []
        messages:

            # Prototype
            name:               []
    body_listener:
        decoders:

            # Prototype
            name:               []
    body_converter:
        enabled: false
        validate: false
        validation_errors_argument: validationErrors # The name of the argument on which the validation errors are set
    format_listener:
        default_priorities:

            # Defaults:
            - html
            - */*
        prefer_extension:       true
        fallback_format:        html
```

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<translations>
    <label key="create" default="create">
        <translation lang="da">opret</translation>
    </label>
    <label key="edit" default="edit">
        <translation lang="da">rediger</translation>
    </label>
    <label key="add" default="add">
        <translation lang="da">tilføj</translation>
    </label>
    <label key="delete" default="delete">
        <translation lang="da">slet</translation>
    </label>
    <label key="save" default="save">
        <translation lang="da">gem</translation>
    </label>
    <label key="close" default="close">
        <translation lang="da">luk</translation>
    </label>
    <label key="open" default="open">
        <translation lang="da">åben</translation>
    </label>
    <label key="by" default="by">
        <translation lang="da">af</translation>
    </label>
    <label key="move" default="move">
        <translation lang="da">flyt</translation>
    </label>
    <label key="remove" default="remove">
        <translation lang="da">fjern</translation>
    </label>
    <label key="error" default="error">
        <translation lang="da">fejl</translation>
    </label>
    <label key="warning" default="warning">
        <translation lang="da">advarsel</translation>
    </label>
    <label key="info" default="info">
        <translation lang="da">info</translation>
    </label>
</translations>


text:
set `planner.slice_target`=1;
select columns[1], count(*) from `psv/partsupp` group by columns[1] order by columns[1] limit 5;
reset `planner.slice_target`;


text:
package com.bccriskadvisory.link.processor;

import com.bccriskadvisory.link.JiraPluginContext;

public enum ImportMode {

	AUTO(true, "automatic import") {
		@Override
		public ProjectImportProcessor createProcessor( JiraPluginContext pluginContext, boolean testMode) {
			return new AutoProjectImportProcessor(pluginContext, testMode);
		}
	},
	UPDATE(true, "updated vulnerability import") {
		@Override
		public ProjectImportProcessor createProcessor( JiraPluginContext pluginContext, boolean testMode) {
			return new UpdateProjectImportProcessor(pluginContext, testMode);
		}
	},
	FULL(false, "full vulnerability import") {
		@Override
		public ProjectImportProcessor createProcessor( JiraPluginContext pluginContext, boolean testMode) {
			return new FullProjectImportProcessor(pluginContext, testMode);
		}
	};

	private boolean isUpdate;
	private String display;

	private ImportMode(boolean isUpdate, String display) {
		this.isUpdate = isUpdate;
		this.display = display;
	}

	public abstract ProjectImportProcessor createProcessor(JiraPluginContext pluginContext, boolean testMode);

	public boolean isUpdate() {
		return isUpdate;
	}

	public String getDisplay() {
		return display;
	}

	public static ImportMode fromString(String in) {
		switch (in.toLowerCase()) {
		case "auto":
			return AUTO;
		case "update":
			return UPDATE;
		case "full":
			return FULL;
		default:
			throw new IllegalArgumentException("Unrecognised import mode: " + in);
		}
	}
}


text:
<html>
    <head>
        <script>window.location = "views/index.html"</script>
    </head>
</html>


text:
/*
 * Note: we do there only trivial tests around the objective-c wrapper. The core exhaustive tests cases are done in CryptoFileTest.
 */

#import <XCTest/XCTest.h>

#import "SMCryptoFileHandle.h"
#import "TestHelper.h"

/*
** CryptoFileHandleTest - Interface
*/
#pragma mark - CryptoFileHandleTest - Interface

@interface CryptoFileHandleTest : XCTestCase

@end

/*
** CryptoFileHandleTest
*/
#pragma mark - CryptoFileHandleTest

@implementation CryptoFileHandleTest

- (void)testGeneralAPI
{
	NSString	*cryptoPath = [TestHelper generateTempPath];
	NSString	*stdPath = [TestHelper generateTempPath];

	NSString	*password1 = @"azerty";
	NSString	*password2 = @"qwerty";

	NSError		*error;

	SMCryptoFileHandle	*cryptoHandle = nil;
	NSFileHandle		*stdHandle = nil;

	// Install cleaner.
	TestCleaner *cleaner = [[TestCleaner alloc] init];

	[cleaner postponeBlock:^{

		[cryptoHandle closeFileAndReturnError:nil];
		[stdHandle closeFile];

		[[NSFileManager defaultManager] removeItemAtPath:cryptoPath error:nil];
		[[NSFileManager defaultManager] removeItemAtPath:stdPath error:nil];
	}];

	// Create crypto file.
	cryptoHandle = [SMCryptoFileHandle cryptoFileHandleByCreatingFileAtPath:cryptoPath password:password1 keySize:SMCryptoFileKeySize128 error:&error];

	if (!cryptoHandle)
	{
		XCTFail(@"Can't create a crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// Create standard file.
	[[NSFileManager defaultManager] createFileAtPath:stdPath contents:[NSData data] attributes:nil];

	stdHandle = [NSFileHandle fileHandleForUpdatingAtPath:stdPath];

	if (!stdHandle)
	{
		XCTFail(@"Can't create a standard file handle");
		return;
	}

	// Generate data.
	NSMutableData *randomData = [[NSMutableData alloc] initWithLength:10000];

	arc4random_buf([randomData mutableBytes], [randomData length]);

	// Write data to crypto file.
	if ([cryptoHandle writeData:randomData error:&error] == NO)
	{
		XCTFail(@"Can't write random data to crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// Write data to standard file.
	@try {
		[stdHandle writeData:randomData];
	}
	@catch (NSException *exception) {
		XCTFail(@"Can't write random data to standard file handle (%@)", exception);
		return;
	}

	// Synchronize data.
	if ([cryptoHandle synchronizeFileAndReturnError:&error] == NO)
	{
		XCTFail(@"Can't synchronize crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// Change password.
	if ([cryptoHandle changePassword:password2 error:&error] == NO)
	{
		XCTFail(@"Can't change password of crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// Close files.
	if ([cryptoHandle closeFileAndReturnError:&error] == NO)
	{
		XCTFail(@"Can't close crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	[stdHandle closeFile];

	// Re-open files.
	cryptoHandle = [SMCryptoFileHandle cryptoFileHandleByOpeningFileAtPath:cryptoPath password:password2 readOnly:NO error:&error];

	if (!cryptoHandle)
	{
		XCTFail(@"Can't re-open crypto file (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	stdHandle = [NSFileHandle fileHandleForUpdatingAtPath:stdPath];

	if (!stdHandle)
	{
		XCTFail(@"Can't re-open standard file");
		return;
	}

	// Read chunk.
	NSData *cryptoChunk;
	NSData *stdChunk;

	// > Crypto file.
	cryptoChunk = [cryptoHandle readDataOfLength:1024 error:&error];

	if (!cryptoChunk)
	{
		XCTFail(@"Can't read a chunk of data in crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	@try {
		stdChunk = [stdHandle readDataOfLength:1024];
	}
	@catch (NSException *exception) {
		XCTFail(@"Can't read a chunk of data in standard file handle (%@)", exception);
		return;
	}

	// Compare chunk.
	if ([cryptoChunk isEqualToData:stdChunk] == NO)
	{
		XCTFail(@"Chunks are not the sames");
		return;
	}

	// Compare offset.
	if ([cryptoHandle offsetInFile] != [stdHandle offsetInFile])
	{
		XCTFail(@"Offset are not the sames");
		return;
	}

	// Read rest of the file.
	// > Crypto file.
	cryptoChunk = [cryptoHandle readDataToEndOfFileAndReturnError:&error];

	if (!cryptoChunk)
	{
		XCTFail(@"Can't read rest of data in crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	@try {
		stdChunk = [stdHandle readDataToEndOfFile];
	}
	@catch (NSException *exception) {
		XCTFail(@"Can't read rest of data in standard file handle (%@)", exception);
		return;
	}

	// Compare chunk.
	if ([cryptoChunk isEqualToData:stdChunk] == NO)
	{
		XCTFail(@"Chunks are not the sames");
		return;
	}

	// Compare offset.
	if ([cryptoHandle offsetInFile] != [stdHandle offsetInFile])
	{
		XCTFail(@"Offset are not the sames");
		return;
	}

	// Compare size.
	if ([cryptoHandle fileSize] != [stdHandle offsetInFile])
	{
		XCTFail(@"Crypto file size is not coherent");
		return;
	}

	// Truncate lower.
	// > Crypto file.
	if ([cryptoHandle truncateFileAtOffset:3000 error:&error] == NO)
	{
		XCTFail(@"Can't truncate crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	[stdHandle truncateFileAtOffset:3000];

	// Seek in file.
	// > Crypto file.
	if ([cryptoHandle seekToFileOffset:50 error:&error] == NO)
	{
		XCTFail(@"Can't seek in crypto file (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	[stdHandle seekToFileOffset:50];

	// Compare offset.
	if ([cryptoHandle offsetInFile] != [stdHandle offsetInFile])
	{
		XCTFail(@"Offset are not the sames");
		return;
	}

	// Read.
	// > Crypto file.
	cryptoChunk = [cryptoHandle readDataToEndOfFileAndReturnError:&error];

	if (!cryptoChunk)
	{
		XCTFail(@"Can't read crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	@try {
		stdChunk = [stdHandle readDataToEndOfFile];
	}
	@catch (NSException *exception) {
		XCTFail(@"Can't read standard file handle (%@)", exception);
		return;
	}

	// Compare chunk.
	if ([cryptoChunk isEqualToData:stdChunk] == NO)
	{
		NSLog(@"stdChunk: %@", stdChunk);
		NSLog(@"cryptoChunk: %@", cryptoChunk);

		XCTFail(@"Chunks are not the sames");
		return;
	}

	// Truncate upper.
	// > Crypto file.
	if ([cryptoHandle truncateFileAtOffset:20000 error:&error] == NO)
	{
		XCTFail(@"Can't truncate crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	[stdHandle truncateFileAtOffset:20000];

	// Seek in file.
	// > Crypto file.
	if ([cryptoHandle seekToFileOffset:0 error:&error] == NO)
	{
		XCTFail(@"Can't seek in crypto file (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	[stdHandle seekToFileOffset:0];

	// Read.
	// > Crypto file.
	cryptoChunk = [cryptoHandle readDataToEndOfFileAndReturnError:&error];

	if (!cryptoChunk)
	{
		XCTFail(@"Can't read crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// > Standard file.
	@try {
		stdChunk = [stdHandle readDataToEndOfFile];
	}
	@catch (NSException *exception) {
		XCTFail(@"Can't read standard file handle (%@)", exception);
		return;
	}

	// Compare chunk.
	if ([cryptoChunk isEqualToData:stdChunk] == NO)
	{
		XCTFail(@"Chunks are not the sames");
		return;
	}

	// Quick test impersonation.
	SMCryptoFileHandle	*cryptoHandleImpersonated = nil;
	NSString			*cryptoPathImpersonated = [TestHelper generateTempPath];

	[cleaner postponeBlock:^{
		[cryptoHandleImpersonated closeFileAndReturnError:nil];
		[[NSFileManager defaultManager] removeItemAtPath:cryptoPathImpersonated error:nil];
	}];

	cryptoHandleImpersonated = [SMCryptoFileHandle cryptoFileHandleByImpersonatingFileHandle:cryptoHandle path:cryptoPathImpersonated error:&error];

	if (!cryptoHandleImpersonated)
	{
		XCTFail(@"Can't create a crypto file handle by impersonation (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// Quick test volatile.
	SMCryptoFileHandle	*cryptoHandleVolatile = nil;

	[cleaner postponeBlock:^{
		[cryptoHandleVolatile closeFileAndReturnError:nil];
	}];

	cryptoHandleVolatile = [SMCryptoFileHandle cryptoFileHandleByCreatingVolatileFileAtPath:nil keySize:SMCryptoFileKeySize128 error:&error];

	if (!cryptoHandleVolatile)
	{
		XCTFail(@"Can't create a volatile crypto file handle (%@)", [TestHelper stringWithError:(SMCryptoFileError)error.code]);
		return;
	}

	// Keep cleaner alive up there.
	[cleaner self];
}

@end


text:
#pragma once

#ifdef _MSC_VER
    //disable windows complaining about max template size.
    #pragma warning (disable : 4503)
#endif // _MSC_VER

#if defined (USE_WINDOWS_DLL_SEMANTICS) || defined (_WIN32)
    #ifdef _MSC_VER
        #pragma warning(disable : 4251)
    #endif // _MSC_VER

    #ifdef USE_IMPORT_EXPORT
        #ifdef AWS_TIMESTREAMWRITE_EXPORTS
            #define AWS_TIMESTREAMWRITE_API __declspec(dllexport)
        #else
            #define AWS_TIMESTREAMWRITE_API __declspec(dllimport)
        #endif /* AWS_TIMESTREAMWRITE_EXPORTS */
    #else
        #define AWS_TIMESTREAMWRITE_API
    #endif // USE_IMPORT_EXPORT
#else // defined (USE_WINDOWS_DLL_SEMANTICS) || defined (WIN32)
    #define AWS_TIMESTREAMWRITE_API
#endif // defined (USE_WINDOWS_DLL_SEMANTICS) || defined (WIN32)


text:
package net.mgsx.game.examples.openworld.ui;

import com.badlogic.ashley.core.Engine;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.utils.Array;

import net.mgsx.game.examples.openworld.model.OpenWorldModel;
import net.mgsx.game.examples.openworld.systems.OpenWorldGameSystem;

public class QuestsView extends Table
{
	private OpenWorldGameSystem gameSystem;

	Table tableQuest;

	public QuestsView(Skin skin, Engine engine) {
		super(skin);

		// display all quests order by :
		// locked first then model order ?
		// unlocked then model order ?

		gameSystem = engine.getSystem(OpenWorldGameSystem.class);

		tableQuest = new Table(skin);

		Table questList = new Table(getSkin());
		questList.defaults().fill();
		for(String questUID : gameSystem.player.pendingQuests){
			questList.add(createQuestButton(questUID, false)).row();
		}
		for(String questUID : gameSystem.player.completedQuests){
			questList.add(createQuestButton(questUID, true)).row();
		}
		add("All Quests").colspan(2).expandX().row();
		add(new ScrollPane(questList,  getSkin())).expand().fill();
		add(new ScrollPane(tableQuest, getSkin())).expand().fill();
	}

	private Actor createQuestButton(final String questUID, final boolean complete) {
		String label = OpenWorldModel.quest(questUID).name();
		if(complete){
			label += " (completed)";
		}
		TextButton bt = new TextButton(label, getSkin());
		bt.addListener(new ChangeListener() {
			@Override
			public void changed(ChangeEvent event, Actor actor) {
				showQuest(questUID, complete);
			}
		});
		return bt;
	}

	protected void showQuest(String questUID, boolean complete) {
		tableQuest.clear();

		Label summary = new Label(OpenWorldModel.quest(questUID).summary(), getSkin());
		summary.setWrap(true);

		tableQuest.add(OpenWorldModel.quest(questUID).name()).row();
		tableQuest.add(summary).width(Gdx.graphics.getWidth() / 2).row();

		int xp = OpenWorldModel.quest(questUID).xp();
		if(xp != 0) tableQuest.add("Reward XP: " + xp).row();

		Array<String> items = OpenWorldModel.quest(questUID).items();
		if(items.size > 0){
			String txt = "New items :";
			for(String item : items){
				txt += " " + OpenWorldModel.name(item);
			}
			tableQuest.add(txt).row();
		}

		Array<String> knowledges = OpenWorldModel.quest(questUID).knowledges();
		if(knowledges.size > 0){
			String txt = "New knowledges :";
			for(String knowledge : knowledges){
				txt += " " + OpenWorldModel.name(knowledge);
			}
			tableQuest.add(txt).row();
		}
		// TODO other rewards here ...

		tableQuest.add(complete ? "COMPLETED" : "").row();;
	}

}


text:
<?php
/**
 * Contains \jamesiarmes\PhpEws\Response\GetConversationItemsResponseType.
 */

namespace jamesiarmes\PhpEws\Response;

/**
 * Defines a response to a GetConversationItems request.
 *
 * @package php-ews\Response
 */
class GetConversationItemsResponseType extends BaseResponseMessageType
{

}


text:
layout: post
title: "How to add Open API support for Azure Functions"
subtitle: "This post is about documenting Azure Functions using Open API."
date: 2020-11-26 00:00:00
categories: [Azure,OpenAPI,Serverless]
tags: [Azure,OpenAPI,Serverless]
author: "Anuraj"
image: /assets/images/2020/11/open_api_spec2.png
---
This post is about documenting Azure Functions using Open API. Similar to ASP.NET Core, Open API support for Azure Functions is also simple and straight forward.

I am using the QR Generator Azure Function and I am enabling Open API support for that. To enable Open API support first you need to add the Open API package for Azure Functions. You can do this by running the command - `dotnet add package Microsoft.Azure.WebJobs.Extensions.OpenApi --version 0.1.0-preview`

When you add this package and if run the function, you will be able to see the function is displaying 3 more URLs other than the function HTTP endpoint.

![Azure Function running]({{ site.url }}/assets/images/2020/11/azure_function_running.png)

But if you try to access it, it will return internal server error. It is because you are missing the Open API configuration. You can fix this by adding the following JSON values in the `host.json` file.

{% highlight Javascript %}
"openApi": {
    "info": {
        "version": "1.0.0",
        "title": "QR Code Generator",
        "description": "A serverless Azure Function which helps you to create QR code for URLs.",
        "termsOfService": "https://dotnetthoughts.net/",
        "contact": {
            "name": "anuraj",
            "email": "anuraj at dotnetthoughts.net",
            "url": "https://dotnetthoughts.net/"
        },
        "license": {
            "name": "MIT",
            "url": "https://anuraj.mit-license.org/"
        }
    }
}
{% endhighlight %}

Now if you run and browse the Swagger UI endpoint you will be able to see a Open API screen like the following.

![Open API Specification]({{ site.url }}/assets/images/2020/11/open_api_spec.png)

But it is showing `No operations defined in spec!`, in case of ASP.NET Core, we don't need to do it, but in Function you need to explicitly configure the Open API operations and associated request and responses. Here is an example.

{% highlight CSharp %}
[OpenApiOperation(operationId: "QRGenerator",
    tags: new[] { "QRGenerator" },
    Summary = "Generate QR Code for the URL",
    Description = "Generate QR Code for the URL",
    Visibility = OpenApiVisibilityType.Important)]
[OpenApiParameter(name: "url",
    In = ParameterLocation.Query,
    Required = true,
    Type = typeof(Uri),
    Summary = "The URL to generate QR code",
    Description = "The URL to generate QR code",
    Visibility = OpenApiVisibilityType.Important)]
[OpenApiResponseWithBody(statusCode: HttpStatusCode.OK,
    contentType: "image/png",
    bodyType: typeof(FileResult),
    Summary = "The QR code image file",
    Description = "The QR code image file")]
[OpenApiResponseWithoutBody(statusCode: HttpStatusCode.BadRequest,
    Summary = "If the URL is missing or invalid URL",
    Description = "If the URL is missing or invalid URL")]
[FunctionName("QRGenerator")]
public static async Task<IActionResult> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
    ILogger log)
{
    log.LogInformation("C# HTTP trigger function processed a request.");
}
{% endhighlight %}

Now if you run the app again you will be able to find something like this.

![Open API Specification with Open API operation]({{ site.url }}/assets/images/2020/11/open_api_spec2.png)

Now you can test and verify this function with the Open API UI, if you provide the URL it will generate the QR code image and will display it in the UI. Now you're able to import the Open API file into API Management and it can work with Azure Functions.

Happy Programming :)


text:
NSString *SaveToPath()
{
    NSArray *path_list =NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory,NSUserDomainMask,YES);
    return [[path_list objectAtIndex:0]stringByAppendingPathComponent:@"data.txt"];
}

@interface AppDelegate ()

@end

@implementation AppDelegate

-(void)AddTask:(id)sender
{
    NSString *text = [task_field text];
    if([text isEqualToString:@""])
    {
        return;
    }
    [tasks addObject:text];
    [task_table reloadData];
    [task_field setText:@""];
    [task_field resignFirstResponder];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([tasks count]==0)
    {
        [tasks addObject:@"遛狗"];
        [tasks addObject:@"打酱油"];
        [tasks addObject:@"挤牛奶"];
    }
    return [tasks count];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [task_table dequeueReusableCellWithIdentifier:@"cell"];
    if(!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                      reuseIdentifier:@"Cell"];
    }
    NSString *item = [tasks objectAtIndex:[indexPath row]];
    [[cell textLabel] setText:item];
    return cell;
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    //初始化程序的状态,完成相关对象的创建
    NSArray *plist = [NSArray arrayWithContentsOfFile:SaveToPath()];
    if(plist)
    {
        tasks = [plist mutableCopy];
    }
    else
    {
        tasks = [[NSMutableArray alloc]init];
    }

    //创建应用程序的主窗口
    CGRect window_frame = [[UIScreen mainScreen] bounds];
    UIWindow *the_window =[[UIWindow alloc] initWithFrame:window_frame];
    [self setWindow:the_window];

    //设置三个UI对象的frame属性
    CGRect table_frame = CGRectMake(0, 80, 320, 380);
    CGRect field_frame = CGRectMake(20, 40, 200, 31);
    CGRect button_frame =CGRectMake(228, 40, 72, 31);
    //创建并设置表格UITableView
    task_table = [[UITableView alloc]initWithFrame:table_frame
                                             style:UITableViewStylePlain];
    [task_table setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    //将AppDelegate设置为UITableView的数据源
    [task_table setDataSource:self];
    //创建并设置文本框(UITextField)
    task_field = [[UITextField alloc]initWithFrame:field_frame];
    [task_field setBorderStyle:UITextBorderStyleRoundedRect];
    [task_field setPlaceholder:@"Type a task,tap Insert"];
    //创建并设置按钮(UIButton)
    insert_button= [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [insert_button setFrame:button_frame];
    [insert_button setTitle:@"Insert" forState:UIControlStateNormal];
    //为按钮设置回调
    [insert_button addTarget:self action:@selector(AddTask:) forControlEvents:UIControlEventTouchUpInside];
    //将三个UI对象加入UIWindow中
    [[self window] addSubview:task_table];
    [[self window] addSubview:task_field];
    [[self window] addSubview:insert_button];

    //实例化一个ViewController的实例,并设置成window的rootViewContrller
    //ViewController *fvc = [[ViewController alloc]init];
    //[[self window] setRootViewController:fvc];

    //设置UIWindow的背景颜色,并放到屏幕上
    [[self window] setBackgroundColor:[UIColor whiteColor]];
    [[self window] makeKeyAndVisible];
   //self.window.rootViewController = [[UIViewController alloc]init];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    [tasks writeToFile:SaveToPath() atomically:YES];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<cronentries>
<cron>
<url>/crons/set_announcement</url>
<description>Set announcement</description>
<schedule>every 24 hours</schedule>
</cron>
</cronentries>


text:
import numpy as np

from ...utils import get_config, verbose
from ...fixes import partial
from ..utils import has_dataset, _data_path, _doc

has_sample_data = partial(has_dataset, name='sample')

@verbose
def data_path(path=None, force_update=False, update_path=True,
              download=True, verbose=None):
    return _data_path(path=path, force_update=force_update,
                      update_path=update_path, name='sample',
                      download=download,
                      verbose=verbose)

data_path.__doc__ = _doc.format(name='sample',
                                conf='MNE_DATASETS_SAMPLE_PATH')

# Allow forcing of sample dataset skip (for tests) using:
# `make test-no-sample`
def _skip_sample_data():
    skip_sample = get_config('MNE_SKIP_SAMPLE_DATASET_TESTS', 'false') == 'true'
    skip = skip_sample or not has_sample_data()
    return skip

requires_sample_data = np.testing.dec.skipif(_skip_sample_data,
                                             'Requires sample dataset')


text:
$computer = Get-WmiObject -Class Win32_ComputerSystem
write-output $computer.PartOfDomain


text:
#ifndef COMPAT_STRNDUP_H_INCLUDED
#define COMPAT_STRNDUP_H_INCLUDED

#ifndef HAVE_STRNDUP
char *strndup(const char *str, size_t len);
#endif

#endif


text:
Creates and manipulates the standard elements of the Windows user interface,
such as the desktop, windows, and menus. Functions perform operations such as
creating and managing windows, receiving window messages, displaying text in a
window, and displaying message boxes.


text:
package yavlanskiy.pages;

import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;

public class UserSettingsPage extends AnyPage {

    public UserSettingsPage(PageManager manager) {
        super(manager);
    }

    @FindBy(id = "fileuploadfield-2282-button-fileInputEl")
    private WebElement selectFotoLink;

    @FindBy(id = "button-2285-btnInnerEl")
    private WebElement downloadButton;

    @FindBy(id = "button-2272-btnInnerEl")
    private WebElement editStatusLink;

    @FindBy(id = "textfield-2271-inputEl")
    private WebElement editStatusField;

    public UserSettingsPage ensurePageLoaded() {
        super.ensurePageLoaded();
        wait.until(presenceOfElementLocated(By.id("fileuploadfield-2282-button")));
        return this;
    }

    public void selectFotoLinkClick(){
        selectFotoLink.click();
    }

    public void downloadButtonClick(){
        downloadButton.click();
    }

    public boolean isDownloadButton(){
        if (downloadButton.isDisplayed()){
            return true;
        }else {
            return false;
        }
    }

    public void selectFoto(String path){
        selectFotoLink.sendKeys(path);
    }

    public UserSettingsPage editStatusLinkClick(){
        editStatusLink.click();
        return this;
    }

    public void editStatusField(String s){
        editStatusField.clear();
        editStatusField.sendKeys(s);
        editStatusField.sendKeys(Keys.ENTER);
    }

}


text:
r"""Generate melodies from a trained checkpoint of the lookback RNN model.

Example usage:
  $ bazel build magenta/models/lookback_rnn:lookback_rnn_generate

  $ ./bazel-bin/magenta/models/lookback_rnn/lookback_rnn_generate \
    --run_dir=/tmp/lookback_rnn/logdir/run1 \
    --output_dir=/tmp/lookback_rnn/generated \
    --num_outputs=10 \
    --num_steps=128 \
    --primer_melody="[60]"

See /magenta/models/shared/melody_rnn_generate.py for flag descriptions.
"""

# internal imports
import tensorflow as tf

from magenta.models.lookback_rnn import lookback_rnn_generator
from magenta.models.shared import melody_rnn_generate

def main(unused_argv):
  melody_rnn_generate.setup_logs()

  with lookback_rnn_generator.create_generator(
      melody_rnn_generate.get_checkpoint(),
      melody_rnn_generate.get_bundle(),
      melody_rnn_generate.get_steps_per_quarter(),
      melody_rnn_generate.get_hparams()) as generator:
    if melody_rnn_generate.should_save_generator_bundle():
      tf.logging.info('Saving generator bundle to %s' % (
          melody_rnn_generate.get_bundle_file()))
      generator.create_bundle_file(melody_rnn_generate.get_bundle_file())
    else:
      melody_rnn_generate.run_with_flags(generator)

def console_entry_point():
  tf.app.run(main)

if __name__ == '__main__':
  console_entry_point()


text:
import java.util.Scanner;

/**
  * 	This Class provides a method to create a new BinaryOperation. It implements the Factory interface.
  */

public class BinaryFactory implements Factory {

	public BinaryFactory(){
	}

	/**
	 * BinaryFactory reads the required parameter for a BinaryOperation and creates a new
	 * BinaryOperation.
	 *
	 * @param scanner
	 *            get threshold parameter to initialize BinaryOperation
	 * @return BinaryOperation
	 * @throws FactoryException
	 *             Thrown if no parameter given or given parameter is not included in charset
	 */

	public Operation create(Scanner scanner) throws FactoryException{

		// need to check if inside charset

		char[] param = new char[1];

		for (int i = 0; i < param.length; i++) {
			if (!scanner.hasNext()) {
				throw new FactoryException("Insufficient parameter");
			}
			String s = scanner.next();
			if (s.length() > 1) {
				throw new FactoryException("Insufficient parameter");
			}
			param[0] = s.charAt(0);
		}
		return new BinaryOperation(param[0]);
	}
}


text:
package com.tvd12.ezyfox.binding.testing;

import com.tvd12.ezyfox.binding.EzyReader;
import com.tvd12.ezyfox.binding.EzyUnmarshaller;
import com.tvd12.ezyfox.binding.annotation.EzyTemplateImpl;
import com.tvd12.ezyfox.entity.EzyObject;
import org.testng.annotations.Test;

public class EzyReaderTest {

    @Test
    public void test() {
        assert new ClassAReader().getObjectType() == ClassA.class;
        assert new ClassATemplate().getObjectType() == ClassA.class;
    }

    public static class ClassA {
    }

    public static class ClassAReader implements EzyReader<EzyObject, ClassA> {

        @Override
        public ClassA read(EzyUnmarshaller unmarshaller, EzyObject value) {
            return null;
        }
    }

    @EzyTemplateImpl
    public static class ClassATemplate implements EzyReader<EzyObject, ClassA> {

        @Override
        public ClassA read(EzyUnmarshaller unmarshaller, EzyObject value) {
            return null;
        }

    }
}


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace CompanySales.Repository.Models
{
    public partial class Product
    {
        [Key]
        [Column("ProductID")]
        public int ProductId { get; set; }
        [Required]
        [StringLength(50)]
        public string ProductName { get; set; }
        [Column(TypeName = "decimal(18, 2)")]
        public decimal? Price { get; set; }
        public int? ProductStockNumber { get; set; }
        public int? ProductSellNumber { get; set; }
    }
}


text:
package com.powerdata.openpa.tools.psmfmt;

import com.powerdata.openpa.BusList;
import com.powerdata.openpa.BusRefIndex;
import com.powerdata.openpa.PAModel;
import com.powerdata.openpa.PAModelException;
import com.powerdata.openpa.SwitchList;

public class SwitchOPA extends ExportOpenPA<SwitchList>
{
	public SwitchOPA(PAModel m, BusRefIndex bri) throws PAModelException
	{
		super(m.getSwitches(), Switch.values().length);

//		int[][] bx = bri.get2TBus(_list);
		BusRefIndex.TwoTerm bx = bri.get2TBus(_list);
		BusList buses = bri.getBuses();
		assign(Switch.ID, new StringWrap(i -> _list.getID(i)));
		assign(Switch.Name, new StringWrap(i -> _list.getName(i)));
		assign(Switch.Node1, new StringWrap(i -> buses.get(bx.getFromBus()[i]).getID()));
		assign(Switch.Node2, new StringWrap(i -> buses.get(bx.getToBus()[i]).getID()));
		assign(Switch.SwitchType,
			new StringWrap(i -> _list.isOperableUnderLoad(i)?"Type_Breaker":"Type_Disconnect"));
	}

	@Override
	protected String getPsmFmtName()
	{
		return PsmMdlFmtObject.Switch.toString();
	}
}


text:
int LSparseSet::get(int index)
{
	SparseSet<int> *s = dynamic_cast <SparseSet<int> *>(this);
	return ((*s)[index]);
}

void LSparseSet::wrapForLua (lua_State *L)
{
	using namespace luabind;

	module(L)
    [
		class_<SparseSet<int> >("JSparseSet")
		,
		class_<LSparseSet, bases<SparseSet<int> > >("SparseSet")
				.def(constructor<const SparseSet<int> &>())
				.def(constructor<>())
				.def("clear", &SparseSet<int>::clear)
				.def("isEmpty", &SparseSet<int>::isEmpty)
				.def("size", &SparseSet<int>::size)
				.def("contains", &SparseSet<int>::contains)
				.def("getNumRanges", &SparseSet<int>::getNumRanges)
				.def("getRange", &SparseSet<int>::getRange)
				.def("getTotalRange", &SparseSet<int>::getTotalRange)
				.def("addRange", &SparseSet<int>::addRange)
				.def("removeRange", &SparseSet<int>::removeRange)
				.def("invertRange", &SparseSet<int>::invertRange)
				.def("overlapsRange", &SparseSet<int>::overlapsRange)
				.def("containsRange", &SparseSet<int>::containsRange)
				.def("get", &LSparseSet::get)
	];
}


text:
#ifdef JABBERWERX_STRINGPREP_ASCII
# include <ctype.h>
#else
# include <string.h>
# include <stdlib.h>
# include <stringprep.h>
# include <idna.h>

#include "jabberwerx/util/mem.h"
#endif

#include "jabberwerx/basics.h"
#include "../include/unicode_int.h"

#ifndef JABBERWERX_STRINGPREP_ASCII

static int _stringprep(const uint8_t * str, size_t strLen,
                       uint8_t * outBuf, size_t outBufSize,
                       const Stringprep_profile * profile)
{
    // use outBuf as the in/out buffer if it is big enough.  otherwise, use
    // a temporary buffer
    char * spBuf;
    size_t spBufSize;
    if (outBufSize > strLen)
    {
        spBufSize = outBufSize;
        spBuf = (char *)outBuf;
    }
    else
    {
        spBufSize = strLen + 1;
        spBuf = jw_data_malloc(spBufSize);
        if (NULL == spBuf)
        {
            // TODO: log error
            return -1;
        }
    }

    memcpy(spBuf, str, strLen);
    spBuf[strLen]='\0';

    if (STRINGPREP_OK != stringprep(spBuf, spBufSize, 0, profile))
    {
        if ((char *)outBuf != spBuf)
        {
            jw_data_free(spBuf);
        }
        // TODO: log error
        return -1;
    }

    size_t outLen = strlen(spBuf);

    // if we allocated a temporary buffer, copy back to outbuf and clean up
    if ((char *)outBuf != spBuf)
    {
        if (outBufSize <= outLen)
        {
            jw_data_free(spBuf);
            // TODO: log error
            return -1;
        }

        memcpy(outBuf, spBuf, outLen+1);
        jw_data_free(spBuf);
    }

    return outLen;
}
#endif

///////////////////////////////////////////////////////////////////////////////
//
// public API
//

int32_t unicode_make_ace_label_int(const uint8_t * namepreppedLabel,
                                   size_t          namepreppedLabelLen,
                                   uint8_t       * aceLabelBuf,
                                   size_t          aceLabelBufSize)
{
#ifdef JABBERWERX_STRINGPREP_ASCII
    UNUSED_PARAM(namepreppedLabel);
    UNUSED_PARAM(namepreppedLabelLen);
    UNUSED_PARAM(aceLabelBuf);
    UNUSED_PARAM(aceLabelBufSize);

    return -1;
#else
    // this will all be much more efficient once we are using libicu
#define JWUNICODE_IN_BUF_SIZE 64
    char inBuf[JWUNICODE_IN_BUF_SIZE];
    char * outBuf;

    if (JWUNICODE_IN_BUF_SIZE <= namepreppedLabelLen)
    {
        // TODO: log error
        return -1;
    }

    memcpy(inBuf, namepreppedLabel, namepreppedLabelLen);
    inBuf[namepreppedLabelLen] = '\0';

    if (IDNA_SUCCESS != idna_to_ascii_8z(inBuf, &outBuf, IDNA_ALLOW_UNASSIGNED))
    {
        // TODO: log error
        return -1;
    }

    size_t outLen = strlen(outBuf);

    // if there is sufficient space in the output buffer, copy the data in
    if (aceLabelBufSize > outLen)
    {
        memcpy(aceLabelBuf, outBuf, outLen+1);
    }

    // outBuf is allocated internally to libidn with malloc; use free instead of
    // jw_data_free
    free(outBuf);
    return outLen;
#undef JWUNICODE_IN_BUF_SIZE
#endif
}

// TODO: it may be beneficial to add a strinprep cache.  further
// TODO:   research is required
int32_t unicode_nodeprep_int(const uint8_t * str, size_t strLen,
                             uint8_t * outBuf, size_t outBufSize)
{
#ifdef JABBERWERX_STRINGPREP_ASCII
    return unicode_nameprep_int(str, strLen, outBuf, outBufSize);
#else
    return _stringprep(str, strLen, outBuf, outBufSize,
                       stringprep_xmpp_nodeprep);
#endif
}

int32_t unicode_nameprep_int(const uint8_t * str, size_t strLen,
                             uint8_t * outBuf, size_t outBufSize)
{
#ifdef JABBERWERX_STRINGPREP_ASCII
    // success if all input is ascii; lcase input to output
    size_t idx;
    for (idx = 0; strLen > idx; ++idx)
    {
        if (idx >= outBufSize)
        {
            // TODO: log error
            return -1;
        }

        if (0 != (0x80 & str[idx]))
        {
            // TODO: log error
            return -1;
        }

        outBuf[idx] = tolower(str[idx]);
    }

    if (idx >= outBufSize)
    {
        // TODO: log error
        return -1;
    }
    outBuf[idx] = '\0';

    return idx;
#else
    return _stringprep(str, strLen, outBuf, outBufSize, stringprep_nameprep);
#endif
}

int32_t unicode_resourceprep_int(const uint8_t * str, size_t strLen,
                                 uint8_t * outBuf, size_t outBufSize)
{
#ifdef JABBERWERX_STRINGPREP_ASCII
    // success if all input is ascii; copy input to output
    size_t idx;
    for (idx = 0; strLen > idx; ++idx)
    {
        if (idx >= outBufSize)
        {
            // TODO: log error
            return -1;
        }

        if (0 != (0x80 & str[idx]))
        {
            // TODO: log error
            return -1;
        }

        outBuf[idx] = str[idx];
    }

    if (idx >= outBufSize)
    {
        // TODO: log error
        return -1;
    }
    outBuf[idx] = '\0';

    return idx;
#else
    return _stringprep(str, strLen, outBuf, outBufSize,
                       stringprep_xmpp_resourceprep);
#endif
}


text:
package jp.co.yahoo.dataplatform.mds.blockindex;

import java.io.IOException;
import java.nio.ByteBuffer;

import java.util.Map;
import java.util.HashMap;

public class BlockIndexNode{

  private final Map<String,BlockIndexNode> childContainer;

  private IBlockIndex blockIndex;
  private boolean isDisable;

  public BlockIndexNode(){
    childContainer = new HashMap<String,BlockIndexNode>();
  }

  public void setBlockIndex( final IBlockIndex blockIndex ){
    if( isDisable ){
      return;
    }
    if( this.blockIndex == null ){
      this.blockIndex = blockIndex;
    }
    else{
      if( ! this.blockIndex.merge( blockIndex ) ){
        disable();
      }
    }
  }

  public void disable(){
    childContainer.clear();
    blockIndex = null;
    isDisable = true;
  }

  public IBlockIndex getBlockIndex(){
    if( blockIndex == null ){
      return UnsupportedBlockIndex.INSTANCE;
    }
    return blockIndex;
  }

  public BlockIndexNode getChildNode( final String nodeName ){
    if( ! childContainer.containsKey( nodeName ) ){
      childContainer.put( nodeName , new BlockIndexNode() );
    }
    return childContainer.get( nodeName );
  }

  public void putChildNode( final String nodeName , final BlockIndexNode node ){
    childContainer.put( nodeName , node );
  }

  public int getBinarySize() throws IOException{
    if( isDisable ){
      return 0;
    }
    int length = 0;
    length += Integer.BYTES;
    if( blockIndex != null ){
      length += Integer.BYTES;
      length += RangeBlockIndexNameShortCut.getShortCutName( blockIndex.getClass().getName() ).getBytes( "UTF-8" ).length;
      length += Integer.BYTES;
      length += blockIndex.getBinarySize();
    }
    length += Integer.BYTES;
    for( Map.Entry<String,BlockIndexNode> entry : childContainer.entrySet() ){
      int childLength = entry.getValue().getBinarySize();
      if( childLength != 0 ){
        length += Integer.BYTES;
        length += Integer.BYTES;
        length += entry.getKey().getBytes( "UTF-8" ).length;
        length += Integer.BYTES;
        length += childLength;
      }
    }
    return length;
  }

  public int toBinary( final byte[] buffer , final int start ) throws IOException{
    if( isDisable ){
      return start;
    }
    int offset = start;
    ByteBuffer wrapBuffer = ByteBuffer.wrap( buffer );
    if( blockIndex == null ){
      wrapBuffer.putInt( offset , 0 );
      offset += Integer.BYTES;
    }
    else{
      wrapBuffer.putInt( offset , 1 );
      offset += Integer.BYTES;
      byte[] rangeClassNameBytes = RangeBlockIndexNameShortCut.getShortCutName( blockIndex.getClass().getName() ).getBytes( "UTF-8" );
      wrapBuffer.putInt( offset , rangeClassNameBytes.length );
      offset += Integer.BYTES;
      wrapBuffer.position( offset );
      wrapBuffer.put( rangeClassNameBytes );
      offset += rangeClassNameBytes.length;
      byte[] indexBinary = blockIndex.toBinary();
      wrapBuffer.putInt( offset , indexBinary.length );
      offset += Integer.BYTES;
      wrapBuffer.position( offset );
      wrapBuffer.put( indexBinary );
      offset += indexBinary.length;
    }
    int childCountOffset = offset;
    int childCount = 0;
    offset += Integer.BYTES;
    for( Map.Entry<String,BlockIndexNode> entry : childContainer.entrySet() ){
      byte[] childKeyNameBytes = entry.getKey().getBytes( "UTF-8" );
      int childBinaryLengthOffset = offset;
      offset += Integer.BYTES;
      int childKeyNameLengthOffset = offset;
      offset += Integer.BYTES;
      int childKeyNameOffset = offset;
      offset += childKeyNameBytes.length;
      int childEndOffset = entry.getValue().toBinary( buffer , offset );
      if( childEndOffset == offset ){
        offset = childBinaryLengthOffset;
      }
      else{
        wrapBuffer.putInt( childBinaryLengthOffset , childEndOffset - offset );
        wrapBuffer.putInt( childKeyNameLengthOffset , childKeyNameBytes.length );
        wrapBuffer.position( childKeyNameOffset );
        wrapBuffer.put( childKeyNameBytes );
        childCount++;
        offset = childEndOffset;
      }
    }
    wrapBuffer.putInt( childCountOffset , childCount );
    return offset;
  }

  public void clear(){
    childContainer.clear();
    blockIndex = null;
    isDisable = false;
  }

  public static BlockIndexNode createFromBinary( final byte[] buffer , final int start ) throws IOException{
    BlockIndexNode result = new BlockIndexNode();
    int offset = start;
    ByteBuffer wrapBuffer = ByteBuffer.wrap( buffer );
    int currentBlockIndexExists = wrapBuffer.getInt( offset );
    offset += Integer.BYTES;
    if( currentBlockIndexExists == 1 ){
      int classNameLength = wrapBuffer.getInt( offset );
      offset += Integer.BYTES;
      byte[] classNameBytes = new byte[ classNameLength ];
      wrapBuffer.position( offset );
      wrapBuffer.get( classNameBytes , 0 , classNameLength );
      offset += classNameLength;
      int indexBinaryLength = wrapBuffer.getInt( offset );
      offset += Integer.BYTES;
      byte[] indexBinary = new byte[indexBinaryLength];
      wrapBuffer.position( offset );
      wrapBuffer.get( indexBinary , 0 , indexBinaryLength );
      offset += indexBinaryLength;
      IBlockIndex blockIndex = FindBlockIndex.get( RangeBlockIndexNameShortCut.getClassName( new String( classNameBytes , "UTF-8" ) ) );
      blockIndex.setFromBinary( indexBinary , 0 , indexBinary.length );
      result.setBlockIndex( blockIndex );
    }
    int childCount = wrapBuffer.getInt( offset );
    offset += Integer.BYTES;
    for( int i = 0 ; i < childCount ; i++ ){
      int childBinaryLength = wrapBuffer.getInt( offset );
      offset += Integer.BYTES;
      int childNameLength = wrapBuffer.getInt( offset );
      offset += Integer.BYTES;
      byte[] childNameBytes = new byte[childNameLength];
      wrapBuffer.position( offset );
      wrapBuffer.get( childNameBytes , 0 , childNameBytes.length );
      offset += childNameBytes.length;
      BlockIndexNode childNode = createFromBinary( buffer , offset );
      offset += childBinaryLength;
      result.putChildNode( new String( childNameBytes , "UTF-8" ) , childNode );
    }
    return result;
  }

}


text:
@interface RKPeripheralManager : NSObject
@property(nonatomic, readonly) BOOL isAdvertising;
@property(nonatomic, readonly) CBPeripheralManagerState state;
@property (nonatomic,copy)RKObjectChangedBlock onStatedUpdated;
@property (nonatomic,copy)RKPeripheralManagerStatedChnagedBlock onWillRestoreState;
@property (nonatomic,copy)RKCentralSubscriptionBlock onSubscribedBlock;
@property (nonatomic,copy)RKCentralSubscriptionBlock onUnsubscribedBlock;
@property (nonatomic,copy)RKCentralReadRequestBlock onReceivedReadRequest;
@property (nonatomic,copy)RKCentralWriteRequestBlock onReceivedWriteRequest;
@property (nonatomic,copy)RKObjectChangedBlock onReadToUpdateSubscribers;

@property (nonatomic,strong)NSArray * services;

- (instancetype)initWithQueue:(dispatch_queue_t)queue;
- (instancetype)initWithQueue:(dispatch_queue_t)queue options:(NSDictionary *)options NS_AVAILABLE(NA, 7_0);

#pragma mark Adding and Removing Services
- (void)addService:(CBMutableService *)service onFinish:(RKSpecifiedServiceUpdatedBlock) onfinish;
- (void)removeService:(CBMutableService *)service;
- (void)removeAllServices;

#pragma mark Managing Advertising

- (void)startAdvertising:(NSDictionary *)advertisementData onStarted:(RKObjectChangedBlock) onstarted;
- (void)stopAdvertising;

#pragma mark Sending Updates of a Characteristic's Value

- (BOOL)updateValue:(NSData *)value forCharacteristic:(CBMutableCharacteristic *)characteristic onSubscribedCentrals:(NSArray *)centrals;
#pragma mark Responding to Read and Write Requests

- (void)respondToRequest:(CBATTRequest *)request withResult:(CBATTError)result;

#pragma mark Setting Connection Latency

- (void)setDesiredConnectionLatency:(CBPeripheralManagerConnectionLatency)latency forCentral:(CBCentral *)central;
@end


text:
package util

import (
	"bufio"
	"fmt"
	gobuild "go/build"
	"log"
	"os"
	"path"
	"path/filepath"
	"strings"
)

// IsGoSrcPath validate if given path is of path $GOPATH/src.
func IsGoSrcPath(filePath string) bool {
	for _, gopath := range getGoPaths() {
		goSrc := path.Join(gopath, "src")
		if filePath == goSrc {
			return true
		}
	}

	return false
}

// IsUnderGoSrcPath validate if given path is under path $GOPATH/src.
func IsUnderGoSrcPath(filePath string) bool {
	for _, gopath := range getGoPaths() {
		goSrc := path.Join(gopath, "src")
		if strings.HasPrefix(filepath.Dir(filePath), goSrc) {
			return true
		}
	}

	return false
}

// DirToGoPkg returns the Gopkg for the given directory if it exists
// under a GOPATH otherwise returns error. For example,
// /Users/x/go/src/github.com/y/z ==> github.com/y/z
func DirToGoPkg(dir string) (pkg string, err error) {
	goPaths := getGoPaths()
	for _, gopath := range goPaths {
		goSrc := path.Join(gopath, "src")
		if !strings.HasPrefix(dir, goSrc) {
			continue
		}
		pkg, err := filepath.Rel(goSrc, dir)
		if err == nil {
			return pkg, err
		}
	}

	return "", fmt.Errorf("dir '%s' does not exist under any GOPATH %v", dir, goPaths)
}

func getGoPaths() []string {
	gopaths := os.Getenv("GOPATH")
	if len(gopaths) == 0 {
		gopaths = gobuild.Default.GOPATH
	}
	return filepath.SplitList(gopaths)
}

// PathHasProjectFile validate if PROJECT file exists under the path.
func PathHasProjectFile(filePath string) bool {
	if _, err := os.Stat(path.Join(filePath, "PROJECT")); os.IsNotExist(err) {
		return false
	}

	return true
}

// GetDomainFromProject get domain information from the PROJECT file under the path.
func GetDomainFromProject(rootPath string) string {
	var domain string

	file, err := os.Open(path.Join(rootPath, "PROJECT"))
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := file.Close(); err != nil {
			log.Fatal(err)
		}
	}()

	scanner := bufio.NewScanner(file)
	for scanner.Scan() {
		if strings.HasPrefix(scanner.Text(), "domain:") {
			domainInfo := strings.Split(scanner.Text(), ":")
			if len(domainInfo) != 2 {
				log.Fatalf("Unexpected domain info: %s", scanner.Text())
			}
			domain = strings.Replace(domainInfo[1], " ", "", -1)
			break
		}
	}

	return domain
}


text:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="ca.ualberta.cs.xpertsapp.views.OutgoingOfferActivity">

</menu>


text:
execute_process(
   COMMAND ${OBJDUMP} --no-show-raw-insn -dC -j .text ${BINARY}
   COMMAND grep -A3 " <test"
   COMMAND sed 1d
   COMMAND cut -d: -f2
   COMMAND xargs echo
   OUTPUT_VARIABLE asm)
string(STRIP "${asm}" asm)

if("${asm}" MATCHES "%esp")
   set(x86_32 TRUE)
else()
   set(x86_32 FALSE)
endif()
set(expect_failure FALSE)

# Note the regex parts looking for %esp can only match on ia32. (Not sure about x32, though)
# 'retq' on the other hand, can only match on x64
if("${IMPL}" STREQUAL SSE)
   set(reference "(^addps %xmm(0,%xmm1 movaps %xmm1,%xmm0 retq|1,%xmm0 retq)|vaddps %xmm(0,%xmm1|1,%xmm0),%xmm0 retq|.*v?movaps 0x[12]4\\(%esp\\),%xmm[01]( | .+ )v?(add|mova)ps 0x[12]4\\(%esp\\),%xmm[01])")
   if(x86_32 AND COMPILER_IS_CLANG AND "${SYSTEM_NAME}" STREQUAL "Linux")
      set(expect_failure TRUE)
   endif()
elseif("${IMPL}" STREQUAL AVX OR "${IMPL}" STREQUAL AVX2)
   set(reference "(^vaddps %ymm(0,%ymm1|1,%ymm0),%ymm0 retq|vmovaps 0x[24]4\\(%esp\\),%ymm[01]( | .+ )v(add|mova)ps 0x[24]4\\(%esp\\),%ymm[01],%ymm)")
   if(x86_32 AND COMPILER_IS_CLANG AND "${SYSTEM_NAME}" STREQUAL "Linux")
      set(expect_failure TRUE)
   endif()
elseif("${IMPL}" STREQUAL MIC)
   set(reference "^vaddps %zmm(0,%zmm1|1,%zmm0),%zmm0 retq")
else()
   message(FATAL_ERROR "Unknown IMPL '${IMPL}'")
endif()

if("${asm}" MATCHES "${reference}")
   if(expect_failure)
      message(FATAL_ERROR "Warning: unexpected pass. The test was flagged as EXPECT_FAILURE but passed instead.")
   else()
      message("PASS: Vector<T> ABI")
   endif()
elseif(expect_failure)
   message("Expected Failure.\n'${asm}'\n  does not match\n'${reference}'")
else()
   message(FATAL_ERROR "Failed.\n'${asm}'\n  does not match\n'${reference}'")
endif()

#######################################################################
# test Mask<T> ABI
#######################################################################
if("${IMPL}" STREQUAL MIC)
   set(reference "%di,.*%si,") # needs to read from %di and %si
endif()

execute_process(
   COMMAND ${OBJDUMP} --no-show-raw-insn -dC -j .text ${BINARY}
   COMMAND grep -A3 " <mask_test"
   COMMAND sed 1d
   COMMAND cut -d: -f2
   COMMAND xargs echo
   OUTPUT_VARIABLE asm)
string(STRIP "${asm}" asm)
string(REPLACE "add" "and" reference "${reference}")
if("${asm}" MATCHES "${reference}")
   if(expect_failure)
      message(FATAL_ERROR "Warning: unexpected pass. The test was flagged as EXPECT_FAILURE but passed instead.")
   else()
      message("PASS: Mask<T> ABI")
   endif()
elseif(expect_failure)
   message("Expected Failure.\n'${asm}'\n  does not match\n'${reference}'")
else()
   message(FATAL_ERROR "Failed.\n'${asm}'\n  does not match\n'${reference}'")
endif()


text:
namespace ChilliSource
{
    //---------------------------------------------------------------------
    /// A particle affector which will change the size of particles over
    /// its lifetime by the calculated scale factor.
    ///
    /// @author Ian Copland
    //---------------------------------------------------------------------
    class ScaleOverLifetimeParticleAffector final : public ParticleAffector
    {
    public:
        //----------------------------------------------------------------
        /// Stores the initial size and generates the scale factor for the
        /// activated particle so it can be used to generate the
        /// interpolated size during updates.
        ///
        /// @author Ian Copland
        ///
        /// @param The index of the particle to activate.
        /// @param The current normalised (0.0 to 1.0) progress through
        /// playback of the particle effect.
        //----------------------------------------------------------------
        void ActivateParticle(u32 in_index, f32 in_effectProgress) override;
        //----------------------------------------------------------------
        /// Updates the size of each particle.
        ///
        /// @author Ian Copland
        ///
        /// @param The delta time.
        /// @param The current normalised (0.0 to 1.0) progress through
        /// playback of the particle effect.
        //----------------------------------------------------------------
        void AffectParticles(f32 in_deltaTime, f32 in_effectProgress) override;
        //----------------------------------------------------------------
        /// Destructor
        ///
        /// @author Ian Copland
        //----------------------------------------------------------------
        virtual ~ScaleOverLifetimeParticleAffector() {};
    private:
        friend class ScaleOverLifetimeParticleAffectorDef;
        //----------------------------------------------------------------
        /// Constructor.
        ///
        /// @author Ian Copland
        ///
        /// @param The particle affector definition.
        /// @param The particle array.
        //----------------------------------------------------------------
        ScaleOverLifetimeParticleAffector(const ParticleAffectorDef* in_affectorDef, dynamic_array<Particle>* in_particleArray);
        //----------------------------------------------------------------
        /// A container for the initial scale and scale factor of a single
        /// particle.
        ///
        /// @author Ian Copland.
        //----------------------------------------------------------------
        struct ScaleData
        {
            Vector2 m_initialScale;
            Vector2 m_targetScale;
        };

        const ScaleOverLifetimeParticleAffectorDef* m_scaleOverLifetimeAffectorDef = nullptr;
        dynamic_array<ScaleData> m_particleScaleData;
    };
}

#endif


text:
/*
 * DO NOT EDIT.  THIS FILE IS GENERATED FROM /builds/slave/rel-2.0-xr-osx64-bld/build/dom/interfaces/svg/nsIDOMSVGPathSegList.idl
 */

#ifndef __gen_nsIDOMSVGPathSegList_h__
#define __gen_nsIDOMSVGPathSegList_h__

#ifndef __gen_domstubs_h__
#include "domstubs.h"
#endif

/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIDOMSVGPathSeg; /* forward declaration */

/* starting interface:    nsIDOMSVGPathSegList */
#define NS_IDOMSVGPATHSEGLIST_IID_STR "94a6db98-3f34-4529-a35f-89ef49713795"

#define NS_IDOMSVGPATHSEGLIST_IID \
  {0x94a6db98, 0x3f34, 0x4529, \
    { 0xa3, 0x5f, 0x89, 0xef, 0x49, 0x71, 0x37, 0x95 }}

class NS_NO_VTABLE NS_SCRIPTABLE nsIDOMSVGPathSegList : public nsISupports {
 public:

  NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSVGPATHSEGLIST_IID)

  /* readonly attribute unsigned long numberOfItems; */
  NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems) = 0;

  /* void clear (); */
  NS_SCRIPTABLE NS_IMETHOD Clear(void) = 0;

  /* nsIDOMSVGPathSeg initialize (in nsIDOMSVGPathSeg newItem); */
  NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) = 0;

  /* nsIDOMSVGPathSeg getItem (in unsigned long index); */
  NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) = 0;

  /* nsIDOMSVGPathSeg insertItemBefore (in nsIDOMSVGPathSeg newItem, in unsigned long index); */
  NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) = 0;

  /* nsIDOMSVGPathSeg replaceItem (in nsIDOMSVGPathSeg newItem, in unsigned long index); */
  NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) = 0;

  /* nsIDOMSVGPathSeg removeItem (in unsigned long index); */
  NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) = 0;

  /* nsIDOMSVGPathSeg appendItem (in nsIDOMSVGPathSeg newItem); */
  NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) = 0;

};

  NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSVGPathSegList, NS_IDOMSVGPATHSEGLIST_IID)

/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIDOMSVGPATHSEGLIST \
  NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems); \
  NS_SCRIPTABLE NS_IMETHOD Clear(void); \
  NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM); \
  NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM);

/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIDOMSVGPATHSEGLIST(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems) { return _to GetNumberOfItems(aNumberOfItems); } \
  NS_SCRIPTABLE NS_IMETHOD Clear(void) { return _to Clear(); } \
  NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return _to Initialize(newItem, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return _to GetItem(index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return _to InsertItemBefore(newItem, index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return _to ReplaceItem(newItem, index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return _to RemoveItem(index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return _to AppendItem(newItem, _retval); }

/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIDOMSVGPATHSEGLIST(_to) \
  NS_SCRIPTABLE NS_IMETHOD GetNumberOfItems(PRUint32 *aNumberOfItems) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetNumberOfItems(aNumberOfItems); } \
  NS_SCRIPTABLE NS_IMETHOD Clear(void) { return !_to ? NS_ERROR_NULL_POINTER : _to->Clear(); } \
  NS_SCRIPTABLE NS_IMETHOD Initialize(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Initialize(newItem, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD GetItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetItem(index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD InsertItemBefore(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->InsertItemBefore(newItem, index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD ReplaceItem(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->ReplaceItem(newItem, index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD RemoveItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveItem(index, _retval); } \
  NS_SCRIPTABLE NS_IMETHOD AppendItem(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->AppendItem(newItem, _retval); }

#if 0
/* Use the code below as a template for the implementation class for this interface. */

/* Header file */
class nsDOMSVGPathSegList : public nsIDOMSVGPathSegList
{
public:
  NS_DECL_ISUPPORTS
  NS_DECL_NSIDOMSVGPATHSEGLIST

  nsDOMSVGPathSegList();

private:
  ~nsDOMSVGPathSegList();

protected:
  /* additional members */
};

/* Implementation file */
NS_IMPL_ISUPPORTS1(nsDOMSVGPathSegList, nsIDOMSVGPathSegList)

nsDOMSVGPathSegList::nsDOMSVGPathSegList()
{
  /* member initializers and constructor code */
}

nsDOMSVGPathSegList::~nsDOMSVGPathSegList()
{
  /* destructor code */
}

/* readonly attribute unsigned long numberOfItems; */
NS_IMETHODIMP nsDOMSVGPathSegList::GetNumberOfItems(PRUint32 *aNumberOfItems)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* void clear (); */
NS_IMETHODIMP nsDOMSVGPathSegList::Clear()
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMSVGPathSeg initialize (in nsIDOMSVGPathSeg newItem); */
NS_IMETHODIMP nsDOMSVGPathSegList::Initialize(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMSVGPathSeg getItem (in unsigned long index); */
NS_IMETHODIMP nsDOMSVGPathSegList::GetItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMSVGPathSeg insertItemBefore (in nsIDOMSVGPathSeg newItem, in unsigned long index); */
NS_IMETHODIMP nsDOMSVGPathSegList::InsertItemBefore(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMSVGPathSeg replaceItem (in nsIDOMSVGPathSeg newItem, in unsigned long index); */
NS_IMETHODIMP nsDOMSVGPathSegList::ReplaceItem(nsIDOMSVGPathSeg *newItem, PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMSVGPathSeg removeItem (in unsigned long index); */
NS_IMETHODIMP nsDOMSVGPathSegList::RemoveItem(PRUint32 index, nsIDOMSVGPathSeg **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* nsIDOMSVGPathSeg appendItem (in nsIDOMSVGPathSeg newItem); */
NS_IMETHODIMP nsDOMSVGPathSegList::AppendItem(nsIDOMSVGPathSeg *newItem, nsIDOMSVGPathSeg **_retval NS_OUTPARAM)
{
    return NS_ERROR_NOT_IMPLEMENTED;
}

/* End of implementation class template. */
#endif

#endif /* __gen_nsIDOMSVGPathSegList_h__ */


text:
export { Converters } from './Converters';
export { EmojiEditor } from './EmojiEditor';
export { EmojiCategory } from './EmojiCategory';
export { Emoji } from './Emoji';

import { EmojiPicker } from './EmojiPicker';
export default EmojiPicker;


text:
package io.cereebro.snitch;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import io.cereebro.core.ApplicationAnalyzer;
import io.cereebro.core.RelationshipDetector;
import io.cereebro.snitch.actuate.CereebroWebMvcEndpointConfiguration;

/**
 * Cereebro Snitch configuration entry point.
 *
 * @author michaeltecourt
 */
@Configuration
@EnableConfigurationProperties({ CereebroProperties.class })
@Import({ CereebroRelationshipDetectorsAutoConfiguration.class, CereebroWebMvcEndpointConfiguration.class })
public class CereebroSnitchAutoConfiguration {

    @Autowired
    private CereebroProperties cereebroProperties;

    @Autowired
    private ObjectMapper objectMapper;

    @Bean
    @ConditionalOnMissingBean
    public ApplicationAnalyzer applicationAnalyzer(List<RelationshipDetector> detectors) {
        return new SpringBootApplicationAnalyzer(cereebroProperties, detectors);
    }

    @Bean
    @ConditionalOnProperty(prefix = "cereebro.snitch", name = "log-on-startup", havingValue = "true", matchIfMissing = false)
    public Slf4jSnitchLogger snitchLogger(ApplicationAnalyzer analyzer) {
        return new Slf4jSnitchLogger(analyzer, copyObjectMapperWithoutIndentation());
    }

    /**
     * Copy the object auto-configure ObjectMapper settings, but force the JSON
     * output on single line to be logged.
     *
     * @return ObjectMapper with indent_output serialization feature set to
     *         {@code false}.
     */
    private ObjectMapper copyObjectMapperWithoutIndentation() {
        ObjectMapper noIdentationMapper = new ObjectMapper(objectMapper.getFactory());
        noIdentationMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
        return noIdentationMapper;
    }

    @Bean
    @ConditionalOnProperty(prefix = "cereebro.snitch.file", name = "enabled", havingValue = "true", matchIfMissing = false)
    public FileWriterSnitch fileSnitch(ApplicationAnalyzer analyzer) {
        return new FileWriterSnitch(analyzer, objectMapper, cereebroProperties);
    }

}


text:
from django.contrib import admin

from .forms import recurringevent_admin_form
from .models import RecurringEvent, SpecialEvent

@admin.register(SpecialEvent)
class SpecialEventAdmin(admin.ModelAdmin):
    list_display = ('title', 'start', 'published')
    list_filter = ('start', 'published')
    ordering = ('-start',)
    date_hierarchy = 'start'
    prepopulated_fields = {
        'slug': ('title',)
    }

@admin.register(RecurringEvent)
class RecurringEventAdmin(admin.ModelAdmin):
    list_display = ('title', 'day_of_the_week', 'time', 'published')
    list_filter = ('day_of_the_week', 'published')
    form = recurringevent_admin_form()


text:
<?php

defined('_JEXEC') or die('Restricted access');

class CTableMultiProfile extends JTable
{
	var $id			= null;
	var $name		= null;
	var $description= null;
	var $approvals	= null;
	var $published	= null;
	var $avatar		= null;
	var $thumb		= null;
	var $created	= null;
  	var $watermark	= null;
  	var $watermark_hash		= null;
  	var $watermark_location	= null;
	var $create_groups	= null;
	var $create_events	= null;
	var $profile_lock = null;
  	var $ordering		= null;

	public function __construct( &$db )
	{
		parent::__construct( '#__community_profiles', 'id', $db );
	}

	public function getWatermark()
	{
		return JURI::root() . $this->watermark;
	}

	/**
	 * Retrieve the profile type avatar
	 **/
	public function getThumbAvatar()
	{
		if( empty($this->thumb) )
		{
			return JURI::root() . DEFAULT_USER_THUMB;
		}
		return JURI::root() . $this->thumb;
	}

	/**
	 * Retrieve the profile type avatar
	 **/
	public function getAvatar()
	{
		return JURI::root() . $this->avatar;
	}

	public function getName()
	{
	    if( empty( $this->name ) )
	    {
	        return JText::_('COM_COMMUNITY_DEFAULT_PROFILE_TYPE');
		}

		return $this->name;
	}
	/**
	 * Retrieve a multiprofile mapping for a given multi profile.
	 *
	 * @return	Object	An object of #__community_multiprofiles_fields
	 **/
	public function getChild( $fieldId , $multiprofileId )
	{
		$db		= JFactory::getDBO();
		$query	= 'SELECT * FROM ' . $db->quoteName('#__community_profiles_fields')
				. ' WHERE ' . $db->quoteName( 'field_id' ) . '=' . $db->Quote( $fieldId )
				. ' AND ' . $db->quoteName( 'parent' ) . '=' . $db->Quote( $multiprofileId );
		$db->setQuery( $query );

		$result	= $db->loadObject();

		return $result;
	}

	/**
	 * Override paren't store method so we can do some checking with the watermarks.
	 *
	 * @return	bool	True on success.
	 **/
	public function store( $updateNulls = false )
	{
		if( !$this->id )
		{
			$this->ordering		= parent::getNextOrder();
		}

		parent::store();
	}

	/**
	 * Override parents delete method
	 **/
	public function delete( $pk = null)
	{
		parent::delete();

		// @rule: Deleting a multiple profile should revert all users using it to the default profile
		$db		= JFactory::getDBO();
		$query	= 'UPDATE ' . $db->quoteName('#__community_users') . ' SET ' . $db->quoteName('profile_id') . '=' . $db->Quote( COMMUNITY_DEFAULT_PROFILE ) . ' '
				. 'WHERE ' . $db->quoteName('profile_id') . '=' . $db->Quote( $this->id );
		$db->setQuery( $query );
		$db->Query();

		// @rule: Delete all childs related to this multiprofile
		$this->deleteChilds();
	}

	/**
	 * Delete all existing childs in commmunity_multiprofiles_fields
	 *
	 * @return	bool	True on success.
	 **/
	public function deleteChilds()
	{
		$db		= JFactory::getDBO();
		$query	= 'DELETE FROM ' . $db->quoteName('#__community_profiles_fields') . ' WHERE ' . $db->quoteName( 'parent' ) . '=' . $db->Quote( $this->id );
		$db->setQuery( $query );
		$db->Query();

		return true;
	}

	public function isChild( $fieldId )
	{
		if( $this->id == 0 )
			return false;

		if( $this->getChild( $fieldId , $this->id ) )
		{
			return true;
		}

		return false;
	}

	/**
	 * Checks if the current profile type has users already assigned.
	 *
	 * @params
	 * @return	Boolean	True if there are still users assigned to this profile type.
	 **/
	public function hasUsers()
	{
		$db		= JFactory::getDBO();
		$query	= 'SELECT COUNT(1) FROM ' . $db->quoteName( '#__community_users' ) . ' '
				. 'WHERE ' . $db->quoteName( 'profile_id' ) . '=' . $db->Quote( $this->id );
		$db->setQuery( $query );

		$result	= $db->loadResult() > 0 ? true : false;

		return $result;
	}

	/**
	 * Check current avatar's hash
	 **/
	public function isHashMatched( $profileType , $hash )
	{
		// @rule: backward compatibility. In 2.0, the hash column is a new column.
		if( empty($hash ) )
		{
			return true;
		}

		static $types	= array();
		$match			= true;

		if( empty($types) )
		{
			$model	= CFactory::getModel( 'Profile' );
			$rows	= $model->getProfileTypes();

			if( $rows )
			{
				foreach( $rows as $row )
				{
					$types[ $row->id ]	= $row;
				}
			}
		}

		if( isset( $types[ $profileType ] ) )
		{
			$match	= $types[ $profileType ]->watermark_hash == $hash;
		}

		return $match;
	}

	/**
	 * Updates existing default image that is already stored in the community_users table.
	 *
	 * @param	String	$type	Type of image, thumb or avatar.
	 * @param	String	$oldPath	The path for the old image.
	 *
	 * @return	Boolean		True on success false otherwise.
	 **/
	public function updateUserDefaultImage( $type , $oldPath )
	{
		$db		= JFactory::getDBO();
		$query	= 'UPDATE ' . $db->quoteName( '#__community_users' ) . ' '
				. 'SET ' . $db->quoteName( $type ) . '=' . $db->Quote( $this->$type ) . ' '
				. 'WHERE ' . $db->quoteName( $type ) . '=' . $db->Quote( $oldPath );
		$db->setQuery( $query );
		$db->Query();

		// Remove the old files.
		$oldImagePath = JPATH_ROOT .'/'. CString::str_ireplace( '/' , '/' , $oldPath );

		if( JFile::exists( $oldImagePath ) )
		{
			JFile::delete( $oldImagePath );
		}

		if($db->getErrorNum())
		{
			return false;
	    }

	    return true;
	}

	public function updateUserThumb( $user , $hashName )
	{
		$this->_updateUserWatermark( $user , 'thumb' , $hashName );
	}

	public function updateUserAvatar( $user , $hashName )
	{
		$this->_updateUserWatermark( $user , 'avatar' , $hashName );
	}

	private function _updateUserWatermark( $user , $type , $hashName )
	{
		$config		= CFactory::getConfig();

		// @rule: This is the original avatar path
		//CFactory::load( 'helpers' , 'image' );
		$userImageType	= '_' . $type;
		$data			= @getimagesize( JPATH_ROOT .'/'. CString::str_ireplace( '/' , '/' , $user->$userImageType ) );
		$original		= JPATH_ROOT .'/images/watermarks/original' .'/'. md5( $user->id . '_' . $type ) . CImageHelper::getExtension( $data[ 'mime' ] );

		if( !$config->get('profile_multiprofile') || !JFile::exists( $original ) )
		{
			return false;
		}

		static $types	= array();

		if( empty($types) )
		{
			$model	= CFactory::getModel( 'Profile' );
			$rows	= $model->getProfileTypes();

			if( $rows )
			{
				foreach( $rows as $row )
				{
					$types[ $row->id ]	= $row;
				}
			}
		}
		$model			= CFactory::getModel( 'User' );

		if( isset( $types[ $user->_profile_id ] ) )
		{
			// Bind the data to the current object so we can access it here.
			$this->bind( $types[ $user->_profile_id ] );

			// Path to the watermark image.
			$watermarkPath	= JPATH_ROOT .'/'. CString::str_ireplace('/' , '/' , $this->watermark);

			// Retrieve original image info
			$originalData	= getimagesize( $original );

			// Generate image file name.
			$fileName	= ( $type == 'thumb' ) ? 'thumb_' : '';
			$fileName	.= $hashName;
			$fileName	.= CImageHelper::getExtension( $originalData[ 'mime' ] );

			// Absolute path to the image (local)
			$newImagePath	= JPATH_ROOT .'/'. $config->getString('imagefolder') .'/avatar' .'/'. $fileName;

			// Relative path to the image (uri)
			$newImageUri	= $config->getString('imagefolder') . '/avatar/' . $fileName;

			// Retrieve the height and width for watermark and original image.
			list( $watermarkWidth , $watermarkHeight )	= getimagesize( $watermarkPath );
			list( $originalWidth , $originalHeight )	= getimagesize( $original );

			// Retrieve the proper coordinates to the watermark location
			$position	= CImageHelper::getPositions( $this->watermark_location , $originalWidth , $originalHeight , $watermarkWidth , $watermarkHeight );

			// Create the new image with the watermarks.
			CImageHelper::addWatermark( $original , $newImagePath , $originalData[ 'mime' ] , $watermarkPath , $position->x , $position->y , false );
			$model->setImage( $user->id , $newImageUri , $type );

			// Remove the user's old image
			$oldFile	= JPATH_ROOT .'/'. CString::str_ireplace( '/' , '/' , $user->$userImageType );

			if( JFile::exists( $oldFile ) )
			{
				JFile::delete($oldFile);
			}

			// We need to update the property in CUser as well otherwise when we save the hash, it'll
			// use the old user avatar.
			$user->set( $userImageType , $newImageUri );

			// We need to restore the storage method.
			$user->set( '_storage' , 'file' );

			// Update the watermark hash with the latest hash
			$user->set( '_watermark_hash' , $this->watermark_hash );
			$user->save();

		}
		return true;
	}
}


text:
using System;

namespace FlatRedBall
{
	public static partial class FlatRedBallServices
	{
	}
}


text:
SECONDS=0

test_stack_deploy() {
  amp -k stack up -c tests/cli/service/list/global.service.yml global || return 1
  amp -k stack up -c tests/cli/service/list/replicated.service.yml replicated
}

test_service_starting() {
  amp -k service ls 2>/dev/null | pcregrep -q "global_pinger\s*.*s*(STARTING|RUNNING)\s*appcelerator/pinger" || return 1
  amp -k service ls 2>/dev/null | pcregrep -q "replicated_pinger\s*.*\s*(STARTING|RUNNING)\s*appcelerator/pinger"
}

# FIXME: this test is not reliable, test condition and usage of the internal variable SECONDS
test_service_global_running() {
  while true
  do
     if amp -k service ls 2>/dev/null | grep -q "\s*global_pinger\s*global\s*1/1\s*RUNNING\s*" || [ $SECONDS -eq 5 ]
     then
             break
     fi
     sleep 1
     SECONDS=$[$SECONDS+1]
  done
}

# FIXME: this test is not reliable, test condition and usage of the internal variable SECONDS
test_service_replicated_running() {
  while true
  do
     if amp -k service ls 2>/dev/null | grep -q "\s*replicated_pinger\s*replicated\s*1/1\s*RUNNING\s*" || [ $SECONDS -eq 5 ]
     then
             break
     fi
     sleep 1
     SECONDS=$[$SECONDS+1]
  done
}


text:
<!DOCTYPE HTML>

<title>Uses of Class org.opensextant.output.WKTFormatter (Xponents Core API)</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="dc.created" content="2022-02-02">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<link rel="stylesheet" type="text/css" href="../../../../jquery/jquery-ui.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

SEARCH:
<input type="text" id="search" value="search" disabled="disabled">
<input type="reset" id="reset" value="reset" disabled="disabled">

Uses of Class
org.opensextant.output.WKTFormatter

No usage of org.opensextant.output.WKTFormatter

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

copyright             OpenSextant.org, 2013-2021

Copyright © 2013–2022. All rights reserved.


text:
package org.apache.fontbox.ttf.model;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 *
 * A {@link Map} based simple implementation of the {@link ScriptFeature}
 *
 * @author Palash Ray
 *
 */
public class MapBackedScriptFeature implements ScriptFeature
{

    private final String name;
    private final Map<List<Integer>, Integer> featureMap;

    public MapBackedScriptFeature(String name, Map<List<Integer>, Integer> featureMap)
    {
        this.name = name;
        this.featureMap = featureMap;
    }

    @Override
    public String getName()
    {
        return name;
    }

    @Override
    public Set<List<Integer>> getAllGlyphIdsForSubstitution()
    {
        return featureMap.keySet();
    }

    @Override
    public boolean canReplaceGlyphs(List<Integer> glyphIds)
    {
        return featureMap.containsKey(glyphIds);
    }

    @Override
    public Integer getReplacementForGlyphs(List<Integer> glyphIds)
    {
        if (!canReplaceGlyphs(glyphIds))
        {
            throw new UnsupportedOperationException(
                    "The glyphs " + glyphIds + " cannot be replaced");
        }
        return featureMap.get(glyphIds);
    }

    @Override
    public int hashCode()
    {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((featureMap == null) ? 0 : featureMap.hashCode());
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj)
    {
        if (this == obj)
        {
            return true;
        }
        if (obj == null)
        {
            return false;
        }
        if (getClass() != obj.getClass())
        {
            return false;
        }
        MapBackedScriptFeature other = (MapBackedScriptFeature) obj;
        if (featureMap == null)
        {
            if (other.featureMap != null)
            {
                return false;
            }
        }
        else if (!featureMap.equals(other.featureMap))
        {
            return false;
        }
        if (name == null)
        {
            if (other.name != null)
            {
                return false;
            }
        }
        else if (!name.equals(other.name))
        {
            return false;
        }
        return true;
    }
}


text:
<?php

namespace igorw;

class FailingTooHardException extends \Exception {}

function retry($retries, callable $fn)
{
    beginning:
    try {
        return $fn();
    } catch (\Exception $e) {
        if (!$retries) {
            throw new FailingTooHardException('', 0, $e);
        }
        $retries--;
        goto beginning;
    }
}


text:
from rest_framework import serializers

from version.models import *

class VersionSerializer(serializers.ModelSerializer):
    owner = serializers.ReadOnlyField(source='owner.username')

    def update(self, instance, validated_data):
        instance.name = validated_data['name']
        instance.save()
        return instance

    class Meta:
        model = Version
        fields = '__all__'


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN">

<title>JaccardSimilarity Fields</title>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <meta name="generator" content="Doc-O-Matic">
    <link rel="STYLESHEET" href="default.css" type="text/css">

SimMetrics library v 1.5 for .NET 2.0

Contents | Index | Reference

JaccardSimilarity Fields

JaccardSimilarity | Legend

Fields

Field
Description

 defaultMismatchScore
This is defaultMismatchScore, a member of class JaccardSimilarity.

Copyright (c) 2006. All rights reserved.

Contents | Index | Reference


text:
(function() {
	var rootWindow = null;

	if (OS_IOS) {
		rootWindow = $.doubanAuthNav;
	} else if (OS_ANDROID) {
		rootWindow = $.doubanAuthWindow;
	}

	var DoubanAPI = require("DoubanAPI");
	var url = "https://www.douban.com/service/auth2/auth";
	$.doubanAuthWebView.addEventListener("beforeload", function(e) {
		if(0 == e.url.indexOf(DoubanAPI.redirectUri)) {
			this.stopLoading();
			var urllib = require("url");
			var param = urllib.queryParameters(e.url);
			var code = param["code"];
			var xhr = Ti.Network.createHTTPClient({
				onload: function(e) {
					console.log(this.responseText);
					var param = JSON.parse(this.responseText);
					var token = param["access_token"];
					if (token) {
						Ti.App.Properties.setString("AccessToken", param["access_token"]);
						Ti.App.Properties.setString("RefreshToken", param["refresh_token"]);
						Ti.App.Properties.setString("UserId", param["douban_user_id"]);
						var expires = param["expires_in"];
						expires = Math.floor(Date.now()/1000 + expires);
						Ti.App.Properties.setInt("Expires", expires);
						console.log("get token:" + param["access_token"]);
						rootWindow.close();
					}
					else {

					}
				},
				onerror: function(e) {
					console.log("error:" + e.error + "(" + this.responseText + ")");
				}
			});
			xhr.open("POST", "https://www.douban.com/service/auth2/token");
			xhr.send({
				client_id : DoubanAPI.apikey,
				client_secret : DoubanAPI.secret,
				redirect_uri : DoubanAPI.redirectUri,
				grant_type : "authorization_code",
				code : code
			});
		}
	});
	$.doubanAuthWebView.setUrl(url + "?client_id=" + DoubanAPI.apikey
							 + "&redirect_uri=" + DoubanAPI.redirectUri
							 + "&response_type=code"
							 + "&scope=shuo_basic_r,shuo_basic_w,douban_basic_common");
							 })();


text:
<!DOCTYPE html>

        <meta charset="utf-8">

        <title>Pivot | Launching Soon</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <link href="css/flexslider.min.css" rel="stylesheet" type="text/css" media="all"/>
        <link href="css/line-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
        <link href="css/elegant-icons.min.css" rel="stylesheet" type="text/css" media="all"/>
        <link href="css/lightbox.min.css" rel="stylesheet" type="text/css" media="all"/>
        <link href="css/bootstrap.min.css" rel="stylesheet" type="text/css" media="all"/>
        <link href="css/theme-rocklobster.css" rel="stylesheet" type="text/css" media="all"/>

        <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,400,300,600,700%7CRaleway:700' rel='stylesheet' type='text/css'>

Home Pages

Home Layouts

Home Classic

Home Education

Home Business

Home Agency

Home Layouts

Home Corporate

Home Personal

Service Launch

Product Launch

Home Layouts

Home Resume

Launch with video

Launch with countdown

One Page

											Build your own
											Purchase Pivot

Pages

About Us

About Us 2

Services

Services 2

Login

404 Error

500 Error

Blog

Article Lists

Masonry

Masonry Sidebar

Blog Large List

Blog Image List

Article Singles

Article Basic

Article Basic 2

Article Sidebar

Article Media

Projects

Projects Fullwidth

Projects Contained

Project Single

Project Single 2

Contact

Large Map

Map with form

Header with form

Fullscreen photo

Welcome to our amazing new service
sign up now and experience the pure goodness

											<input class="form-email" type="text" placeholder="Email Address">

											<input class="form-password" type="password" placeholder="Password">

											<input class="form-password2" type="password" placeholder="Confirm Password">

											<input type="submit" class="btn btn-primary btn-filled" value="Start My Free Trial">

								30 Day risk free trial - No credit card required

Our latest product has all the fancy features you could want

								Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labor. Et harum quidem rerum.

					<video autoplay="" muted="" loop="">
						<source src="video/video.webm" type="video/webm">
						<source src="video/video.mp4" type="video/mp4">
						<source src="video/video.ogv" type="video/ogg">
					</video>

Awesome Video Dividers

								Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.

							See More
							Purchase

Compare features of
our popular pricing plans

Storage Space

Unique Logins

Offsite Backup

Support Hours

Bandwidth

Starter

100GB

200Users

No Backup

Standard Support

20GB

									$
									29
									/mo

								Sign Me Up

Business

200GB

400Users

2TB

Standard Support

40GB

									$
									49
									/mo

								Sign Me Up

Corporate

400GB

800Users

4TB

24/7

90GB

									$
									69
									/mo

								Sign Me Up

Pivot is hands down the most flexible and enjoyable HTML template I've ever used. I was a startup framework die-hard but now my eyes have been opened to the sheer power of Variant page builder, I won't be going back!

										Louise Duke - Mother Goose

I was getting fed up with the hassle of setting up bloated WordPress themes. Luckily I've now found Pivot with Variant. Building pages in real-time without a CMS gives me all the power and flexibility I could want.

										Elizabeth Atkinson - Shapewear Australia

The plethora of content blocks available in Pivot has made it my go-to template of choice. I've already used it for a number of clients - all of which have been thrilled with the outcome. Well done Medium Rare!

										Toby Whittaker - Design Dojo

Get In Touch

							hello@mrare.co

							© Copright 2014 Medium Rare - All Rights Reserved


text:
<?xml version="1.0" encoding="utf-8"?>
<DataCommand xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <Name>Resource_GetByResourceSet</Name>
  <DataConnection>Default</DataConnection>
  <Type>StoredProcedure</Type>
  <Text>Resource_GetByResourceSet</Text>
  <ReturnType>DataTable</ReturnType>
  <Parameters>
    <Parameter>
      <Name>@ResourceSet</Name>
      <Type>String</Type>
      <Size>510</Size>
      <Direction>In</Direction>
      <TypeName>nvarchar</TypeName>
      <IsUserDefinedType>false</IsUserDefinedType>
      <IsTableType>false</IsTableType>
    </Parameter>
  </Parameters>
  <Columns>
    <Column>
      <Name>ResourceID</Name>
      <Type>Guid</Type>
    </Column>
    <Column>
      <Name>CultureCode</Name>
      <Type>String</Type>
    </Column>
    <Column>
      <Name>ResourceSet</Name>
      <Type>String</Type>
    </Column>
    <Column>
      <Name>ResourceKey</Name>
      <Type>String</Type>
    </Column>
    <Column>
      <Name>ResourceValue</Name>
      <Type>String</Type>
    </Column>
    <Column>
      <Name>CreatedOn</Name>
      <Type>DateTime</Type>
    </Column>
    <Column>
      <Name>CreatedBy</Name>
      <Type>String</Type>
    </Column>
    <Column>
      <Name>ModifiedOn</Name>
      <Type>DateTime</Type>
    </Column>
    <Column>
      <Name>ModifiedBy</Name>
      <Type>String</Type>
    </Column>
  </Columns>
</DataCommand>


text:
package org.openforis.collect.io.metadata.samplingdesign;

import java.util.Arrays;

import org.apache.commons.lang3.ArrayUtils;

/**
 *
 * @author S. Ricci
 *
 */
public enum SamplingDesignFileColumn {
	LEVEL_1("level1_code", 1),
	LEVEL_2("level2_code", 2),
	LEVEL_3("level3_code", 3),
	X("x"),
	Y("y"),
	SRS_ID("srs_id");

	public static final SamplingDesignFileColumn[] LOCATION_COLUMNS = {X, Y};
	public static final SamplingDesignFileColumn[] REQUIRED_COLUMNS = {LEVEL_1, X, Y, SRS_ID};
	public static final SamplingDesignFileColumn[] LEVEL_COLUMNS = {LEVEL_1, LEVEL_2, LEVEL_3};
	public static final SamplingDesignFileColumn[] ALL_COLUMNS = ArrayUtils.addAll(LEVEL_COLUMNS, X, Y, SRS_ID);

	public static final String[] REQUIRED_COLUMN_NAMES;
	public static final String[] LEVEL_COLUMN_NAMES;
	public static final String[] ALL_COLUMN_NAMES;

	static {
		REQUIRED_COLUMN_NAMES = getColumnNames(REQUIRED_COLUMNS);
		LEVEL_COLUMN_NAMES = getColumnNames(LEVEL_COLUMNS);
		ALL_COLUMN_NAMES = getColumnNames(ALL_COLUMNS);
	}

	public static SamplingDesignFileColumn fromColumnName(String columnName) {
		for (SamplingDesignFileColumn column : values()) {
			if (column.getColumnName().equals(columnName)) {
				return column;
			}
		}
		return null;
	}

	private static String[] getColumnNames(SamplingDesignFileColumn[] columns) {
		String [] result = new String[columns.length];
		for (int i = 0 ; i < columns.length; i ++) {
			SamplingDesignFileColumn column = columns[i];
			result[i] = column.getColumnName();
		}
		return result;
	}

	private String columnName;
	private int level;

	private SamplingDesignFileColumn(String columnName, int level) {
		this.columnName = columnName;
		this.level = level;
	}

	private SamplingDesignFileColumn(String columnName) {
		this(columnName, -1);
	}

	public String getColumnName() {
		return columnName;
	}

	public int getLevel() {
		return level;
	}

	public boolean isLevelColumn() {
		return Arrays.asList(LEVEL_COLUMNS).contains(this);
	}

}