text:
import {
  IInitInteractive,
  ISupportedFeaturesRequest,
  INavigationOptions,
  IAuthInfo,
  IGetFirebaseJwtResponse,
  ISupportedFeatures,
  IGetFirebaseJwtRequest,
  IGetAuthInfoRequest,
  IShowModal,
  ICloseModal,
  IGetInteractiveListOptions,
  IGetInteractiveListResponse,
  ISetLinkedInteractives,
  IGetLibraryInteractiveListRequest,
  IGetInteractiveSnapshotRequest,
  IHintRequest,
  IJwtResponse,
  IGetInteractiveListRequest,
  ICustomMessageHandler,
  ICustomMessagesHandledMap,
  IGetInteractiveSnapshotOptions,
  IGetInteractiveSnapshotResponse,
  IAddLinkedInteractiveStateListenerOptions,
  ILinkedInteractiveStateResponse,
  IAddLinkedInteractiveStateListenerRequest,
  IRemoveLinkedInteractiveStateListenerRequest,
  IDecoratedContentEvent,
  ITextDecorationHandler,
  IAttachmentUrlRequest,
  IAttachmentUrlResponse,
  IWriteAttachmentRequest,
  WriteAttachmentParams,
  ReadAttachmentParams,
  GetAttachmentUrlParams,
  IGetReportItemAnswerHandler,
  IReportItemAnswer,
  OnUnloadFunction,
  IReportItemHandlerMetadata,
  ITextDecorationInfo
} from "./types";
import { getClient } from "./client";
import { v4 as uuidv4 } from "uuid";

const THROW_NOT_IMPLEMENTED_YET = (method: string) => {
  throw new Error(`${method} is not yet implemented in the client!`);
};

export const getInitInteractiveMessage =
  <InteractiveState = {}, AuthoredState = {}, GlobalInteractiveState = {}>():
  Promise<IInitInteractive<InteractiveState, AuthoredState, GlobalInteractiveState> | null> => {
  const client = getClient();
  return new Promise<IInitInteractive<InteractiveState, AuthoredState, GlobalInteractiveState> | null>(resolve => {
    if (client.managedState.initMessage) {
      resolve(client.managedState.initMessage);
    } else {
      client.managedState.once("initInteractive", () => resolve(client.managedState.initMessage));
    }
  });
};

export const getMode = () => {
  return getInitInteractiveMessage().then(initInteractiveMessage => initInteractiveMessage?.mode);
};

export const getInteractiveState = <InteractiveState>(): InteractiveState | null => {
  return getClient().managedState.interactiveState;
};

let setInteractiveStateTimeoutId: number;
let delayedInteractiveStateUpdate: (() => void) | null = null;
export const setInteractiveStateTimeout = 2000; // ms
/**
 * Note that state will become frozen and should never be mutated.
 * Each time you update state, make sure that a new object is passed.
 *
 * Good:
 * ```
 * setInteractiveState(Object.assign({}, previousState, {someProperty: "a new value"}));
 * // or
 * setInteractiveState({...previousState, someProperty: "a new value"});
 * ```
 *
 * Bad:
 * ```
 * previousState.someProperty = "a new value";
 * setInteractiveState(previousState);
 * ```
 */
export const setInteractiveState = <InteractiveState>(newInteractiveState: InteractiveState | null) => {
  const client = getClient();
  client.managedState.interactiveState = newInteractiveState;
  window.clearTimeout(setInteractiveStateTimeoutId);
  delayedInteractiveStateUpdate = () => {
    client.post("interactiveState", newInteractiveState);
    client.managedState.interactiveStateDirty = false;
    delayedInteractiveStateUpdate = null;
  };
  setInteractiveStateTimeoutId = window.setTimeout(() => {
    // Note that delayedInteractiveStateUpdate might be equal to null if it was executed before using .flush()
    delayedInteractiveStateUpdate?.();
  }, setInteractiveStateTimeout);
};

/**
 * Useful in rare cases when it's not desirable to wait for the delayed state updates (at this point it only applies
 * to interactive state updates). Internally used by the showModal and closeModal functions, as opening modal
 * usually means reloading interactive. It's necessary to make sure that the state is up to date before it happens.
 */
export const flushStateUpdates = () => {
  // Note that if delayedInteractiveStateUpdate was set, it should set itself to null and setTimeout will ignore it.
  delayedInteractiveStateUpdate?.();
  window.clearTimeout(setInteractiveStateTimeoutId);
};

export const getAuthoredState = <AuthoredState>(): AuthoredState | null => {
  return getClient().managedState.authoredState;
};

/**
 * Note that state will become frozen and should never be mutated.
 * Each time you update state, make sure that a new object is passed.
 *
 * Good:
 * ```
 * setAuthoredState(Object.assign({}, previousState, {someProperty: "a new value"}));
 * // or
 * setAuthoredState({...previousState, someProperty: "a new value"});
 * ```
 *
 * Bad:
 * ```
 * previousState.someProperty = "a new value";
 * setAuthoredState(previousState);
 * ```
 */
export const setAuthoredState = <AuthoredState>(newAuthoredState: AuthoredState | null) => {
  const client = getClient();
  client.managedState.authoredState = newAuthoredState;
  client.post("authoredState", newAuthoredState);
};

export const getGlobalInteractiveState = <GlobalInteractiveState>(): GlobalInteractiveState | null => {
  return getClient().managedState.globalInteractiveState;
};

/**
 * Note that state will become frozen and should never be mutated.
 * Each time you update state, make sure that a new object is passed.
 *
 * Good:
 * ```
 * setGlobalInteractiveState(Object.assign({}, previousState, {someProperty: "a new value"}));
 * // or
 * setGlobalInteractiveState({...previousState, someProperty: "a new value"});
 * ```
 *
 * Bad:
 * ```
 * previousState.someProperty = "a new value";
 * setGlobalInteractiveState(previousState);
 * ```
 */
export const setGlobalInteractiveState = <GlobalInteractiveState>(newGlobalState: GlobalInteractiveState | null) => {
  const client = getClient();
  client.managedState.globalInteractiveState = newGlobalState;
  client.post("interactiveStateGlobal", newGlobalState);
};

export const addCustomMessageListener = (callback: ICustomMessageHandler, handles?: ICustomMessagesHandledMap) => {
  const client = getClient();
  if (handles) {
    client.customMessagesHandled = handles;
  }
  client.addListener("customMessage", callback);
};

export const removeCustomMessageListener = () => {
  return getClient().removeListener("customMessage");
};

export const addDecorateContentListener = (callback: ITextDecorationHandler) => {
  getClient().addListener("decorateContent", (msg: ITextDecorationInfo) => {
    callback({
      words: msg.words,
      replace: msg.replace,
      wordClass: msg.wordClass,
      eventListeners: msg.listenerTypes.map((listener) => {
        return {
          type: listener.type,
          listener: (evt: Event) => {
            const wordElement = evt.srcElement as HTMLElement;
            if (!wordElement) {
              return;
            }
            const clickedWord = (wordElement.textContent || "").toLowerCase();
            postDecoratedContentEvent({type: listener.type,
                                       text: clickedWord,
                                       bounds: wordElement.getBoundingClientRect()});
          }
        };
      })
    });
  });
};

export const removeDecorateContentListener = () => {
  getClient().removeListener("decorateContent");
};

// tslint:disable-next-line:max-line-length
export const addGetReportItemAnswerListener = <InteractiveState, AuthoredState>(callback: IGetReportItemAnswerHandler<InteractiveState, AuthoredState>) => {
  getClient().addListener("getReportItemAnswer", callback);
};

export const removeGetReportItemAnswerListener = () => {
  getClient().removeListener("getReportItemAnswer");
};

export const notifyReportItemClientReady = (metadata?: IReportItemHandlerMetadata) => {
  getClient().post("reportItemClientReady", metadata);
};

export const setSupportedFeatures = (features: ISupportedFeatures) => {
  const request: ISupportedFeaturesRequest = {
    apiVersion: 1,
    features
  };
  getClient().setSupportedFeatures(request);
};

export const setHeight = (height: number | string) => {
  getClient().post("height", height);
};

export const postDecoratedContentEvent = (msg: IDecoratedContentEvent) => {
  getClient().post("decoratedContentEvent", msg);
};

/**
 * Providing empty string or null disables hint.
 */
export const setHint = (hint: string | null) => {
  const request: IHintRequest = { text: hint };
  getClient().post("hint", request);
};

export const setNavigation = (options: INavigationOptions) => {
  getClient().post("navigation", options);
};

export const getAuthInfo = (): Promise<IAuthInfo> => {
  return new Promise<IAuthInfo>((resolve, reject) => {
    const listener = (authInfo: IAuthInfo) => {
      resolve(authInfo);
    };
    const client = getClient();
    const requestId = client.getNextRequestId();
    const request: IGetAuthInfoRequest = {
      requestId
    };
    client.addListener("authInfo", listener, requestId);
    client.post("getAuthInfo", request);
  });
};

export const getFirebaseJwt = (firebaseApp: string): Promise<IJwtResponse> => {
  return new Promise<IJwtResponse>((resolve, reject) => {
    getInitInteractiveMessage().then(initMsg => {
      if (initMsg?.hostFeatures?.getFirebaseJwt?.version === "1.0.0") {
        const listener = (response: IGetFirebaseJwtResponse) => {
          if (response.response_type === "ERROR") {
            reject(response.message || "Error getting Firebase JWT");
          } else if (response.token) {
            try {
              const claimsJson = atob(response.token.split(".")[1]);
              resolve({token: response.token, claims: JSON.parse(claimsJson)});
            } catch (error) {
              reject("Unable to parse JWT Token");
            }
          } else {
            reject("Empty token");
          }
        };
        const client = getClient();
        const requestId = client.getNextRequestId();
        const request: IGetFirebaseJwtRequest = {
          requestId,
          firebase_app: firebaseApp
        };
        client.addListener("firebaseJWT", listener, requestId);
        client.post("getFirebaseJWT", request);
      } else {
        reject("getFirebaseJwt not supported by the host environment");
      }
    });
  });
};

export const log = (action: string, data?: object) => {
  getClient().post("log", {action, data});
};

// tslint:disable-next-line:max-line-length
export const addInteractiveStateListener = <InteractiveState>(listener: (interactiveState: InteractiveState) => void) => {
  getClient().managedState.on("interactiveStateUpdated", listener);
};

// tslint:disable-next-line:max-line-length
export const removeInteractiveStateListener = <InteractiveState>(listener: (interactiveState: InteractiveState) => void) => {
  getClient().managedState.off("interactiveStateUpdated", listener);
};

export const addAuthoredStateListener = <AuthoredState>(listener: (authoredState: AuthoredState) => void) => {
  getClient().managedState.on("authoredStateUpdated", listener);
};

export const removeAuthoredStateListener = <AuthoredState>(listener: (authoredState: AuthoredState) => void) => {
  getClient().managedState.off("authoredStateUpdated", listener);
};

// tslint:disable-next-line:max-line-length
export const addGlobalInteractiveStateListener = <GlobalInteractiveState>(listener: (globalInteractiveState: GlobalInteractiveState) => void) => {
  getClient().managedState.on("globalInteractiveStateUpdated", listener);
};

// tslint:disable-next-line:max-line-length
export const removeGlobalInteractiveStateListener = <GlobalInteractiveState>(listener: (globalInteractiveState: GlobalInteractiveState) => void) => {
  getClient().managedState.off("globalInteractiveStateUpdated", listener);
};

// Mapping between external listener and internal listener, so it's possible to remove linkedInteractiveState listeners.
const _linkedInteractiveStateListeners = new Map();
/**
 * The listener should be called immediately after it is added with any state of the linked
 * interactive that the host currently knows about. This first call might not happen
 * synchronously it could be slightly delayed. And then the listener should be called again
 * whenever the state of the linked interactive changes.
 */
export const addLinkedInteractiveStateListener = <LinkedInteractiveState>(
  listener: (linkedIntState: LinkedInteractiveState | undefined) => void,
  options: IAddLinkedInteractiveStateListenerOptions
) => {
  const client = getClient();
  const listenerId = uuidv4();
  const internalListener = (response: ILinkedInteractiveStateResponse<LinkedInteractiveState>) => {
    if (response.listenerId === listenerId) {
      listener(response.interactiveState);
    }
  };
  client.addListener("linkedInteractiveState", internalListener);
  // Initialize observing in the host environment.
  const request: IAddLinkedInteractiveStateListenerRequest = {
    ...options,
    listenerId
  };
  client.post("addLinkedInteractiveStateListener", request);
  // Save wrappedInternalListener so it's possible to remove it later.
  _linkedInteractiveStateListeners.set(listener, {
    listenerId: request.listenerId,
    internalListener
  });
};

export const removeLinkedInteractiveStateListener = <InteractiveState>(
  listener: (intState: InteractiveState | null) => void
) => {
  const client = getClient();
  if (_linkedInteractiveStateListeners.has(listener)) {
    const { internalListener, listenerId } = _linkedInteractiveStateListeners.get(listener);
    // Remove local message handler. Theoretically it's not necessary if host implementation is correct
    // (no more messages with this listenerId should be sent), but just to keep things cleaner.
    client.removeListener("linkedInteractiveState", undefined, internalListener);
    // Stop observing in the host environment.
    const request: IRemoveLinkedInteractiveStateListenerRequest = { listenerId };
    client.post("removeLinkedInteractiveStateListener", request);
    _linkedInteractiveStateListeners.delete(listener);
  }
};

/**
 * "lightbox" type is used for displaying images or generic iframes (e.g. help page, but NOT dynamic interactives).
 * "dialog" is used for showing dynamic interactives. It'll be initialized correctly by the host environment and
 * all the runtime features will be supported.
 */
export const showModal = (options: IShowModal) => {
  // Opening modal usually means reloading interactive. It's necessary to make sure that the state is up to date
  // before it happens.
  flushStateUpdates();
  getClient().post("showModal", options);
};

export const closeModal = (options: ICloseModal) => {
  // Opening modal usually means reloading interactive. It's necessary to make sure that the state is up to date
  // before it happens.
  flushStateUpdates();
  getClient().post("closeModal", options);
};

export const getInteractiveList = (options: IGetInteractiveListOptions) => {
  return new Promise<IGetInteractiveListResponse>((resolve, reject) => {
    return getMode()
      .then(mode => {
        if (mode === "authoring") {
          const client = getClient();
          const requestId = client.getNextRequestId();
          const request: IGetInteractiveListRequest = {
            requestId,
            ...options
          };
          client.addListener("interactiveList", resolve, requestId);
          client.post("getInteractiveList", request);
        } else {
          reject("getInteractiveList is only available in authoring mode");
        }
      });
  });
};

export const setLinkedInteractives = (options: ISetLinkedInteractives) => {
  getClient().post("setLinkedInteractives", options);
};

export const getInteractiveSnapshot = (options: IGetInteractiveSnapshotOptions) => {
  return new Promise<IGetInteractiveSnapshotResponse>((resolve, reject) => {
    const listener = (snapshotResponse: IGetInteractiveSnapshotResponse) => {
      resolve(snapshotResponse);
    };
    const client = getClient();
    const requestId = client.getNextRequestId();
    const request: IGetInteractiveSnapshotRequest = {
      requestId,
      ...options
    };
    client.addListener("interactiveSnapshot", listener, requestId);
    client.post("getInteractiveSnapshot", request);
  });
};

/**
 * @todo Implement this function.
 */
export const getLibraryInteractiveList = (options: IGetLibraryInteractiveListRequest) => {
  THROW_NOT_IMPLEMENTED_YET("getLibraryInteractiveList");
};

export const writeAttachment = (params: WriteAttachmentParams): Promise<Response> => {
  return new Promise<Response>((resolve, reject) => {
    const client = getClient();
    const { content, options = {}, ...others } = params;
    const { contentType = "text/plain" } = params;
    const request: IAttachmentUrlRequest = { ...others, operation: "write", requestId: client.getNextRequestId() };
    client.addListener("attachmentUrl", async (response: IAttachmentUrlResponse) => {
      if (response.url) {
        const headers: Record<string, string> = { ...(options.headers as Record<string, string>) };
        headers["Content-Type"] = contentType;
        options.headers = headers;
        try {
          // resolves with the fetch Response object, so clients can check status
          resolve(await fetch(response.url, { ...options, method: "PUT", body: content }));
        }
        catch (e) {
          reject(e);
        }
      }
      else {
        reject(new Error(response.error || "error writing attachment"));
      }
    }, request.requestId);
    client.post("getAttachmentUrl", request);
  });
};

export const readAttachment = (params: ReadAttachmentParams): Promise<Response> => {
  return new Promise<Response>((resolve, reject) => {
    // set up response listener
    const client = getClient();
    const request: IAttachmentUrlRequest = { ...params, operation: "read", requestId: client.getNextRequestId() };
    client.addListener("attachmentUrl", async (response: IAttachmentUrlResponse) => {
      if (response.url) {
        try {
          // resolves with the fetch Response object, so clients can check status
          // or convert to JSON or text or something else.
          resolve(await fetch(response.url));
        }
        catch (e) {
          reject(e);
        }
      }
      else {
        reject(new Error(response.error || "error reading attachment"));
      }
    }, request.requestId);
    client.post("getAttachmentUrl", request);
  });
};

export const getAttachmentUrl = (params: GetAttachmentUrlParams) => {
  return new Promise<string>((resolve, reject) => {
    // set up response listener
    const client = getClient();
    const requestId = client.getNextRequestId();
    const request: IAttachmentUrlRequest = { ...params, operation: "read", requestId };
    client.addListener("attachmentUrl", async (response: IAttachmentUrlResponse) => {
      if (response.url) {
        resolve(response.url);
      }
      else {
        reject(new Error(response.error || "error getting attachment url"));
      }
    }, request.requestId);
    client.post("getAttachmentUrl", request);
  });
};

export const sendReportItemAnswer = (request: Omit<IReportItemAnswer, "requestId">) => {
  getClient().post("reportItemAnswer", request);
};

export const setOnUnload = (onUnload?: OnUnloadFunction) => {
  getClient().setOnUnload(onUnload);
};

redpajama_set_name: RedPajamaGithub


text:
package mockstore

import (
	"errors"
	"io"
	"net/http"
	"time"

	"github.com/fxnn/gone/store"
)

// MockStore is only for testing and provides configurable answers.
// By default, it returns only zero values.
type MockStore struct {
	err          error
	readAccess   bool
	writeAccess  bool
	deleteAccess bool
	mimeType     string
	exists       bool
}

func New() *MockStore {
	return &MockStore{exists: true}
}

func (s *MockStore) GivenNoErr() {
	s.GivenErr(nil)
}

func (s *MockStore) GivenSomeErr() {
	s.GivenErr(errors.New("mock error"))
}

func (s *MockStore) GivenErr(err error) {
	s.err = err
}

func (s *MockStore) GivenNotExists() {
	s.exists = false
}

func (s *MockStore) GivenReadAccess() {
	s.readAccess = true
}

func (s *MockStore) HasReadAccessForRequest(request *http.Request) bool {
	return s.readAccess
}

func (s *MockStore) GivenWriteAccess() {
	s.writeAccess = true
}

func (s *MockStore) HasWriteAccessForRequest(request *http.Request) bool {
	return s.writeAccess
}

func (s *MockStore) GivenDeleteAccess() {
	s.deleteAccess = true
}

func (s *MockStore) HasDeleteAccessForRequest(request *http.Request) bool {
	return s.deleteAccess
}

func (s *MockStore) OpenReader(request *http.Request) io.ReadCloser {
	if !s.exists {
		s.err = store.NewPathNotFoundError("mocked PathNotFoundError")
	}
	return nil
}

func (s *MockStore) OpenWriter(request *http.Request) io.WriteCloser {
	return nil
}

func (s *MockStore) ReadString(request *http.Request) string {
	if !s.exists {
		s.err = store.NewPathNotFoundError("mocked PathNotFoundError")
	}
	return ""
}

func (s *MockStore) WriteString(request *http.Request, content string) {
}

func (s *MockStore) Delete(request *http.Request) {
	if !s.exists {
		s.err = store.NewPathNotFoundError("mocked PathNotFoundError")
	}
}

func (s *MockStore) FileSizeForRequest(request *http.Request) int64 {
	if !s.exists {
		s.err = store.NewPathNotFoundError("mocked PathNotFoundError")
	}
	return 0
}

func (s *MockStore) ModTimeForRequest(request *http.Request) time.Time {
	if !s.exists {
		s.err = store.NewPathNotFoundError("mocked PathNotFoundError")
	}
	return time.Now()
}

func (s *MockStore) GivenMimeType(mimeType string) {
	s.mimeType = mimeType
}

func (s *MockStore) MimeTypeForRequest(request *http.Request) string {
	if !s.exists {
		s.err = store.NewPathNotFoundError("mocked PathNotFoundError")
	}
	return s.mimeType
}

func (s *MockStore) Err() error {
	var result = s.err
	s.err = nil
	return result
}


text:
=begin
    Copyright 2010-2014 Tasos Laskos <tasos.laskos@gmail.com>

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
=end

require 'set'

module Arachni
module Support::LookUp

#
# Lightweight look-up Set implementation.
#
# It uses stores hashes of items instead of the items themselves.
#
# This leads to decreased memory consumption and faster comparisons during look-ups.
#
# @author Tasos "Zapotek" Laskos <tasos.laskos@gmail.com>
#
class HashSet < Base

    # @param    (see Base#initialize)
    def initialize(*)
        super
        @collection = Set.new
    end

end

end
end


text:
package com.withinet.opaas;

import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class PropertiesInstaller {

	public static void install() {
		String input = null;
		if (new File ("application.properties").exists()) {
			input = PropertiesInstaller.ask ("Continue previous application context? (Y or N)", Arrays.asList("Y", "N", "y", "n")).toUpperCase();
			if (input.toUpperCase().equals("N")) {
				run ();
			}
		} else {
			 run ();
		}
		verifyConfig ();
	}

	private static void verifyConfig () {
		String s = PropertiesInstaller.get("domain");
		if (s == null) throw new RuntimeException ("Domain name not configured check application.properties file");
		try {
			s = PropertiesInstaller.get("min.port");
			Integer.parseInt(s);
			s = PropertiesInstaller.get("max.port");
			Integer.parseInt(s);
		} catch (NumberFormatException e) {
			throw new RuntimeException ("Port number not integer check application.properties file");
		}
		s = PropertiesInstaller.get("security.bundle");
		if (s == null) throw new RuntimeException ("Security bundle location not configured check application.properties file");
		if (!new File (s).exists()) throw new RuntimeException ("Security bundle not in configured location " + s );

	}

	private static void run () {
		String input = null;
		Properties p = new Properties();
		if (!new File ("security-1.0.0.jar").exists()){
			try {
				extractSecurityBundle (p);
			} catch (IOException e) {
				throw new RuntimeException (e.getMessage());
			}
		}
		try {
			p.setProperty("security.bundle", new File ("security-1.0.0.jar").getCanonicalPath());
		} catch (IOException e1) {
			throw new RuntimeException (e1.getMessage());
		}
		input = ask ("What is your name?");
		System.out.println ("******************************************************");
		p.setProperty("name", input);
		p.setProperty("email", ask ("What is your email address?"));
		System.out.println ("******************************************************");
		p.setProperty("password", ask ("What is your password?"));
		System.out.println ("******************************************************");
		p.setProperty("domain", ask("What is the domain name or ip of this server?"));
		System.out.println ("******************************************************");
		String minport = ask("Minimum port for deployed application containers? (1 - 65535)");
		System.out.println ("******************************************************");
		p.setProperty("min.port", minport);
		p.setProperty("max.port", ask("Maximum port for deployed application containers? (" + minport + " - 65535)"));
		System.out.println ("******************************************************");
		p.setProperty("spring.jpa.hibernate.ddl-auto", "update");
		p.setProperty("spring.jpa.show-sql", "false");
		p.setProperty("spring.datasource.driverClassName",
				"org.hsqldb.jdbcDriver");
		p.setProperty("server.port", "80");
		p.setProperty("server.sessionTimeout", "100000");
		p.setProperty("spring.datasource.username", "sa");
		p.setProperty("spring.datasource.password", "");
		p.setProperty("spring.datasource.url", "jdbc:hsqldb:mem:aname");
		OutputStream o = null;
		try {
			o = new FileOutputStream("application.properties");
			input = ask(
					"Run in default mode (Y or N)? \n Default is non persistent and port 80 must be open", Arrays.asList("Y", "N", "y", "n"))
					.toUpperCase();
			if (input.toUpperCase().equals("Y")) {
				email (p);
				p.store(o, "Default");
			} else if (input.toUpperCase().equals("N")) {
				input = ask("What's your web server port for this application?");
				System.out.println ("******************************************************");
				p.setProperty("server.port", input);
				input = ask("Do you have a running database server? Y or N", Arrays.asList("Y", "N", "y", "n"));
				System.out.println ("******************************************************");
				if (input.toUpperCase().equals("Y")) {
					input = ask("What's the jdbc data source url e.g jdbc:hsqldb:hsql://localhost:9001?");
					System.out.println ("******************************************************");
					p.setProperty("spring.datasource.url", input);
					input = ask("What's the database username?");
					System.out.println ("******************************************************");
					p.setProperty("spring.datasource.username", input);
					input = ask("What's the database password?");
					System.out.println ("******************************************************");
					p.setProperty("spring.datasource.password", input);
				} else if (input.toUpperCase().equals("N")) {
					p.setProperty("spring.datasource.url",
							"jdbc:hsqldb:mem:aname");
				}
				email (p);
				p.store(o, "Non default settings");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if (o != null)
					o.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private static void extractSecurityBundle (Properties p) throws IOException {
		String location = new File(PropertiesInstaller.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getAbsolutePath().toString();
		location = location.split("file:")[1].replace("!", "");
		UnzipJar.unzipJar(location, "security-1.0.0.jar");
	}

	private static void email (Properties p) {
		String input = null;
		input = ask ("Would you like to setup email \n-> Needed for team functionality? (Y or N)" ,Arrays.asList("Y", "N", "y", "n"));
		if (input.toUpperCase().equals("Y")) {
			input = ask ("What's the email account to dispatch emails:");
			p.setProperty("mailer.email", input);
			input = ask ("What's the email password?");
			p.setProperty("mailer.password", input);
			input = ask ("What's the host smtp address?");
			p.setProperty("mailer.host", input);
			input = ask ("SMTP Port Number?");
			p.setProperty("mailer.port", input);
			input = ask ("Startttls enabled (true or false)?",Arrays.asList("true", "false"));
			p.setProperty ("mailer.ttls", input);
			p.setProperty("mailer.auth", "true");
		}
	}

	private static String ask(String question) {
		System.out.println(question);
		Console console = System.console();
		String response = console.readLine("Enter input:");
		if (response != null && response.length() > 0)
			return response;
		else {
			System.out.println("\nError: Your response is required\n");
			ask (question);
		}

		return response;
	}

	private static String ask(String question, List<String> expected) {
		System.out.println(question);
		Console console = System.console();
		String response = console.readLine("Enter input:");
		if (expected.contains(response))
			return response;
		else {
			System.out.println("\nError: That input is not recognized\n");
			ask (question, expected);
		}

		return response;
	}

	public static String get(String property) {
		Properties prop = new Properties();
		InputStream input = null;
		try {
			input = new FileInputStream("application.properties");
			prop.load(input);
			return (String) prop.get(property);
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
}


text:
/**
  This route is used for retrieving a topic based on params

  @class TopicFromParamsRoute
  @extends Discourse.Route
  @namespace Discourse
  @module Discourse
**/
Discourse.TopicFromParamsRoute = Discourse.Route.extend({

  setupController: function(controller, params) {
    params = params || {};
    params.track_visit = true;

    var topic = this.modelFor('topic'),
        postStream = topic.get('postStream'),
        queryParams = Discourse.URL.get('queryParams');

    if (queryParams) {
      // Set summary on the postStream if present
      postStream.set('summary', Em.get(queryParams, 'filter') === 'summary');

      // Set any username filters on the postStream
      var userFilters = Em.get(queryParams, 'username_filters') || Em.get(queryParams, 'username_filters[]');
      if (userFilters) {
        if (typeof userFilters === "string") { userFilters = [userFilters]; }
        userFilters.forEach(function (username) {
          postStream.get('userFilters').add(username);
        });
      }
    }

    var topicController = this.controllerFor('topic'),
        composerController = this.controllerFor('composer');

    postStream.refresh(params).then(function () {
      // The post we requested might not exist. Let's find the closest post
      var closest = postStream.closestPostNumberFor(params.nearPost) || 1;

      topicController.setProperties({
        currentPost: closest,
        progressPosition: closest,
        enteredAt: new Date().getTime().toString(),
        highlightOnInsert: closest
      });

      Discourse.TopicView.jumpToPost(closest);

      if (topic.present('draft')) {
        composerController.open({
          draft: Discourse.Draft.getLocal(topic.get('draft_key'), topic.get('draft')),
          draftKey: topic.get('draft_key'),
          draftSequence: topic.get('draft_sequence'),
          topic: topic,
          ignoreIfChanged: true
        });
      }
    });
  }

});

Discourse.TopicFromParamsNearRoute = Discourse.TopicFromParamsRoute;


text:
set -eux
# run test module with multi-gpu requirements. We currently do not have a way to filter tests.
# this issue is also tracked in https://github.com/google/jax/issues/7323
python3 -m pytest --reruns 3 -x tests/pmap_test.py
python3 -m pytest --reruns 3 -x tests/multi_device_test.py


text:
/* libc/sys/linux/include/alloca.h - Allocate memory on stack */

/* Written 2000 by Werner Almesberger */

#ifndef _NEWLIB_ALLOCA_H
#define _NEWLIB_ALLOCA_H

/* Simple, since we know that we use gcc */

#define alloca(size) __builtin_alloca(size)

#endif


text:
using ConsoleApplication.Printer.ContentBuilders;

namespace ConsoleApplication.Printer
{
    public interface IResultPrinter
    {
        IResultPrinter AddPrinter(IPrinter printer, IContentBuilder contentBuilder);

        /// <summary>
        /// Prints result with supplied printers
        /// </summary>
        void Print(string title);
    }
}


text:
import os
import os.path
import unittest
import shutil
import tempfile

import flask

from werkzeug.exceptions import NotFound

import browsepy
import browsepy.compat as compat
import browsepy.file as browsepy_file
import browsepy.manager as browsepy_manager
import browsepy.plugin.player as player
import browsepy.plugin.player.playable as player_playable
import browsepy.tests.utils as test_utils

class ManagerMock(object):
    def __init__(self):
        self.blueprints = []
        self.mimetype_functions = []
        self.widgets = []
        self.arguments = []
        self.argument_values = {}

    def register_blueprint(self, blueprint):
        self.blueprints.append(blueprint)

    def register_mimetype_function(self, fnc):
        self.mimetype_functions.append(fnc)

    def register_widget(self, **kwargs):
        self.widgets.append(kwargs)

    def register_argument(self, *args, **kwargs):
        self.arguments.append((args, kwargs))

    def get_argument(self, name, default=None):
        return self.argument_values.get(name, default)

class TestPlayerBase(unittest.TestCase):
    module = player

    def assertPathEqual(self, a, b):
        return self.assertEqual(
            os.path.normcase(a),
            os.path.normcase(b)
            )

    def assertPathListEqual(self, a, b):
        return self.assertListEqual(
            list(map(os.path.normcase, a)),
            list(map(os.path.normcase, b))
        )

    def setUp(self):
        self.base = 'c:\\base' if os.name == 'nt' else '/base'
        self.app = flask.Flask(self.__class__.__name__)
        self.app.config['directory_base'] = self.base
        self.manager = ManagerMock()

class TestPlayer(TestPlayerBase):
    def test_register_plugin(self):
        self.module.register_plugin(self.manager)
        self.assertListEqual(self.manager.arguments, [])

        self.assertIn(self.module.player, self.manager.blueprints)
        self.assertIn(
            self.module.playable.detect_playable_mimetype,
            self.manager.mimetype_functions
            )

        widgets = [
            action['filename']
            for action in self.manager.widgets
            if action['type'] == 'stylesheet'
            ]
        self.assertIn('css/browse.css', widgets)

        actions = [action['endpoint'] for action in self.manager.widgets]
        self.assertIn('player.static', actions)
        self.assertIn('player.audio', actions)
        self.assertIn('player.playlist', actions)
        self.assertNotIn('player.directory', actions)

    def test_register_plugin_with_arguments(self):
        self.manager.argument_values['player_directory_play'] = True
        self.module.register_plugin(self.manager)

        actions = [action['endpoint'] for action in self.manager.widgets]
        self.assertIn('player.directory', actions)

    def test_register_arguments(self):
        self.module.register_arguments(self.manager)
        self.assertEqual(len(self.manager.arguments), 1)

        arguments = [arg[0][0] for arg in self.manager.arguments]
        self.assertIn('--player-directory-play', arguments)

class TestIntegrationBase(TestPlayerBase):
    player_module = player
    browsepy_module = browsepy
    manager_module = browsepy_manager

class TestIntegration(TestIntegrationBase):
    non_directory_args = ['--plugin', 'player']
    directory_args = ['--plugin', 'player', '--player-directory-play']

    def test_register_plugin(self):
        self.app.config.update(self.browsepy_module.app.config)
        self.app.config['plugin_namespaces'] = ('browsepy.plugin',)
        manager = self.manager_module.PluginManager(self.app)
        manager.load_plugin('player')
        self.assertIn(self.player_module.player, self.app.blueprints.values())

    def test_register_arguments(self):
        self.app.config.update(self.browsepy_module.app.config)
        self.app.config['plugin_namespaces'] = ('browsepy.plugin',)

        manager = self.manager_module.ArgumentPluginManager(self.app)
        manager.load_arguments(self.non_directory_args)
        self.assertFalse(manager.get_argument('player_directory_play'))
        manager.load_arguments(self.directory_args)
        self.assertTrue(manager.get_argument('player_directory_play'))

    def test_reload(self):
        self.app.config.update(
            plugin_modules=['player'],
            plugin_namespaces=['browsepy.plugin']
        )
        manager = self.manager_module.PluginManager(self.app)
        manager.load_arguments(self.non_directory_args)
        manager.reload()

        manager = self.manager_module.PluginManager(self.app)
        manager.load_arguments(self.directory_args)
        manager.reload()

class TestPlayable(TestIntegrationBase):
    module = player_playable

    def setUp(self):
        super(TestPlayable, self).setUp()
        self.manager = self.manager_module.MimetypePluginManager(
            self.app
            )
        self.manager.register_mimetype_function(
            self.player_module.playable.detect_playable_mimetype
            )

    def test_normalize_playable_path(self):
        playable = self.module.PlayListFile(
            path=p(self.base, 'a.m3u'),
            app=self.app
            )
        self.assertEqual(
            playable.normalize_playable_path('http://asdf/asdf.mp3'),
            'http://asdf/asdf.mp3'
            )
        self.assertEqual(
            playable.normalize_playable_path('ftp://asdf/asdf.mp3'),
            'ftp://asdf/asdf.mp3'
            )
        self.assertPathEqual(
            playable.normalize_playable_path('asdf.mp3'),
            self.base + '/asdf.mp3'
            )
        self.assertPathEqual(
            playable.normalize_playable_path(self.base + '/other/../asdf.mp3'),
            self.base + '/asdf.mp3'
            )
        self.assertEqual(
            playable.normalize_playable_path('/other/asdf.mp3'),
            None
            )

    def test_playablefile(self):
        exts = {
         'mp3': 'mp3',
         'wav': 'wav',
         'ogg': 'ogg'
        }
        for ext, media_format in exts.items():
            pf = self.module.PlayableFile(path='asdf.%s' % ext, app=self.app)
            self.assertEqual(pf.media_format, media_format)
            self.assertEqual(pf.title, 'asdf.%s' % ext)

    def test_playabledirectory(self):
        tmpdir = tempfile.mkdtemp()
        try:
            file = p(tmpdir, 'playable.mp3')
            open(file, 'w').close()
            node = browsepy_file.Directory(tmpdir)
            self.assertTrue(self.module.PlayableDirectory.detect(node))

            directory = self.module.PlayableDirectory(tmpdir, app=self.app)

            self.assertEqual(directory.parent.path, directory.path)

            entries = directory.entries()
            self.assertEqual(next(entries).path, file)
            self.assertRaises(StopIteration, next, entries)

            os.remove(file)
            self.assertFalse(self.module.PlayableDirectory.detect(node))

        finally:
            shutil.rmtree(tmpdir)

    def test_playlistfile(self):
        pf = self.module.PlayListFile.from_urlpath(
            path='filename.m3u', app=self.app)
        self.assertTrue(isinstance(pf, self.module.M3UFile))
        pf = self.module.PlayListFile.from_urlpath(
            path='filename.m3u8', app=self.app)
        self.assertTrue(isinstance(pf, self.module.M3UFile))
        pf = self.module.PlayListFile.from_urlpath(
            path='filename.pls', app=self.app)
        self.assertTrue(isinstance(pf, self.module.PLSFile))

    def test_m3ufile(self):
        data = '/base/valid.mp3\n/outside.ogg\n/base/invalid.bin\nrelative.ogg'
        tmpdir = tempfile.mkdtemp()
        try:
            file = p(tmpdir, 'playable.m3u')
            with open(file, 'w') as f:
                f.write(data)
            playlist = self.module.M3UFile(path=file, app=self.app)
            self.assertPathListEqual(
                [a.path for a in playlist.entries()],
                [p(self.base, 'valid.mp3'), p(tmpdir, 'relative.ogg')]
                )
        finally:
            shutil.rmtree(tmpdir)

    def test_plsfile(self):
        data = (
            '[playlist]\n'
            'File1=/base/valid.mp3\n'
            'File2=/outside.ogg\n'
            'File3=/base/invalid.bin\n'
            'File4=relative.ogg'
            )
        tmpdir = tempfile.mkdtemp()
        try:
            file = p(tmpdir, 'playable.pls')
            with open(file, 'w') as f:
                f.write(data)
            playlist = self.module.PLSFile(path=file, app=self.app)
            self.assertPathListEqual(
                [a.path for a in playlist.entries()],
                [p(self.base, 'valid.mp3'), p(tmpdir, 'relative.ogg')]
                )
        finally:
            shutil.rmtree(tmpdir)

    def test_plsfile_with_holes(self):
        data = (
            '[playlist]\n'
            'File1=/base/valid.mp3\n'
            'File3=/base/invalid.bin\n'
            'File4=relative.ogg\n'
            'NumberOfEntries=4'
            )
        tmpdir = tempfile.mkdtemp()
        try:
            file = p(tmpdir, 'playable.pls')
            with open(file, 'w') as f:
                f.write(data)
            playlist = self.module.PLSFile(path=file, app=self.app)
            self.assertPathListEqual(
                [a.path for a in playlist.entries()],
                [p(self.base, 'valid.mp3'), p(tmpdir, 'relative.ogg')]
                )
        finally:
            shutil.rmtree(tmpdir)

class TestBlueprint(TestPlayerBase):
    def setUp(self):
        super(TestBlueprint, self).setUp()
        self.app = browsepy.app  # required for our url_for calls
        self.app.config.update(
            directory_base=tempfile.mkdtemp(),
            SERVER_NAME='test'
        )
        self.app.register_blueprint(self.module.player)

    def tearDown(self):
        shutil.rmtree(self.app.config['directory_base'])
        test_utils.clear_flask_context()

    def url_for(self, endpoint, **kwargs):
        with self.app.app_context():
            return flask.url_for(endpoint, _external=False, **kwargs)

    def get(self, endpoint, **kwargs):
        with self.app.test_client() as client:
            url = self.url_for(endpoint, **kwargs)
            response = client.get(url)
        return response

    def file(self, path, data=''):
        apath = p(self.app.config['directory_base'], path)
        with open(apath, 'w') as f:
            f.write(data)
        return apath

    def directory(self, path):
        apath = p(self.app.config['directory_base'], path)
        os.mkdir(apath)
        return apath

    def test_playable(self):
        name = 'test.mp3'
        result = self.get('player.audio', path=name)
        self.assertEqual(result.status_code, 404)
        self.file(name)
        result = self.get('player.audio', path=name)
        self.assertEqual(result.status_code, 200)

    def test_playlist(self):
        name = 'test.m3u'
        result = self.get('player.playlist', path=name)
        self.assertEqual(result.status_code, 404)
        self.file(name)
        result = self.get('player.playlist', path=name)
        self.assertEqual(result.status_code, 200)

    def test_directory(self):
        name = 'directory'
        result = self.get('player.directory', path=name)
        self.assertEqual(result.status_code, 404)
        self.directory(name)
        result = self.get('player.directory', path=name)
        self.assertEqual(result.status_code, 200)
        self.file('directory/test.mp3')
        result = self.get('player.directory', path=name)
        self.assertEqual(result.status_code, 200)

    def test_endpoints(self):
        with self.app.app_context():
            self.assertIsInstance(
                self.module.audio(path='..'),
                NotFound
            )

            self.assertIsInstance(
                self.module.playlist(path='..'),
                NotFound
            )

            self.assertIsInstance(
                self.module.directory(path='..'),
                NotFound
            )

def p(*args):
    args = [
        arg if isinstance(arg, compat.unicode) else arg.decode('utf-8')
        for arg in args
        ]
    return os.path.join(*args)


text:
<query id="updateMusic" action="update">
	<tables>
		<table name="musicbox_music" />
	</tables>
	<columns>
		<column name="title" var="title" notnull="notnull" />
		<column name="artist" var="artist" notnull="notnull" />
		<column name="album" var="album" default="" />
		<column name="source_filename" var="source_filename" />
		<column name="uploaded_filename" var="uploaded_filename" />
		<column name="file_size" var="file_size" />
		<column name="lyric" var="lyric" />
		<column name="comment" var="comment" />
	</columns>
	<conditions>
		<condition operation="equal" column="music_srl" var="music_srl" notnull="notnull" />
	</conditions>
</query>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Can. J. Bot. 38: 934 (1960)

#### Original name
Rhizoctonia dichotoma H.K. Saksena & Vaartaja, 1960

### Remarks
null


text:
package org.springframework.boot.actuate.endpoint;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanWrapperImpl;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationBeanFactoryMetaData;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.BeanDescription;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationConfig;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.introspect.Annotated;
import com.fasterxml.jackson.databind.introspect.AnnotatedMethod;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
import com.fasterxml.jackson.databind.ser.BeanPropertyWriter;
import com.fasterxml.jackson.databind.ser.BeanSerializerFactory;
import com.fasterxml.jackson.databind.ser.BeanSerializerModifier;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.SerializerFactory;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

/**
 * {@link Endpoint} to expose application properties from {@link ConfigurationProperties}
 * annotated beans.
 *
 *

 * To protect sensitive information from being exposed, certain property values are masked
 * if their names end with a set of configurable values (default "password" and "secret").
 * Configure property names by using endpoints.configprops.keys_to_sanitize
 * in your Spring Boot application configuration.
 *
 * @author Christian Dupuis
 * @author Dave Syer
 */
@ConfigurationProperties(prefix = "endpoints.configprops", ignoreUnknownFields = false)
public class ConfigurationPropertiesReportEndpoint extends
		AbstractEndpoint<Map<String, Object>> implements ApplicationContextAware {

	private static final String CGLIB_FILTER_ID = "cglibFilter";

	private static final Log logger = LogFactory
			.getLog(ConfigurationPropertiesReportEndpoint.class);

	private final Sanitizer sanitizer = new Sanitizer();

	private ApplicationContext context;

	private ConfigurationPropertiesMetaData metadata;

	private String metadataLocations = "classpath:*/META-INF/*spring-configuration-metadata.json";

	public ConfigurationPropertiesReportEndpoint() {
		super("configprops");
	}

	@Override
	public void setApplicationContext(ApplicationContext context) throws BeansException {
		this.context = context;
	}

	public void setKeysToSanitize(String... keysToSanitize) {
		this.sanitizer.setKeysToSanitize(keysToSanitize);
	}

	/**
	 * Location path for JSON metadata about config properties.
	 *
	 * @param metadataLocations the metadataLocations to set
	 */
	public void setMetadataLocations(String metadataLocations) {
		this.metadataLocations = metadataLocations;
	}

	@Override
	public Map<String, Object> invoke() {
		return extract(this.context);
	}

	/**
	 * Extract beans annotated {@link ConfigurationProperties} and serialize into
	 * {@link Map}.
	 */
	protected Map<String, Object> extract(ApplicationContext context) {
		// Serialize beans into map structure and sanitize values
		ObjectMapper mapper = new ObjectMapper();
		configureObjectMapper(mapper);
		return extract(context, mapper);
	}

	private Map<String, Object> extract(ApplicationContext context, ObjectMapper mapper) {
		Map<String, Object> result = new HashMap<String, Object>();
		ConfigurationBeanFactoryMetaData beanFactoryMetaData = getBeanFactoryMetaData(context);
		Map<String, Object> beans = getConfigurationPropertiesBeans(context,
				beanFactoryMetaData);
		for (Map.Entry<String, Object> entry : beans.entrySet()) {
			String beanName = entry.getKey();
			Object bean = entry.getValue();
			Map<String, Object> root = new HashMap<String, Object>();
			String prefix = extractPrefix(context, beanFactoryMetaData, beanName, bean);
			root.put("prefix", prefix);
			root.put("properties", sanitize(safeSerialize(mapper, bean, prefix)));
			result.put(beanName, root);
		}
		if (context.getParent() != null) {
			result.put("parent", extract(context.getParent(), mapper));
		}
		return result;
	}

	private ConfigurationBeanFactoryMetaData getBeanFactoryMetaData(
			ApplicationContext context) {
		Map<String, ConfigurationBeanFactoryMetaData> beans = context
				.getBeansOfType(ConfigurationBeanFactoryMetaData.class);
		if (beans.size() == 1) {
			return beans.values().iterator().next();
		}
		return null;
	}

	private Map<String, Object> getConfigurationPropertiesBeans(
			ApplicationContext context,
			ConfigurationBeanFactoryMetaData beanFactoryMetaData) {
		Map<String, Object> beans = new HashMap<String, Object>();
		beans.putAll(context.getBeansWithAnnotation(ConfigurationProperties.class));
		if (beanFactoryMetaData != null) {
			beans.putAll(beanFactoryMetaData
					.getBeansWithFactoryAnnotation(ConfigurationProperties.class));
		}
		return beans;
	}

	/**
	 * Cautiously serialize the bean to a map (returning a map with an error message
	 * instead of throwing an exception if there is a problem).
	 */
	private Map<String, Object> safeSerialize(ObjectMapper mapper, Object bean,
			String prefix) {
		if (this.metadata == null) {
			this.metadata = new ConfigurationPropertiesMetaData(this.metadataLocations);
		}
		try {
			@SuppressWarnings("unchecked")
			Map<String, Object> result = new HashMap<String, Object>(mapper.convertValue(
					this.metadata.extractMap(bean, prefix), Map.class));
			return result;
		}
		catch (Exception ex) {
			return new HashMap<String, Object>(Collections.<String, Object> singletonMap(
					"error", "Cannot serialize '" + prefix + "'"));
		}
	}

	/**
	 * Configure Jackson's {@link ObjectMapper} to be used to serialize the
	 * {@link ConfigurationProperties} objects into a {@link Map} structure.
	 */
	protected void configureObjectMapper(ObjectMapper mapper) {
		mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
		mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
		applyCglibFilters(mapper);
		applySerializationModifier(mapper);
	}

	/**
	 * Ensure only bindable and non-cyclic bean properties are reported.
	 */
	private void applySerializationModifier(ObjectMapper mapper) {
		SerializerFactory factory = BeanSerializerFactory.instance
				.withSerializerModifier(new GenericSerializerModifier());
		mapper.setSerializerFactory(factory);
	}

	/**
	 * Configure PropertyFilter to make sure Jackson doesn't process CGLIB generated bean
	 * properties.
	 */
	private void applyCglibFilters(ObjectMapper mapper) {
		mapper.setAnnotationIntrospector(new CglibAnnotationIntrospector());
		mapper.setFilters(new SimpleFilterProvider().addFilter(CGLIB_FILTER_ID,
				new CglibBeanPropertyFilter()));
	}

	/**
	 * Extract configuration prefix from {@link ConfigurationProperties} annotation.
	 * @param beanFactoryMetaData
	 */
	private String extractPrefix(ApplicationContext context,
			ConfigurationBeanFactoryMetaData beanFactoryMetaData, String beanName,
			Object bean) {
		ConfigurationProperties annotation = context.findAnnotationOnBean(beanName,
				ConfigurationProperties.class);
		if (beanFactoryMetaData != null) {
			ConfigurationProperties override = beanFactoryMetaData.findFactoryAnnotation(
					beanName, ConfigurationProperties.class);
			if (override != null) {
				// The @Bean-level @ConfigurationProperties overrides the one at type
				// level when binding. Arguably we should render them both, but this one
				// might be the most relevant for a starting point.
				annotation = override;
			}
		}
		return (StringUtils.hasLength(annotation.value()) ? annotation.value()
				: annotation.prefix());
	}

	/**
	 * Sanitize all unwanted configuration properties to avoid leaking of sensitive
	 * information.
	 */
	@SuppressWarnings("unchecked")
	private Map<String, Object> sanitize(Map<String, Object> map) {
		for (Map.Entry<String, Object> entry : map.entrySet()) {
			String key = entry.getKey();
			Object value = entry.getValue();
			if (value instanceof Map) {
				map.put(key, sanitize((Map<String, Object>) value));
			}
			else {
				map.put(key, this.sanitizer.sanitize(key, value));
			}
		}
		return map;
	}

	/**
	 * Extension to {@link JacksonAnnotationIntrospector} to suppress CGLIB generated bean
	 * properties.
	 */
	@SuppressWarnings("serial")
	private static class CglibAnnotationIntrospector extends
			JacksonAnnotationIntrospector {

		@Override
		public Object findFilterId(Annotated a) {
			Object id = super.findFilterId(a);
			if (id == null) {
				id = CGLIB_FILTER_ID;
			}
			return id;
		}

	}

	/**
	 * {@link SimpleBeanPropertyFilter} to filter out all bean properties whose names
	 * start with '$$'.
	 */
	private static class CglibBeanPropertyFilter extends SimpleBeanPropertyFilter {

		@Override
		protected boolean include(BeanPropertyWriter writer) {
			return include(writer.getFullName().getSimpleName());
		}

		@Override
		protected boolean include(PropertyWriter writer) {
			return include(writer.getFullName().getSimpleName());
		}

		private boolean include(String name) {
			return !name.startsWith("$$");
		}

	}

	/**
	 * {@link BeanSerializerModifier} to return only relevant configuration properties.
	 */
	protected static class GenericSerializerModifier extends BeanSerializerModifier {

		@Override
		public List<BeanPropertyWriter> changeProperties(SerializationConfig config,
				BeanDescription beanDesc, List<BeanPropertyWriter> beanProperties) {
			List<BeanPropertyWriter> result = new ArrayList<BeanPropertyWriter>();
			for (BeanPropertyWriter writer : beanProperties) {
				boolean readable = isReadable(beanDesc, writer);
				if (readable) {
					result.add(writer);
				}
			}
			return result;
		}

		private boolean isReadable(BeanDescription beanDesc, BeanPropertyWriter writer) {
			String parentType = beanDesc.getType().getRawClass().getName();
			String type = writer.getPropertyType().getName();
			AnnotatedMethod setter = beanDesc.findMethod(
					"set" + StringUtils.capitalize(writer.getName()),
					new Class<?>[] { writer.getPropertyType() });
			// If there's a setter, we assume it's OK to report on the value,
			// similarly, if there's no setter but the package names match, we assume
			// that its a nested class used solely for binding to config props, so it
			// should be kosher. This filter is not used if there is JSON metadata for
			// the property, so it's mainly for user-defined beans.
			return (setter != null)
					|| ClassUtils.getPackageName(parentType).equals(
							ClassUtils.getPackageName(type));
		}
	}

	/**
	 * Convenience class for grabbing and caching valid property names from
	 * /META-INF/spring-configuration-metadata.json so that metadata that is known to be
	 * valid can be used to pull the correct nested properties out of beans that might
	 * otherwise be tricky (contain cycles or other unserializable properties).
	 */
	protected static class ConfigurationPropertiesMetaData {

		private final String metadataLocations;

		private final Map<String, Set<String>> matched = new HashMap<String, Set<String>>();

		private Set<String> keys = null;

		public ConfigurationPropertiesMetaData(String metadataLocations) {
			this.metadataLocations = metadataLocations;
		}

		public boolean matches(String prefix) {
			if (this.matched.containsKey(prefix)) {
				return matchesInternal(prefix);
			}
			synchronized (this.matched) {
				if (this.matched.containsKey(prefix)) {
					return matchesInternal(prefix);
				}
				this.matched.put(prefix, findKeys(prefix));
			}
			return matchesInternal(prefix);
		}

		private boolean matchesInternal(String prefix) {
			return this.matched.get(prefix) != null;
		}

		private Set<String> findKeys(String prefix) {
			HashSet<String> keys = new HashSet<String>();
			for (String key : getKeys()) {
				if (key.length() > prefix.length()
						&& key.startsWith(prefix)
						&& ".".equals(key.substring(prefix.length(), prefix.length() + 1))) {
					keys.add(key.substring(prefix.length() + 1));
				}
			}
			return (keys.isEmpty() ? null : keys);
		}

		private Set<String> getKeys() {
			if (this.keys != null) {
				return this.keys;
			}
			this.keys = new HashSet<String>();
			try {
				ObjectMapper mapper = new ObjectMapper();
				Resource[] resources = new PathMatchingResourcePatternResolver()
						.getResources(this.metadataLocations);
				for (Resource resource : resources) {
					addKeys(mapper, resource);
				}
			}
			catch (IOException ex) {
				logger.warn("Could not deserialize config properties metadata", ex);
			}
			return this.keys;
		}

		@SuppressWarnings("unchecked")
		private void addKeys(ObjectMapper mapper, Resource resource) throws IOException,
				JsonParseException, JsonMappingException {
			InputStream inputStream = resource.getInputStream();
			Map<String, Object> map = mapper.readValue(inputStream, Map.class);
			Collection<Map<String, Object>> metadata = (Collection<Map<String, Object>>) map
					.get("properties");
			for (Map<String, Object> value : metadata) {
				try {
					if (value.containsKey("type")) {
						this.keys.add((String) value.get("name"));
					}
				}
				catch (Exception ex) {
					logger.warn("Could not parse config properties metadata", ex);
				}
			}
		}

		public Object extractMap(Object bean, String prefix) {
			if (!matches(prefix)) {
				return bean;
			}
			Map<String, Object> map = new HashMap<String, Object>();
			for (String key : this.matched.get(prefix)) {
				addProperty(bean, key, map);
			}
			return map;
		}

		@SuppressWarnings("unchecked")
		private void addProperty(Object bean, String key, Map<String, Object> map) {
			String prefix = (key.contains(".") ? StringUtils.split(key, ".")[0] : key);
			String suffix = (key.length() > prefix.length() ? key.substring(prefix
					.length() + 1) : null);
			String property = prefix;
			if (bean instanceof Map) {
				Map<String, Object> value = (Map<String, Object>) bean;
				bean = new MapHolder(value);
				property = "map[" + property + "]";
			}
			BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
			try {
				Object value = wrapper.getPropertyValue(property);
				if (value instanceof Map) {
					Map<String, Object> nested = new HashMap<String, Object>();
					map.put(prefix, nested);
					if (suffix != null) {
						addProperty(value, suffix, nested);
					}
				}
				else {
					map.put(prefix, value);
				}
			}
			catch (Exception ex) {
				// Probably just lives on a different bean (it happens)
				logger.debug("Could not parse config properties metadata '" + key + "': "
						+ ex.getMessage());
			}
		}

		protected static class MapHolder {

			Map<String, Object> map = new HashMap<String, Object>();

			public MapHolder(Map<String, Object> bean) {
				this.map.putAll(bean);
			}

			public Map<String, Object> getMap() {
				return this.map;
			}

			public void setMap(Map<String, Object> map) {
				this.map = map;
			}

		}

	}

}


text:
echo "CVMFS_REPOSITORIES=mytestrepo.cern.ch" > /etc/cvmfs/default.local
echo "CVMFS_TIMEOUT=10" >> /etc/cvmfs/default.local
echo "CVMFS_TIMEOUT_DIRECT=5" >> /etc/cvmfs/default.local
echo "CVMFS_QUOTA_LIMIT=8000" >> /etc/cvmfs/default.local
echo "CVMFS_DEBUGLOG=/tmp/cvmfsdebug.log" >> /etc/cvmfs/default.local
echo "CVMFS_SERVER_URL=http://mytestrepo.cern.ch:8080/catalogs" > /etc/cvmfs/config.d/mytestrepo.cern.ch.conf
echo "CVMFS_PUBLIC_KEY=/tmp/cvmfs_master.pub" >> /etc/cvmfs/config.d/mytestrepo.cern.ch.conf
echo "CVMFS_HTTP_PROXY=\"http://mytestrepo.cern.ch:3128\"" >> /etc/cvmfs/config.d/mytestrepo.cern.ch.conf


text:
Pattern: Malformed space after `,`

Issue: -

## Description

Checks that there is at least one space or whitespace following each comma. That includes checks for method and closure declaration parameter lists, method call parameter lists, Map literals and List literals.

Known limitations:

-   May not catch actual violations if the source line contains unicode character literals, e.g. `'\u00A0'`

Examples of violations:

``` groovy
def value = calculate(1,399, 'abc')         // violation on parameter 399

def method1(int a,String b) { }             // violation on parameter b

def closure1 = { int a,String b -> }        // violation on parameter b

def list1 = [a,b, c]                        // violation on list element b

def map1 = [a:1,b:2, c:3]                   // violation on map element b:2
```

## Further Reading

* [CodeNarc - SpaceAfterComma](https://codenarc.github.io/CodeNarc/codenarc-rules-formatting.html#spaceaftercomma-rule)


text:
Website: http://hoosierphp.com (live version of this very code)

Hoosier PHP MVC framework.

This is a framework I've been working on for a while (at least in parts).
My main drive was to create a framework that more properly separated out the M V & C code and kept things clean, easy, & organized.
So many current frameworks are far more complicated than needed.
So I'm hoping to provide all the same tools, with a lot less hassle.
I also liked the idea of building a powerful framework that's also really easy to look under the hood and tweak.  For example, I love Symfony; but could you imagine digging in to some of its core code and tweaking something?  I would always hope that you'd never need to tweak any of Hoosier's core code, but if you take a peak, it will be very easy to understand and work with.

Where does the name "Hoosier" come from?
----------
Here: https://en.wikipedia.org/wiki/Hoosier_cabinet

Features:
----------
- Auto detecting database schema.  No need to code anything about each models' schema.
- no use of any templating tools for your views (straight PHP)
- Simple controller system. No extra config files. Using .htaccess file to handle URL parsing.
- Use of Memcache

Pre-Requisites:
----------
- Must have a Mysql DB setup.
- Must have Memcache installed.
- All DB Tables with an auto-increment primary key must have that primary key named 'id' (will eventually update code to make this more flexible).

Latest Updates:
----------
- Just replaced my old mysqli code for my pdo code.  I still need to complete the code handling "join" statements. But I'll get there soon.
- Began the /bin/hoosier.php script that will be the basic command line tool.  It currently works to create new models, but it will eventually do SO much more.

To Dos:
----------
- Update the /bin/hoosier.php: make it a compiled file: /bin/hoosier
- Update the /bin/hoosier.php: Add function to list all possible URLs based on the controller files.
- Update the /bin/hoosier.php: Add function to build out a schema file &/or an SQL schema dump file.
- I would also like to create a command line tool to init a Hoosier setup (not all sites need an admin or user section for example).
- I would also like to build a similar tool to edit existing Hoosier projects (maybe put this code in /bin/hoosier).
- Maybe create a tool to build out a config file or config-override file (maybe put this code in /bin/hoosier).
- Create different Database.php classes for PostgreSQL, MSSQL, & Oracle.  Eventually even NoSQL DBs.
- Create a Hoosier Install Tool which will be a command line script.  It will need to be versioned and recognize versions. But I would like to be able to install different basic setups (will there be a user interface? will there be an admin/user interface? do you need THIS plugin? do you need THAT plugin? etc.) based on a few quick questions.
- See if we can incorporate Doctrine or some other tool to manage DB Schema stuff.
- create a command line tool for applying updates and plugins.  System will keep track of what plugins you apply so that an update can re-apply those plugins post update.

How to get started:
----------
- build the DB.
- update any settings (including DB info) in the /conf/config.php &/or /conf/config-override.php file(s).
- start building your pages and classes (don't forget to "include" any new libraries in the /libraries/init.php file); models will be auto-loaded.

Suggestions:
----------
I do my code releases with a helper script (see /bin/release.sh). Though I have left it out of this repo (for now), I typically include some extra code to handle DB updates in there too.  This extra code would do three things:
- read in the file path to a sql file that would perform all needed updates.
- recreate the base_schema.sql file in /conf/database
- restart memcached

In accordance with this flow I would typically create a /conf/database/patches dir that would hold each release patch file.
I haven't decided if I will add this to the Hoosier repo or not.  So until I do, I'll leave these notes.


text:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE web-app PUBLIC
 "-//Oracle Corporation//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="2.5">
    <servlet>
        <servlet-name>demo</servlet-name>
        <servlet-class>myapp.MalloryServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>demo</servlet-name>
        <url-pattern>/demo</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>


text:
namespace command{
bool Test::isReplaced(){
    return false;
};
bool Test::usableFor(LPCHARACTER ch){
    return true;
};
void Test::use(CHARACTER* ch,std::vector<std::string> args){
    SQLMsg* msg = DBManager::instance()->DirectQuery("SELECT 1,2");
    MYSQL_RES* res=msg->Get()->pSQLResult;
    if (!res){
     // error
    }
    MYSQL_ROW row; // array of char* strings
    while ((row=mysql_fetch_row(res))){
     // row[0] is "1" (null-terminated char* string)
     // row[1] is "2"
        ch->ChatPacket(1,row[0]);
        ch->ChatPacket(1,row[1]);
     // if you want a number (int, bool etc) look into (http://www.cplusplus.com/reference/cstdlib/strtoul/)[stroul] and the sort
    }
};
}


text:
import { Component, OnInit } from '@angular/core';
import { NodeService } from '../../service/nodeservice';
import { TreeNode } from 'primeng/api';

@Component({
    templateUrl: './treedemo.html'
})
export class TreeDemo implements OnInit {
    files1: TreeNode[];

    files2: TreeNode[];

    constructor(private nodeService: NodeService) {}

    ngOnInit() {
        this.nodeService.getFiles().then((files) => (this.files1 = files));
        this.nodeService.getFiles().then((files) => (this.files2 = files));
    }

    expandAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, true);
        });
    }

    collapseAll() {
        this.files2.forEach((node) => {
            this.expandRecursive(node, false);
        });
    }

    private expandRecursive(node: TreeNode, isExpand: boolean) {
        node.expanded = isExpand;
        if (node.children) {
            node.children.forEach((childNode) => {
                this.expandRecursive(childNode, isExpand);
            });
        }
    }
}


text:
package dummy

import(
	KAFKA "transformer-business/adapter/kafka"
	PARSER "transformer-business/parser/parser_contents"
	RECORDER "transformer-business/recorder/contents"
	SPECIALIZED_RECORDERS "transformer-business/recorder/specialized_recorder"
	SPECIALIZED_SAVERS "transformer-business/saver/specialized_saver"
)

// Containers
var DummyKafka KAFKA.Dummy
var DummyParser PARSER.Dummy
var DummyRecorder RECORDER.Dummy

// Specialized
var DummySpecializedRecorder SPECIALIZED_RECORDERS.Dummy
var DummySpecializedSaver SPECIALIZED_SAVERS.Dummy


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_activit_main_menu">ActivitMainMenu</string>

    <!-- FRANÇAIS -->
    	<!-- Pager Menu -->
    		<string name="Categorias">Catégories</string>
    		<string name="Inicio">Home</string>

    <string name="actionbar_activity_not_found">Failed to open intent...</string>

	<!-- ============================== -->
    <!--  app/dialog examples strings  -->
    <!-- ============================== -->

    <string name="activity_alert_dialog">App/Dialog</string>
    <string name="alert_dialog_two_buttons">OK Cancel dialog with a message</string>
    <string name="alert_dialog_two_buttons2">OK Cancel dialog with a long message</string>
    <string name="alert_dialog_select_button">List dialog</string>
    <string name="alert_dialog_single_choice">Single choice list</string>
    <string name="alert_dialog_multi_choice">Repeat alarm</string>
    <string name="alert_dialog_multi_choice_cursor">Send Call to VoiceMail</string>
    <string name="alert_dialog_progress_button">Progress dialog</string>
    <string name="alert_dialog_text_entry">Text Entry dialog</string>
    <string name="alert_dialog_username">Name:</string>
    <string name="alert_dialog_password">Password:</string>
    <string name="alert_dialog_two_buttons_title">
        Lorem ipsum dolor sit aie consectetur adipiscing\nPlloaso mako nuto
        siwuf cakso dodtos anr koop.
    </string>
    <string name="alert_dialog_two_buttons_msg">Header title</string>
    <string name="alert_dialog_two_buttons2_msg">
        Plloaso mako nuto siwuf cakso dodtos anr koop a
        cupy uf cak vux noaw yerw phuno. Whag schengos, uf efed, quiel
        ba mada su otrenzr.\n\nSwipontgwook proudgs hus yag su ba dagarmidad.
        Plasa maku noga wipont trenzsa schengos ent kaap zux comy.\n\nWipont trenz
        kipg naar mixent phona. Cak pwico siructiun
        ruous nust apoply tyu cak Uhex sisulutiun munityuw uw dseg
    </string>
    <string name="alert_dialog_ok">OK</string>
    <string name="alert_dialog_hide">Hide</string>
    <string name="alert_dialog_something">Something</string>
    <string name="alert_dialog_cancel">Cancel</string>

    <string name="alert_dialog_progress_text2">145/305 KB</string>

    <string name="select_dialog">Header title</string>
    <string name="select_dialog_show">List dialog</string>

    <string name="title_section3">Section 3</string>
    <string name="title_section2">Section 2</string>
    <string name="title_section1">Section 1</string>
    <string name="mezzofanti_appName">Mezzofanti</string>
    <string name="mezzofanti_ocrResult">Your ocr result here</string>
    <string name="mezzofanti_msg_default_status">Press camera button to start OCR.</string>
    <string name="mezzofanti_status_text">Your status here</string>
    <string name="mezzofanti_ocr_processing_title">Text-recognition in progress:</string>
    <string name="mezzofanti_ocr_processing_body_begin">using the</string>
    <string name="mezzofanti_ocr_processing_body_end">dictionary.</string>
    <string name="mezzofanti_status_bar_vertical">Vertical </string>
    <string name="mezzofanti_status_bar_horizontal">Horizontal </string>
    <string name="mezzofanti_status_bar_updown">up/down</string>
    <string name="mezzofanti_status_bar_ocr_dict">OCR dictionary:</string>
    <string name="mezzofanti_status_bar_orientation">orientation:</string>
    <string name="mezzofanti_nolanginstalled_title">Warning</string>
    <string name="mezzofanti_nolanginstalled_body">No languages installed, please install using "menu->preferences->download languages"</string>
    <string name="mezzofanti_nolanginstalled_ok">OK</string>
    <string name="resultsactivity_add_word_to_dictionary_yes">Yes</string>
    <string name="resultsactivity_add_word_to_dictionary_no">No</string>
    <string name="resultsactivity_addword2dict_title">Add word to dictionary</string>
    <string name="resultsactivity_addword2dict_message1">Do you want to add the word</string>
    <string name="resultsactivity_addword2dict_message2">to the</string>
    <string name="resultsactivity_addword2dict_message3">dictionary?</string>
    <string name="resultsactivity_selected_word">Selected word: </string>
    <string name="resultsactivity_ocr_trust">OCR trust: </string>
    <string name="resultsactivity_ocr_valid_word">Valid</string>
    <string name="resultsactivity_ocr_valid_word2">word:</string>
    <string name="resultsactivity_resultsmode_selected_text">Selected text: </string>
    <string name="resultsactivity_resultsmode_selected_word_none">Selected word: none</string>
    <string name="resultsactivity_resultsmode_mean_confidence">Mean OCR confidence is</string>
    <string name="resultsactivity_resultsmode_selected_single_word">Single-word: translate/google/dictionary/wiki.</string>
    <string name="resultsactivity_resultsmode_selected_multiple_words">Multiple-words: translate/google/dictionary/wiki.</string>
    <string name="resultsactivity_resultsmode_edit_mode_back">To end Edit mode, press Back.</string>
    <string name="resultsactivity_ocrbadresults_title">Warning: </string>
    <string name="resultsactivity_ocrbadresults_msg1">The OCR confidence is</string>
    <string name="resultsactivity_ocrbadresults_msg2">(max=100) \n\n
This may happen for one of the following reasons: \n
- the OCR was optimized for speed, thus the quality is low (consider changing "Settings->speed vs quality")\n
- the angle of the camera relative to the text was more than the OCR could handle (consider taking the snapshot with the smallest angle to the text as possible)\n
- there was too much light in the picture (consider changing the position of the paper)\n\n</string>
    <string name="resultsactivity_ocrbadresults_ok">OK</string>
    <string name="mezzofanti_capturemode_statustext_switchtosmall">switch to small capture mode</string>
    <string name="mezzofanti_capturemode_statustext_switchtolarge">switch to large capture mode</string>
    <string name="mezzofanti_capturemode_statustext_switchtolarge2">delete-last / go-to-results</string>

    <!-- Menu -->
    <string name="menu_help">Help</string>
    <string name="menu_about">About us</string>
    <string name="menu_feedback">Feedback</string>

    <!-- Preferences -->
    <string name="preferences_helpTitle">Help</string>
    <string name="preferences_msg_help_step1">Welcome to Mezzofanti - Augmented reality through text-recognition.\n
    The application at a glance:\n
1. Select a text of interest (ex: menu at a restaurant, tourist information sign, etc), and take a photo. The internal-OCR engine will start Text Recognition.\n
2. Use Mezzofanti to translate the text (or parts of it) to any one of over forty languages, or to google it on the web or on Wikipedia.\n
    \n
    More insides about step 1 - Grabbing the picture and settings\n\n
    - you can switch between line/full-screen recognition\n
    - take the picture either with the "camera button" or by "long-press" on the screen
    - you can select either horizontal or vertical orientation while taking the picture, when the focus button is pressed you will observe indicators about your orientation\n
    - please make sure the camera focuses: green=focused, red=unfocused
    - the OCR will work best if the text is parallel to one of the margins (note: with a small tolerance of ~15 degree angle)\n
    - once the picture is taken, the OCR will start processing. Depending on the picture quality, and the amount of text, the processing may take roughly between 1-20 seconds.\n
	- to improve the speed of the OCR (in the detriment of the quality) you can use select from options "Settings->Speed/Quality ratio"\n
	- the OCR uses some language-specific files, by default the application has the English language installed, if you want to install another language to use with OCR, please go to "Settings->Download new languages"\n
	- if you are taking pictures with uneven light source, you may consider using the "Settings->Use uneven light filter" (note: this will add to the OCR processing time)\n
	- please select "Settings->Skip intro at startup" to enable/disable the intro message when the application starts\n
	- please select "Settring->Restore factory settings" if you want to switch back to the default settings.\n
	\n
	Enjoy using Mezzofanti! ;)\n
	The Wizard Team.\n
	\n
	PS: Please do not hesitate to write us feedback "Menu->Feedback". We are appreciating your thoughts.\n</string>
    <string name="preferences_msg_help_step2">Welcome to Mezzofanti!\n
    More insides about step 2 - Using the results\n\n
    Once the OCR has finished, you will be displayed the OCRed text along with confidence information in the status box.\n
    First thing you should make sure the text is similar to the original image. Mezzofanti will span the text, using italics where the word has a low confidence or is not a valid dictionary word. Pressing each word you can see more info about it.\n
    If you want to edit/modify the text you may do so using the appropriate "Edit" button. Note: if you are not happy with the OCR results, please take again the picture using increased "Settings->Speed/Quality ratio", also consider either an even light source for the paper surface (consult also the internal OCR image if needed), or use the "Settings->Use uneven light filter".\n
    When you are happy with the text, you can:\n
    - translate it in one of the 40 available languages\n
    - search parts of the text on Google\n
    - search parts of the text on Wiki\n
    - get information about a word from WikiDictionary\n
    With the options above, you may be interested to use the whole text or just select parts of it, for this use the "Select" button.\n
    \n
    At any time you can email/sms the text to yourself for later use or a friend.\n
    If you want to restart the whole process with another text, just hit the back button.\n
	\n
	Enjoy using Mezzofanti! ;)\n
	The Wizard Team.\n
	\n
	PS: Please do not hesitate to write us feedback "Menu->Feedback". We are appreciating your thoughts.\n</string>

    <!-- About -->
    <string name="preferences_aboutTitle">About us</string>
    <string name="preferences_msg_about">    More about the engine:\n
    - the internal text-recognition engine: Tesseract 2.03 - developed by Google and released under the Apache License 2.0\n
    - the translation engine - based on "Google translate" - API developed by Google and released under the Apache License\n
    - all code is source free, released under Apache License 2.0, for more information and the code please visit out website\n
    \n
    More about Mezzofanti:\n
    Giuseppe Caspar Mezzofanti (19 September 1774 – 15 March 1849) was an Italian cardinal and famed linguist and hyperpolyglot. Born and educated in Bologna, he completed his theological studies before he had reached the minimum age for ordination as a priest; he was ordained in 1797. In the same year, he became professor of Arabic at the University of Bologna. He later lost the position for refusing to take the oath of allegiance required by the Cisalpine Republic, which governed Bologna at the time.\n
    Mezzofanti was well-known for being a hyperpolyglot who fluently spoke thirty-eight languages and forty dialects, despite never traveling outside of Italy. He spoke at least twenty-eight languages perfectly: English, Welsh, Scottish Gaelic, German, Hebrew, Arabic, Aramaic, Coptic, Armenian, Persian, Turkish, Maltese, Ancient Greek, Modern Greek, Latin, Italian, Spanish, Portuguese, French, Swedish, Danish, Dutch, Russian, Polish, Czech, Hungarian, Chinese.\n
	\n
    More about IT Wizard:\n
	We started working together as a team in 2002 as preparation for IEEE's Computer Society International Design Competition. Following our first place in the world finals, we decided to join our expertise in hardware design and software development.The result was a young, tireless and enthusiastic team, Wizard, focused on providing companies with functioning prototypes and production solutions for their ideas. Our past activity involved extensive consulting on and enhancing of specific parts of existing embedded projects, software defined radios, mobile phone development.\n
	Members of Wizard team have been awarded gold medals for participation in past prestigious international competitions, such as the IEEE's CSIDC and ACM's ICPC contests. Our skills are reflected in Certificates of Excellence from the Romanian National Association of Software Industry, Romanian Ministry of Youth and Sport, and IEEE. Our results have also been published and presented at international events. Last, but not least, our trainees won top places at prestigious international competitions such as IEEE's CSIDC and Microsoft's Windows Embedded Challenge.\n

  	\n
	Enjoy using Mezzofanti! ;)\n
	The Wizard Team.\n
	\n
	PS: Please do not hesitate to write us feedback "Menu->Feedback". We are appreciating your thoughts.\n</string>

    <!-- Settings -->
    <string name="preferences_name">Settings</string>
    <string name="preferences_general_title">General settings</string>
    <string name="preferences_skip_intro_at_startup">Skip intro at start</string>
    <string name="preferences_OCR_title">OCR settings</string>
    <string name="preferences_use_image_ligth_filter">Use uneven light filter</string>
    <string name="preferences_display_debug_image">Display internal OCR image</string>
    <string name="preferences_speed_quality">Speed/Quality ratio</string>
    <string name="preferences_set_OCR_language">Set OCR dictionary language</string>
    <string name="preferences_download_language">Download new languages</string>
    <string name="preferences_min_overall_confidence">Min overall confidence</string>
    <string name="preferences_min_word_confidence">Min word confidence</string>
    <string name="preferences_translate_from_settings">Default translate-from</string>
    <string name="preferences_translate_to_settings">Default translate-in</string>
    <string name="preferences_restore_factory_settings_message">Are you sure?</string>
    <string name="preferences_restore_factory_settings_button_cancel">Cancel</string>
    <string name="preferences_restore_factory_settings_button_ok">OK</string>
    <string name="preferences_restore_factory_settings_title">Restore factory settings</string>
    <string name="preferences_button_cancel">OK</string>
    <string name="preferences_itwiz_url">http://www.itwizard.ro</string>
    <string name="preferences_button_open_browser">ITWizard web-site</string>
    <string name="preferencesactivity_reinstall"> - reinstall</string>
    <string name="preferencesactivity_cannotaccessinternet">cannot access internet</string>
    <string name="preferencesactivity_warning">Warning:</string>
    <string name="preferencesactivity_problems">Problems accessing language server. Please make sure internet connection is ok, before downloading a new language.</string>
    <string name="preferencesactivity_rfs_title">Restore factory settings</string>
    <string name="preferencesactivity_rfs_body">Are you sure?</string>
    <string name="preferencesactivity_imgsz_optimal">Optimal</string>
    <string name="preferencesactivity_imgsz_medium">Medium</string>
    <string name="preferencesactivity_rangedialog_title">Error Setting</string>
    <string name="preferencesactivity_rangedialog_body">Value must be in betwen 0 and 100</string>
    <string name="preferencesactivity_download_title">Download status:</string>
    <string name="preferencesactivity_downloaderr_body">Errors while installing new language.</string>
    <string name="preferencesactivity_downloaderrsdcard_body">No more space on SD Card, or SD Card removed.</string>
    <string name="preferencesactivity_downloadok_body">Language installed succesfully.</string>
    <string name="preferencesactivity_pd_title">In progress:</string>
    <string name="preferencesactivity_pd_body1">downloading </string>
    <string name="preferencesactivity_pd_body2">unziping .. </string>

    <!-- Install Activity -->
    <string name="installactivity_status_text">Your status here</string>
    <string name="installactivity_mainMessage">    Welcome to Mezzofanti - Augmented reality through text-recognition.\n
    \n
    The application at a glance:\n
1. Select a text of interest (ex: menu at a restaurant, tourist information sign, etc), and take a photo. The internal-OCR engine will start Text Recognition.\n
2. Use Mezzofanti to translate the text (or parts of it) to any one of over forty languages, or to google it on the web or on Wikipedia.\n
\n
Using Mezzofanti is just easy and fun to accomodate to a new language, or just get more information about the text in front of you.\n
\n\n
More about Mezzofanti: Giuseppe Caspar Mezzofanti (19 September 1774 – 15 March 1849) was an Italian cardinal and famed linguist and hyperpolyglot. Born and educated in Bologna, he completed his theological studies before he had reached the minimum age for ordination as a priest; he was ordained in 1797. In the same year, he became professor of Arabic at the University of Bologna. He later lost the position for refusing to take the oath of allegiance required by the Cisalpine Republic, which governed Bologna at the time.\n
\n
Mezzofanti was well-known for being a hyperpolyglot who fluently spoke thirty-eight languages and forty dialects, despite never traveling outside of Italy. He spoke at least twenty-eight languages perfectly: English, Welsh, Scottish Gaelic, German, Hebrew, Arabic, Aramaic, Coptic, Armenian, Persian, Turkish, Maltese, Ancient Greek, Modern Greek, Latin, Italian, Spanish, Portuguese, French, Swedish, Danish, Dutch, Russian, Polish, Czech, Hungarian, Chinese.\n
\n
More about IT Wizard: founded in 2005\n
    We started working together as a team in 2002 as preparation for IEEE's Computer Society International Design Competition. Following our first place in the world finals, we decided to join our expertise in hardware design and software development.The result was a young, tireless and enthusiastic team, Wizard, focused on providing companies with functioning prototypes and production solutions for their ideas. Our past activity involved extensive consulting on and enhancing of specific parts of existing embedded projects, software defined radios, mobile phone development.\n
    Members of Wizard team have been awarded gold medals for participation in past prestigious international competitions, such as the IEEE's CSIDC and ACM's ICPC contests. Our skills are reflected in Certificates of Excellence from the Romanian National Association of Software Industry, Romanian Ministry of Youth and Sport, and IEEE. Our results have also been published and presented at international events. Last, but not least, our trainees won top places at prestigious international competitions such as IEEE's CSIDC and Microsoft's Windows Embedded Challenge.\n

	\n
	Enjoy using Mezzofanti! ;)\n
	The Wizard Team.\n
	\n
	PS: Please do not hesitate to write us feedback "Menu->Feedback". We are appreciating your thoughts.\n
	\n</string>
    <string name="installactivity_name">Install Activity</string>

    <!-- Language dialog -->
    <string name="languagedialog_translateFrom">Translate from</string>
    <string name="languagedialog_translateIn">Translate in</string>

    <!-- Translate Activity -->
    <string name="translateactivity_name">Translate Activity</string>
    <string name="translateactivity_inprogress">Translation in progress</string>
    <string name="translateactivity_translate_OK">Translation successfully finished.</string>
    <string name="translateactivity_translate_FALSE">Translation error / Internet connection errors.</string>
    <string name="translateactivity_keep_text_yes">Yes</string>
    <string name="translateactivity_keep_text_no">No</string>
    <string name="translateactivity_dialog_keepeditedtext_title">Keep edited text</string>
    <string name="translateactivity_dialog_keepeditedtext_body">Do you want to keep edited text?</string>

    <!-- SD card messages -->
    <string name="mezzofanti_sdcard_preparing">Preparing SD card</string>
    <string name="mezzofanti_sdcard_unmount">Please insert the SD card before using Mezzofanti.</string>
    <string name="mezzofanti_sdcard_full">Your SD card is full.</string>
    <string name="mezzofanti_sdcard_wait">Please wait.</string>
    <string name="assetsmanager_title">Warning: </string>
    <string name="assetsmanager_msg1">Not enough space for installation on external storage - requested:</string>
    <string name="assetsmanager_msg2">free:</string>
    <string name="assetsmanager_ok">OK</string>
    <string name="mezzofanti_capturelayout_processing">Processing using</string>
    <string name="mezzofanti_capturelayout_processing2">dictionary.</string>
    <string name="mezzofanti_capturelayout_takingpicture">Taking the picture ...</string>
    <string name="resultsactivity_name">Results</string>
    <string name="resultsactivity_status_text">Your status here</string>
    <string name="title_activity_listdata">ListdataActivity</string>

</resources>


text:
#ifndef HAVE_NO_CONFIG
#include <votca_config.h>
#endif

#include <iostream>
#include "gmxtopologyreader.h"

#if GMX == 50
        #include <gromacs/fileio/tpxio.h>
#elif GMX == 45
        #include <gromacs/statutil.h>
        #include <gromacs/typedefs.h>
        #include <gromacs/smalloc.h>
        #include <gromacs/vec.h>
        #include <gromacs/copyrite.h>
        #include <gromacs/statutil.h>
        #include <gromacs/tpxio.h>
#elif GMX == 40
    extern "C"
    {
        #include <statutil.h>
        #include <typedefs.h>
        #include <smalloc.h>
        #include <vec.h>
        #include <copyrite.h>
        #include <statutil.h>
        #include <tpxio.h>
    }
#else
#error Unsupported GMX version
#endif
    // this one is needed because of bool is defined in one of the headers included by gmx
    #undef bool

namespace votca { namespace csg {

bool GMXTopologyReader::ReadTopology(string file, Topology &top)
{
    gmx_mtop_t mtop;

    int natoms;
    // cleanup topology to store new data
    top.Cleanup();

#if GMX == 50
    t_inputrec ir;
    ::matrix gbox;

    (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop);
#elif GMX == 45
    set_program_name("VOTCA");

    t_inputrec ir;
    ::matrix gbox;
    (void)read_tpx((char *)file.c_str(),&ir,gbox,&natoms,NULL,NULL,NULL,&mtop);
#elif GMX == 40
    set_program_name("VOTCA");

    int sss;   // wtf is this
    ::real    ttt,lll; // wtf is this
    (void)read_tpx((char *)file.c_str(),&sss,&ttt,&lll,NULL,NULL,&natoms,NULL,NULL,NULL,&mtop);
#else
#error Unsupported GMX version
#endif

    int count=0;
    for(int iblock=0; iblock<mtop.nmolblock; ++iblock)
        count+=mtop.molblock[iblock].nmol;

    if(count != mtop.mols.nr  ) {
        throw runtime_error("gromacs topology contains inconsistency in molecule definitons\n\n"
                "A possible reason is an outdated .tpr file. Please rerun grompp to generate a new tpr file.\n"
                "If the problem remains or "
                "you're missing the files to rerun grompp,\n contact the votca mailing list for a solution.");
    }

    for(int iblock=0; iblock<mtop.nmolblock; ++iblock) {
        gmx_moltype_t *mol
                = &(mtop.moltype[mtop.molblock[iblock].type]);

        string molname =  *(mol->name);

        int res_offset = top.ResidueCount();

        t_atoms *atoms=&(mol->atoms);

        for(int i=0; i < atoms->nres; i++) {
#if GMX == 50
                top.CreateResidue(*(atoms->resinfo[i].name));
#elif GMX == 45
                top.CreateResidue(*(atoms->resinfo[i].name));
#elif GMX == 40
                top.CreateResidue(*(atoms->resname[i]));
#else
#error Unsupported GMX version
#endif
        }

        int ifirstatom = 0;
        for(int imol=0; imol<mtop.molblock[iblock].nmol; ++imol) {
            Molecule *mi = top.CreateMolecule(molname);

            // read the atoms
            for(int iatom=0; iatom<mtop.molblock[iblock].natoms_mol; iatom++) {
                t_atom *a = &(atoms->atom[iatom]);

                BeadType *type = top.GetOrCreateBeadType(*(atoms->atomtype[iatom]));
#if GMX == 50
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind + res_offset, a->m, a->q);
#elif GMX == 45
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resind + res_offset, a->m, a->q);
#elif GMX == 40
                Bead *bead = top.CreateBead(1, *(atoms->atomname[iatom]), type, a->resnr + res_offset, a->m, a->q);
#else
#error Unsupported GMX version
#endif

                stringstream nm;
                nm << bead->getResnr() + 1 - res_offset << ":" <<  top.getResidue(bead->getResnr())->getName() << ":" << bead->getName();
                mi->AddBead(bead, nm.str());
            }

            // add exclusions
            for(int iatom=0; iatom<mtop.molblock[iblock].natoms_mol; iatom++) {
                t_atom *a = &(atoms->atom[iatom]);

                // read exclusions
                t_blocka * excl = &(mol->excls);
                // insert exclusions
                list<Bead *> excl_list;
                for(int k=excl->index[iatom]; k<excl->index[iatom+1]; k++) {
                	excl_list.push_back(top.getBead(excl->a[k]+ifirstatom));
                }
                top.InsertExclusion(top.getBead(iatom+ifirstatom), excl_list);
            }
            ifirstatom+=mtop.molblock[iblock].natoms_mol;
        }
    }

#if GMX != 40
    matrix m;
    for(int i=0; i<3; i++)
        for(int j=0; j<3; j++)
            m[i][j] = gbox[j][i];
    top.setBox(m);
#endif

    return true;
}

}}


text:
<?php

namespace Symfony\Component\PropertyAccess;

/**
 * A configurable builder for PropertyAccessorInterface objects.
 *
 * @author Jérémie Augustin <jeremie.augustin@pixel-cookers.com>
 */
class PropertyAccessorBuilder
{
    /**
     * @var bool
     */
    private $magicCall = false;

    /**
     * Enables the use of "__call" by the ProperyAccessor.
     *
     * @return PropertyAccessorBuilder The builder object
     */
    public function enableMagicCall()
    {
        $this->magicCall = true;

        return $this;
    }

    /**
     * Disables the use of "__call" by the ProperyAccessor.
     *
     * @return PropertyAccessorBuilder The builder object
     */
    public function disableMagicCall()
    {
        $this->magicCall = false;

        return $this;
    }

    /**
     * @return bool true if the use of "__call" by the ProperyAccessor is enabled
     */
    public function isMagicCallEnabled()
    {
        return $this->magicCall;
    }

    /**
     * Builds and returns a new propertyAccessor object.
     *
     * @return PropertyAccessorInterface The built propertyAccessor
     */
    public function getPropertyAccessor()
    {
        return new PropertyAccessor($this->magicCall);
    }
}


text:
<template>

                    ${group}

Individuelles

Par équipes

                ${row.title}

        <require from='./filters'></require>

            <router-view></router-view>

</template>