repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
statsbiblioteket/sbutil | sbutil-webservices/sbutil-webservices-logback/src/main/java/dk/statsbiblioteket/sbutil/LogBackConfigLoader.java | 1820 | package dk.statsbiblioteket.sbutil;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.IOException;
/**
* Simple Utility class for loading an external config file for logback
*
* @author daniel
*/
public class LogBackConfigLoader {
private Logger logger = LoggerFactory.getLogger(LogBackConfigLoader.class);
public LogBackConfigLoader(String externalConfigFileLocation) throws IOException, JoranException {
LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
File externalConfigFile = new File(externalConfigFileLocation);
System.out.println("Reading logback config from " + externalConfigFile.getAbsolutePath());
if (!externalConfigFile.exists()) {
throw new IOException("Logback External Config File Parameter does not reference a file that exists");
} else {
if (!externalConfigFile.isFile()) {
throw new IOException("Logback External Config File Parameter exists, but does not reference a file");
} else {
if (!externalConfigFile.canRead()) {
throw new IOException("Logback External Config File exists and is a file, but cannot be read.");
} else {
JoranConfigurator configurator = new JoranConfigurator();
configurator.setContext(lc);
lc.reset();
configurator.doConfigure(externalConfigFileLocation);
logger.info("Configured Logback with config file from: " + externalConfigFileLocation);
}
}
}
}
} | lgpl-2.1 |
lhanson/checkstyle | src/checkstyle/com/puppycrawl/tools/checkstyle/checks/javadoc/JavadocMethodCheck.java | 34531 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2010 Oliver Burn
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.javadoc;
import antlr.collections.AST;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.FileContents;
import com.puppycrawl.tools.checkstyle.api.FullIdent;
import com.puppycrawl.tools.checkstyle.api.JavadocTag;
import com.puppycrawl.tools.checkstyle.api.JavadocTagInfo;
import com.puppycrawl.tools.checkstyle.api.Scope;
import com.puppycrawl.tools.checkstyle.api.ScopeUtils;
import com.puppycrawl.tools.checkstyle.api.TextBlock;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
import com.puppycrawl.tools.checkstyle.api.Utils;
import com.puppycrawl.tools.checkstyle.checks.AbstractTypeAwareCheck;
import com.puppycrawl.tools.checkstyle.checks.CheckUtils;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Checks the Javadoc of a method or constructor.
*
* @author Oliver Burn
* @author Rick Giles
* @author o_sukhodoslky
*/
public class JavadocMethodCheck extends AbstractTypeAwareCheck
{
/** compiled regexp to match Javadoc tags that take an argument * */
private static final Pattern MATCH_JAVADOC_ARG =
Utils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s+\\S*");
/** compiled regexp to match first part of multilineJavadoc tags * */
private static final Pattern MATCH_JAVADOC_ARG_MULTILINE_START =
Utils.createPattern("@(throws|exception|param)\\s+(\\S+)\\s*$");
/** compiled regexp to look for a continuation of the comment * */
private static final Pattern MATCH_JAVADOC_MULTILINE_CONT =
Utils.createPattern("(\\*/|@|[^\\s\\*])");
/** Multiline finished at end of comment * */
private static final String END_JAVADOC = "*/";
/** Multiline finished at next Javadoc * */
private static final String NEXT_TAG = "@";
/** compiled regexp to match Javadoc tags with no argument * */
private static final Pattern MATCH_JAVADOC_NOARG =
Utils.createPattern("@(return|see)\\s+\\S");
/** compiled regexp to match first part of multilineJavadoc tags * */
private static final Pattern MATCH_JAVADOC_NOARG_MULTILINE_START =
Utils.createPattern("@(return|see)\\s*$");
/** compiled regexp to match Javadoc tags with no argument and {} * */
private static final Pattern MATCH_JAVADOC_NOARG_CURLY =
Utils.createPattern("\\{\\s*@(inheritDoc)\\s*\\}");
/** Maximum children allowed * */
private static final int MAX_CHILDREN = 7;
/** Maximum children allowed * */
private static final int BODY_SIZE = 3;
/** the visibility scope where Javadoc comments are checked * */
private Scope mScope = Scope.PRIVATE;
/** the visibility scope where Javadoc comments shouldn't be checked * */
private Scope mExcludeScope;
/**
* controls whether to allow documented exceptions that are not declared if
* they are a subclass of java.lang.RuntimeException.
*/
private boolean mAllowUndeclaredRTE;
/**
* controls whether to allow documented exceptions that are subclass of one
* of declared exception. Defaults to false (backward compatibility).
*/
private boolean mAllowThrowsTagsForSubclasses;
/**
* controls whether to ignore errors when a method has parameters but does
* not have matching param tags in the javadoc. Defaults to false.
*/
private boolean mAllowMissingParamTags;
/**
* controls whether to ignore errors when a method declares that it throws
* exceptions but does not have matching throws tags in the javadoc.
* Defaults to false.
*/
private boolean mAllowMissingThrowsTags;
/**
* controls whether to ignore errors when a method returns non-void type
* but does not have a return tag in the javadoc. Defaults to false.
*/
private boolean mAllowMissingReturnTag;
/**
* Controls whether to ignore errors when there is no javadoc. Defaults to
* false.
*/
private boolean mAllowMissingJavadoc;
/**
* Controls whether to allow missing Javadoc on accessor methods for
* properties (setters and getters).
*/
private boolean mAllowMissingPropertyJavadoc;
/**
* Set the scope.
*
* @param aFrom a <code>String</code> value
*/
public void setScope(String aFrom)
{
mScope = Scope.getInstance(aFrom);
}
/**
* Set the excludeScope.
*
* @param aScope a <code>String</code> value
*/
public void setExcludeScope(String aScope)
{
mExcludeScope = Scope.getInstance(aScope);
}
/**
* controls whether to allow documented exceptions that are not declared if
* they are a subclass of java.lang.RuntimeException.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowUndeclaredRTE(boolean aFlag)
{
mAllowUndeclaredRTE = aFlag;
}
/**
* controls whether to allow documented exception that are subclass of one
* of declared exceptions.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowThrowsTagsForSubclasses(boolean aFlag)
{
mAllowThrowsTagsForSubclasses = aFlag;
}
/**
* controls whether to allow a method which has parameters to omit matching
* param tags in the javadoc. Defaults to false.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingParamTags(boolean aFlag)
{
mAllowMissingParamTags = aFlag;
}
/**
* controls whether to allow a method which declares that it throws
* exceptions to omit matching throws tags in the javadoc. Defaults to
* false.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingThrowsTags(boolean aFlag)
{
mAllowMissingThrowsTags = aFlag;
}
/**
* controls whether to allow a method which returns non-void type to omit
* the return tag in the javadoc. Defaults to false.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingReturnTag(boolean aFlag)
{
mAllowMissingReturnTag = aFlag;
}
/**
* Controls whether to ignore errors when there is no javadoc. Defaults to
* false.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingJavadoc(boolean aFlag)
{
mAllowMissingJavadoc = aFlag;
}
/**
* Controls whether to ignore errors when there is no javadoc for a
* property accessor (setter/getter methods). Defaults to false.
*
* @param aFlag a <code>Boolean</code> value
*/
public void setAllowMissingPropertyJavadoc(final boolean aFlag)
{
mAllowMissingPropertyJavadoc = aFlag;
}
@Override
public int[] getDefaultTokens()
{
return new int[] {TokenTypes.PACKAGE_DEF, TokenTypes.IMPORT,
TokenTypes.CLASS_DEF, TokenTypes.ENUM_DEF,
TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF,
TokenTypes.ANNOTATION_FIELD_DEF,
};
}
@Override
public int[] getAcceptableTokens()
{
return new int[] {TokenTypes.METHOD_DEF, TokenTypes.CTOR_DEF,
TokenTypes.ANNOTATION_FIELD_DEF,
};
}
@Override
protected final void processAST(DetailAST aAST)
{
final Scope theScope = calculateScope(aAST);
if (shouldCheck(aAST, theScope)) {
final FileContents contents = getFileContents();
final TextBlock cmt = contents.getJavadocBefore(aAST.getLineNo());
if (cmt == null) {
if (!isMissingJavadocAllowed(aAST)) {
log(aAST, "javadoc.missing");
}
}
else {
checkComment(aAST, cmt, theScope);
}
}
}
@Override
protected final void logLoadError(Token aIdent)
{
logLoadErrorImpl(aIdent.getLineNo(), aIdent.getColumnNo(),
"javadoc.classInfo",
JavadocTagInfo.THROWS.getText(), aIdent.getText());
}
/**
* The JavadocMethodCheck is about to report a missing Javadoc.
* This hook can be used by derived classes to allow a missing javadoc
* in some situations. The default implementation checks
* <code>allowMissingJavadoc</code> and
* <code>allowMissingPropertyJavadoc</code> properties, do not forget
* to call <code>super.isMissingJavadocAllowed(aAST)</code> in case
* you want to keep this logic.
* @param aAST the tree node for the method or constructor.
* @return True if this method or constructor doesn't need Javadoc.
*/
protected boolean isMissingJavadocAllowed(final DetailAST aAST)
{
return mAllowMissingJavadoc || isOverrideMethod(aAST)
|| (mAllowMissingPropertyJavadoc
&& (isSetterMethod(aAST) || isGetterMethod(aAST)));
}
/**
* Whether we should check this node.
*
* @param aAST a given node.
* @param aScope the scope of the node.
* @return whether we should check a given node.
*/
private boolean shouldCheck(final DetailAST aAST, final Scope aScope)
{
final Scope surroundingScope = ScopeUtils.getSurroundingScope(aAST);
return aScope.isIn(mScope)
&& surroundingScope.isIn(mScope)
&& ((mExcludeScope == null) || !aScope.isIn(mExcludeScope)
|| !surroundingScope.isIn(mExcludeScope));
}
/**
* Checks the Javadoc for a method.
*
* @param aAST the token for the method
* @param aComment the Javadoc comment
* @param aScope the scope of the method.
*/
private void checkComment(DetailAST aAST, TextBlock aComment, Scope aScope)
{
final List<JavadocTag> tags = getMethodTags(aComment);
if (hasShortCircuitTag(aAST, tags, aScope)) {
return;
}
Iterator<JavadocTag> it = tags.iterator();
if (aAST.getType() != TokenTypes.ANNOTATION_FIELD_DEF) {
// Check for inheritDoc
boolean hasInheritDocTag = false;
while (it.hasNext() && !hasInheritDocTag) {
hasInheritDocTag |= (it.next()).isInheritDocTag();
}
checkParamTags(tags, aAST, !hasInheritDocTag);
checkThrowsTags(tags, getThrows(aAST), !hasInheritDocTag);
if (isFunction(aAST)) {
checkReturnTag(tags, aAST.getLineNo(), !hasInheritDocTag);
}
}
// Dump out all unused tags
it = tags.iterator();
while (it.hasNext()) {
final JavadocTag jt = it.next();
if (!jt.isSeeOrInheritDocTag()) {
log(jt.getLineNo(), "javadoc.unusedTagGeneral");
}
}
}
/**
* Validates whether the Javadoc has a short circuit tag. Currently this is
* the inheritTag. Any errors are logged.
*
* @param aAST the construct being checked
* @param aTags the list of Javadoc tags associated with the construct
* @param aScope the scope of the construct
* @return true if the construct has a short circuit tag.
*/
private boolean hasShortCircuitTag(final DetailAST aAST,
final List<JavadocTag> aTags, final Scope aScope)
{
// Check if it contains {@inheritDoc} tag
if ((aTags.size() != 1)
|| !(aTags.get(0)).isInheritDocTag())
{
return false;
}
// Invalid if private, a constructor, or a static method
if (!JavadocTagInfo.INHERIT_DOC.isValidOn(aAST)) {
log(aAST, "javadoc.invalidInheritDoc");
}
return true;
}
/**
* Returns the scope for the method/constructor at the specified AST. If
* the method is in an interface or annotation block, the scope is assumed
* to be public.
*
* @param aAST the token of the method/constructor
* @return the scope of the method/constructor
*/
private Scope calculateScope(final DetailAST aAST)
{
final DetailAST mods = aAST.findFirstToken(TokenTypes.MODIFIERS);
final Scope declaredScope = ScopeUtils.getScopeFromMods(mods);
return ScopeUtils.inInterfaceOrAnnotationBlock(aAST) ? Scope.PUBLIC
: declaredScope;
}
/**
* Returns the tags in a javadoc comment. Only finds throws, exception,
* param, return and see tags.
*
* @return the tags found
* @param aComment the Javadoc comment
*/
private List<JavadocTag> getMethodTags(TextBlock aComment)
{
final String[] lines = aComment.getText();
final List<JavadocTag> tags = Lists.newArrayList();
int currentLine = aComment.getStartLineNo() - 1;
for (int i = 0; i < lines.length; i++) {
currentLine++;
final Matcher javadocArgMatcher =
MATCH_JAVADOC_ARG.matcher(lines[i]);
final Matcher javadocNoargMatcher =
MATCH_JAVADOC_NOARG.matcher(lines[i]);
final Matcher noargCurlyMatcher =
MATCH_JAVADOC_NOARG_CURLY.matcher(lines[i]);
final Matcher argMultilineStart =
MATCH_JAVADOC_ARG_MULTILINE_START.matcher(lines[i]);
final Matcher noargMultilineStart =
MATCH_JAVADOC_NOARG_MULTILINE_START.matcher(lines[i]);
if (javadocArgMatcher.find()) {
int col = javadocArgMatcher.start(1) - 1;
if (i == 0) {
col += aComment.getStartColNo();
}
tags.add(new JavadocTag(currentLine, col, javadocArgMatcher
.group(1), javadocArgMatcher.group(2)));
}
else if (javadocNoargMatcher.find()) {
int col = javadocNoargMatcher.start(1) - 1;
if (i == 0) {
col += aComment.getStartColNo();
}
tags.add(new JavadocTag(currentLine, col, javadocNoargMatcher
.group(1)));
}
else if (noargCurlyMatcher.find()) {
int col = noargCurlyMatcher.start(1) - 1;
if (i == 0) {
col += aComment.getStartColNo();
}
tags.add(new JavadocTag(currentLine, col, noargCurlyMatcher
.group(1)));
}
else if (argMultilineStart.find()) {
final String p1 = argMultilineStart.group(1);
final String p2 = argMultilineStart.group(2);
int col = argMultilineStart.start(1) - 1;
if (i == 0) {
col += aComment.getStartColNo();
}
// Look for the rest of the comment if all we saw was
// the tag and the name. Stop when we see '*/' (end of
// Javadoc), '@' (start of next tag), or anything that's
// not whitespace or '*' characters.
int remIndex = i + 1;
while (remIndex < lines.length) {
final Matcher multilineCont = MATCH_JAVADOC_MULTILINE_CONT
.matcher(lines[remIndex]);
if (multilineCont.find()) {
remIndex = lines.length;
final String lFin = multilineCont.group(1);
if (!lFin.equals(NEXT_TAG)
&& !lFin.equals(END_JAVADOC))
{
tags.add(new JavadocTag(currentLine, col, p1, p2));
}
}
remIndex++;
}
}
else if (noargMultilineStart.find()) {
final String p1 = noargMultilineStart.group(1);
int col = noargMultilineStart.start(1) - 1;
if (i == 0) {
col += aComment.getStartColNo();
}
// Look for the rest of the comment if all we saw was
// the tag and the name. Stop when we see '*/' (end of
// Javadoc), '@' (start of next tag), or anything that's
// not whitespace or '*' characters.
int remIndex = i + 1;
while (remIndex < lines.length) {
final Matcher multilineCont = MATCH_JAVADOC_MULTILINE_CONT
.matcher(lines[remIndex]);
if (multilineCont.find()) {
remIndex = lines.length;
final String lFin = multilineCont.group(1);
if (!lFin.equals(NEXT_TAG)
&& !lFin.equals(END_JAVADOC))
{
tags.add(new JavadocTag(currentLine, col, p1));
}
}
remIndex++;
}
}
}
return tags;
}
/**
* Computes the parameter nodes for a method.
*
* @param aAST the method node.
* @return the list of parameter nodes for aAST.
*/
private List<DetailAST> getParameters(DetailAST aAST)
{
final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
final List<DetailAST> retVal = Lists.newArrayList();
DetailAST child = params.getFirstChild();
while (child != null) {
if (child.getType() == TokenTypes.PARAMETER_DEF) {
final DetailAST ident = child.findFirstToken(TokenTypes.IDENT);
retVal.add(ident);
}
child = child.getNextSibling();
}
return retVal;
}
/**
* Computes the exception nodes for a method.
*
* @param aAST the method node.
* @return the list of exception nodes for aAST.
*/
private List<ExceptionInfo> getThrows(DetailAST aAST)
{
final List<ExceptionInfo> retVal = Lists.newArrayList();
final DetailAST throwsAST = aAST
.findFirstToken(TokenTypes.LITERAL_THROWS);
if (throwsAST != null) {
DetailAST child = throwsAST.getFirstChild();
while (child != null) {
if ((child.getType() == TokenTypes.IDENT)
|| (child.getType() == TokenTypes.DOT))
{
final FullIdent fi = FullIdent.createFullIdent(child);
final ExceptionInfo ei = new ExceptionInfo(new Token(fi),
getCurrentClassName());
retVal.add(ei);
}
child = child.getNextSibling();
}
}
return retVal;
}
/**
* Checks a set of tags for matching parameters.
*
* @param aTags the tags to check
* @param aParent the node which takes the parameters
* @param aReportExpectedTags whether we should report if do not find
* expected tag
*/
private void checkParamTags(final List<JavadocTag> aTags,
final DetailAST aParent, boolean aReportExpectedTags)
{
final List<DetailAST> params = getParameters(aParent);
final List<DetailAST> typeParams = CheckUtils
.getTypeParameters(aParent);
// Loop over the tags, checking to see they exist in the params.
final ListIterator<JavadocTag> tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = tagIt.next();
if (!tag.isParamTag()) {
continue;
}
tagIt.remove();
boolean found = false;
// Loop looking for matching param
final Iterator<DetailAST> paramIt = params.iterator();
while (paramIt.hasNext()) {
final DetailAST param = paramIt.next();
if (param.getText().equals(tag.getArg1())) {
found = true;
paramIt.remove();
break;
}
}
if (tag.getArg1().startsWith("<") && tag.getArg1().endsWith(">")) {
// Loop looking for matching type param
final Iterator<DetailAST> typeParamsIt = typeParams.iterator();
while (typeParamsIt.hasNext()) {
final DetailAST typeParam = typeParamsIt.next();
if (typeParam.findFirstToken(TokenTypes.IDENT).getText()
.equals(
tag.getArg1().substring(1,
tag.getArg1().length() - 1)))
{
found = true;
typeParamsIt.remove();
break;
}
}
}
// Handle extra JavadocTag
if (!found) {
log(tag.getLineNo(), tag.getColumnNo(), "javadoc.unusedTag",
"@param", tag.getArg1());
}
}
// Now dump out all type parameters/parameters without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingParamTags && aReportExpectedTags) {
for (DetailAST param : params) {
log(param, "javadoc.expectedTag",
JavadocTagInfo.PARAM.getText(), param.getText());
}
for (DetailAST typeParam : typeParams) {
log(typeParam, "javadoc.expectedTag",
JavadocTagInfo.PARAM.getText(),
"<" + typeParam.findFirstToken(TokenTypes.IDENT).getText()
+ ">");
}
}
}
/**
* Checks whether a method is a function.
*
* @param aAST the method node.
* @return whether the method is a function.
*/
private boolean isFunction(DetailAST aAST)
{
boolean retVal = false;
if (aAST.getType() == TokenTypes.METHOD_DEF) {
final DetailAST typeAST = aAST.findFirstToken(TokenTypes.TYPE);
if ((typeAST != null)
&& (typeAST.findFirstToken(TokenTypes.LITERAL_VOID) == null))
{
retVal = true;
}
}
return retVal;
}
/**
* Checks for only one return tag. All return tags will be removed from the
* supplied list.
*
* @param aTags the tags to check
* @param aLineNo the line number of the expected tag
* @param aReportExpectedTags whether we should report if do not find
* expected tag
*/
private void checkReturnTag(List<JavadocTag> aTags, int aLineNo,
boolean aReportExpectedTags)
{
// Loop over tags finding return tags. After the first one, report an
// error.
boolean found = false;
final ListIterator<JavadocTag> it = aTags.listIterator();
while (it.hasNext()) {
final JavadocTag jt = it.next();
if (jt.isReturnTag()) {
if (found) {
log(jt.getLineNo(), jt.getColumnNo(),
"javadoc.duplicateTag",
JavadocTagInfo.RETURN.getText());
}
found = true;
it.remove();
}
}
// Handle there being no @return tags :- unless
// the user has chosen to suppress these problems
if (!found && !mAllowMissingReturnTag && aReportExpectedTags) {
log(aLineNo, "javadoc.return.expected");
}
}
/**
* Checks a set of tags for matching throws.
*
* @param aTags the tags to check
* @param aThrows the throws to check
* @param aReportExpectedTags whether we should report if do not find
* expected tag
*/
private void checkThrowsTags(List<JavadocTag> aTags,
List<ExceptionInfo> aThrows, boolean aReportExpectedTags)
{
// Loop over the tags, checking to see they exist in the throws.
// The foundThrows used for performance only
final Set<String> foundThrows = Sets.newHashSet();
final ListIterator<JavadocTag> tagIt = aTags.listIterator();
while (tagIt.hasNext()) {
final JavadocTag tag = tagIt.next();
if (!tag.isThrowsTag()) {
continue;
}
tagIt.remove();
// Loop looking for matching throw
final String documentedEx = tag.getArg1();
final Token token = new Token(tag.getArg1(), tag.getLineNo(), tag
.getColumnNo());
final ClassInfo documentedCI = createClassInfo(token,
getCurrentClassName());
boolean found = foundThrows.contains(documentedEx);
// First look for matches on the exception name
ListIterator<ExceptionInfo> throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = throwIt.next();
if (ei.getName().getText().equals(
documentedCI.getName().getText()))
{
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
}
// Now match on the exception type
throwIt = aThrows.listIterator();
while (!found && throwIt.hasNext()) {
final ExceptionInfo ei = throwIt.next();
if (documentedCI.getClazz() == ei.getClazz()) {
found = true;
ei.setFound();
foundThrows.add(documentedEx);
}
else if (mAllowThrowsTagsForSubclasses) {
found = isSubclass(documentedCI.getClazz(), ei.getClazz());
}
}
// Handle extra JavadocTag.
if (!found) {
boolean reqd = true;
if (mAllowUndeclaredRTE) {
reqd = !isUnchecked(documentedCI.getClazz());
}
if (reqd) {
log(tag.getLineNo(), tag.getColumnNo(),
"javadoc.unusedTag",
JavadocTagInfo.THROWS.getText(), tag.getArg1());
}
}
}
// Now dump out all throws without tags :- unless
// the user has chosen to suppress these problems
if (!mAllowMissingThrowsTags && aReportExpectedTags) {
for (ExceptionInfo ei : aThrows) {
if (!ei.isFound()) {
final Token fi = ei.getName();
log(fi.getLineNo(), fi.getColumnNo(),
"javadoc.expectedTag",
JavadocTagInfo.THROWS.getText(), fi.getText());
}
}
}
}
/**
* Returns whether an AST represents a setter method.
* @param aAST the AST to check with
* @return whether the AST represents a setter method
*/
private boolean isSetterMethod(final DetailAST aAST)
{
// Check have a method with exactly 7 children which are all that
// is allowed in a proper setter method which does not throw any
// exceptions.
if ((aAST.getType() != TokenTypes.METHOD_DEF)
|| (aAST.getChildCount() != MAX_CHILDREN))
{
return false;
}
// Should I handle only being in a class????
// Check the name matches format setX...
final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE);
final String name = type.getNextSibling().getText();
if (!name.matches("^set[A-Z].*")) { // Depends on JDK 1.4
return false;
}
// Check the return type is void
if (type.getChildCount(TokenTypes.LITERAL_VOID) == 0) {
return false;
}
// Check that is had only one parameter
final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
if ((params == null)
|| (params.getChildCount(TokenTypes.PARAMETER_DEF) != 1))
{
return false;
}
// Now verify that the body consists of:
// SLIST -> EXPR -> ASSIGN
// SEMI
// RCURLY
final DetailAST slist = aAST.findFirstToken(TokenTypes.SLIST);
if ((slist == null) || (slist.getChildCount() != BODY_SIZE)) {
return false;
}
final AST expr = slist.getFirstChild();
if ((expr.getType() != TokenTypes.EXPR)
|| (expr.getFirstChild().getType() != TokenTypes.ASSIGN))
{
return false;
}
return true;
}
/**
* Returns whether an AST represents a getter method.
* @param aAST the AST to check with
* @return whether the AST represents a getter method
*/
private boolean isGetterMethod(final DetailAST aAST)
{
// Check have a method with exactly 7 children which are all that
// is allowed in a proper getter method which does not throw any
// exceptions.
if ((aAST.getType() != TokenTypes.METHOD_DEF)
|| (aAST.getChildCount() != MAX_CHILDREN))
{
return false;
}
// Check the name matches format of getX or isX. Technically I should
// check that the format isX is only used with a boolean type.
final DetailAST type = aAST.findFirstToken(TokenTypes.TYPE);
final String name = type.getNextSibling().getText();
if (!name.matches("^(is|get)[A-Z].*")) { // Depends on JDK 1.4
return false;
}
// Check the return type is void
if (type.getChildCount(TokenTypes.LITERAL_VOID) > 0) {
return false;
}
// Check that is had only one parameter
final DetailAST params = aAST.findFirstToken(TokenTypes.PARAMETERS);
if ((params == null)
|| (params.getChildCount(TokenTypes.PARAMETER_DEF) > 0))
{
return false;
}
// Now verify that the body consists of:
// SLIST -> RETURN
// RCURLY
final DetailAST slist = aAST.findFirstToken(TokenTypes.SLIST);
if ((slist == null) || (slist.getChildCount() != 2)) {
return false;
}
final AST expr = slist.getFirstChild();
if ((expr.getType() != TokenTypes.LITERAL_RETURN)
|| (expr.getFirstChild().getType() != TokenTypes.EXPR))
{
return false;
}
return true;
}
/**
* Returns is a method has the "@Override" annotation.
* @param aAST the AST to check with
* @return whether the AST represents a method that has the annotation.
*/
private boolean isOverrideMethod(DetailAST aAST)
{
// Need it to be a method, cannot have an override on anything else.
// Must also have MODIFIERS token to hold the @Override
if ((TokenTypes.METHOD_DEF != aAST.getType())
|| (TokenTypes.MODIFIERS != aAST.getFirstChild().getType()))
{
return false;
}
// Now loop over all nodes while they are annotations looking for
// an "@Override".
DetailAST node = aAST.getFirstChild().getFirstChild();
while ((null != node) && (TokenTypes.ANNOTATION == node.getType())) {
if ((node.getFirstChild().getType() == TokenTypes.AT)
&& (node.getFirstChild().getNextSibling().getType()
== TokenTypes.IDENT)
&& ("Override".equals(
node.getFirstChild().getNextSibling().getText())))
{
return true;
}
node = node.getNextSibling();
}
return false;
}
/** Stores useful information about declared exception. */
private class ExceptionInfo
{
/** does the exception have throws tag associated with. */
private boolean mFound;
/** class information associated with this exception. */
private final ClassInfo mClassInfo;
/**
* Creates new instance for <code>FullIdent</code>.
*
* @param aIdent the exception
* @param aCurrentClass name of current class.
*/
ExceptionInfo(Token aIdent, String aCurrentClass)
{
mClassInfo = createClassInfo(aIdent, aCurrentClass);
}
/** Mark that the exception has associated throws tag */
final void setFound()
{
mFound = true;
}
/** @return whether the exception has throws tag associated with */
final boolean isFound()
{
return mFound;
}
/** @return exception's name */
final Token getName()
{
return mClassInfo.getName();
}
/** @return class for this exception */
final Class<?> getClazz()
{
return mClassInfo.getClazz();
}
}
}
| lgpl-2.1 |
JamesK89/gmsqlite3 | src/module.cpp | 22868 | /*
Gm_sqlite3 the improved sqlite library for Garry's Mod
Copyright (C) 2010 James John Kelly Jr
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "module.h"
#include "database.h"
#include "statement.h"
#include "LuaDatabase.h"
#include "LuaStatement.h"
ILuaInterface* g_pLua = NULL;
//-----------------------------------------------------------------------------
// Small misc functions
//-----------------------------------------------------------------------------
LUA_FUNCTION(MiscIsStatementComplete)
{
g_pLua->CheckType(1, GLua::TYPE_STRING);
g_pLua->Push((float)sqlite3_complete(g_pLua->GetString(1)));
return 1;
}
LUA_FUNCTION(MiscLibVersion)
{
g_pLua->Push((const char*)sqlite3_libversion());
return 1;
}
LUA_FUNCTION(MiscLibVersionNumber)
{
g_pLua->Push((float)sqlite3_libversion_number());
return 1;
}
LUA_FUNCTION(MiscSourceId)
{
g_pLua->Push((const char*)sqlite3_sourceid());
return 1;
}
//-----------------------------------------------------------------------------
// Called when the DLL is being initialized
//-----------------------------------------------------------------------------
int Init(lua_State* L)
{
sqlite3_initialize();
g_pLua = Lua();
// Database object definition
ILuaObject* pMetaDatabase = g_pLua->GetMetaTable(META_DATABASE, TYPE_DATABASE);
if( pMetaDatabase )
{
// Destructor
pMetaDatabase->SetMember("__gc", LUA_FUNC(DatabaseDelete));
ILuaObject* pMembersDatabase = g_pLua->GetNewTable();
if( pMembersDatabase )
{
pMembersDatabase->SetMember("Open", LUA_FUNC(DatabaseOpen));
pMembersDatabase->SetMember("Close", LUA_FUNC(DatabaseClose));
pMembersDatabase->SetMember("IsOpen", LUA_FUNC(DatabaseIsOpen));
pMembersDatabase->SetMember("SetExtendedErrors", LUA_FUNC(DatabaseExtendedErrors));
pMembersDatabase->SetMember("LastError", LUA_FUNC(DatabaseLastError));
pMembersDatabase->SetMember("LastErrorMessage", LUA_FUNC(DatabaseLastErrorMessage));
pMembersDatabase->SetMember("LastInsertId", LUA_FUNC(DatabaseLastInsertId));
pMembersDatabase->SetMember("Changes", LUA_FUNC(DatabaseChanges));
pMembersDatabase->SetMember("TotalChanges", LUA_FUNC(DatabaseTotalChanges));
pMembersDatabase->SetMember("Execute", LUA_FUNC(DatabaseExecute));
pMembersDatabase->SetMember("Prepare", LUA_FUNC(DatabasePrepare));
// Index
pMetaDatabase->SetMember("__index", pMembersDatabase);
}
SAFE_UNREF(pMembersDatabase);
}
SAFE_UNREF(pMetaDatabase);
// Statement object definition
ILuaObject* pMetaStatement = g_pLua->GetMetaTable(META_STATEMENT, TYPE_STATEMENT);
if( pMetaStatement )
{
// Destructor
pMetaStatement->SetMember("__gc", LUA_FUNC(StatementDelete));
ILuaObject* pMembersStatement = g_pLua->GetNewTable();
if( pMembersStatement )
{
pMembersStatement->SetMember("Finalize", LUA_FUNC(StatementFinalize));
pMembersStatement->SetMember("SQLString", LUA_FUNC(StatementSqlString));
pMembersStatement->SetMember("Fetch", LUA_FUNC(StatementFetch));
pMembersStatement->SetMember("Step", LUA_FUNC(StatementStep));
pMembersStatement->SetMember("Reset", LUA_FUNC(StatementReset));
pMembersStatement->SetMember("ClearBindings", LUA_FUNC(StatementClearBindings));
pMembersStatement->SetMember("ParameterCount", LUA_FUNC(StatementParameterCount));
pMembersStatement->SetMember("GetParameterName", LUA_FUNC(StatementParameterName));
pMembersStatement->SetMember("GetParameterIndex", LUA_FUNC(StatementParameterIndex));
pMembersStatement->SetMember("BindNull", LUA_FUNC(StatementBindNull));
pMembersStatement->SetMember("BindInteger", LUA_FUNC(StatementBindInteger));
pMembersStatement->SetMember("BindFloat", LUA_FUNC(StatementBindFloat));
pMembersStatement->SetMember("BindString", LUA_FUNC(StatementBindString));
pMembersStatement->SetMember("ColumnCount", LUA_FUNC(StatementColumnCount));
pMembersStatement->SetMember("GetColumnName", LUA_FUNC(StatementColumnName));
pMembersStatement->SetMember("GetColumnIndex", LUA_FUNC(StatementColumnIndex));
pMembersStatement->SetMember("GetColumnType", LUA_FUNC(StatementColumnType));
pMembersStatement->SetMember("GetInteger", LUA_FUNC(StatementGetInteger));
pMembersStatement->SetMember("GetFloat", LUA_FUNC(StatementGetFloat));
pMembersStatement->SetMember("GetString", LUA_FUNC(StatementGetString));
// Index
pMetaStatement->SetMember("__index", pMembersStatement);
}
SAFE_UNREF(pMembersStatement);
}
SAFE_UNREF(pMetaStatement);
// Make our global table
g_pLua->NewGlobalTable(GLOBAL_TABLE);
// Add the members
ILuaObject* pObject = g_pLua->GetGlobal(GLOBAL_TABLE);
if( pObject )
{
// Constructor
pObject->SetMember("New", LUA_FUNC(DatabaseNew));
// Misc Functions
pObject->SetMember("IsStatementComplete", LUA_FUNC(MiscIsStatementComplete));
pObject->SetMember("LibVersion", LUA_FUNC(MiscLibVersion));
pObject->SetMember("LibVersionNumber", LUA_FUNC(MiscLibVersionNumber));
pObject->SetMember("SourceId", LUA_FUNC(MiscSourceId));
// Constants
pObject->SetMember( "SQLITE_VERSION", SQLITE_VERSION );
pObject->SetMember( "SQLITE_VERSION_NUMBER", (float)SQLITE_VERSION_NUMBER );
pObject->SetMember( "SQLITE_SOURCE_ID", SQLITE_SOURCE_ID );
pObject->SetMember( "SQLITE_OK", (float)SQLITE_OK );
pObject->SetMember( "SQLITE_ERROR", (float)SQLITE_ERROR );
pObject->SetMember( "SQLITE_INTERNAL", (float)SQLITE_INTERNAL );
pObject->SetMember( "SQLITE_PERM", (float)SQLITE_PERM );
pObject->SetMember( "SQLITE_ABORT", (float)SQLITE_ABORT );
pObject->SetMember( "SQLITE_BUSY", (float)SQLITE_BUSY );
pObject->SetMember( "SQLITE_LOCKED", (float)SQLITE_LOCKED );
pObject->SetMember( "SQLITE_NOMEM", (float)SQLITE_NOMEM );
pObject->SetMember( "SQLITE_READONLY", (float)SQLITE_READONLY );
pObject->SetMember( "SQLITE_INTERRUPT", (float)SQLITE_INTERRUPT );
pObject->SetMember( "SQLITE_IOERR", (float)SQLITE_IOERR );
pObject->SetMember( "SQLITE_CORRUPT", (float)SQLITE_CORRUPT );
pObject->SetMember( "SQLITE_NOTFOUND", (float)SQLITE_NOTFOUND );
pObject->SetMember( "SQLITE_FULL", (float)SQLITE_FULL );
pObject->SetMember( "SQLITE_CANTOPEN", (float)SQLITE_CANTOPEN );
pObject->SetMember( "SQLITE_PROTOCOL", (float)SQLITE_PROTOCOL );
pObject->SetMember( "SQLITE_EMPTY", (float)SQLITE_EMPTY );
pObject->SetMember( "SQLITE_SCHEMA", (float)SQLITE_SCHEMA );
pObject->SetMember( "SQLITE_TOOBIG", (float)SQLITE_TOOBIG );
pObject->SetMember( "SQLITE_CONSTRAINT", (float)SQLITE_CONSTRAINT );
pObject->SetMember( "SQLITE_MISMATCH", (float)SQLITE_MISMATCH );
pObject->SetMember( "SQLITE_MISUSE", (float)SQLITE_MISUSE );
pObject->SetMember( "SQLITE_NOLFS", (float)SQLITE_NOLFS );
pObject->SetMember( "SQLITE_AUTH", (float)SQLITE_AUTH );
pObject->SetMember( "SQLITE_FORMAT", (float)SQLITE_FORMAT );
pObject->SetMember( "SQLITE_RANGE", (float)SQLITE_RANGE );
pObject->SetMember( "SQLITE_NOTADB", (float)SQLITE_NOTADB );
pObject->SetMember( "SQLITE_ROW", (float)SQLITE_ROW );
pObject->SetMember( "SQLITE_DONE", (float)SQLITE_DONE );
pObject->SetMember( "SQLITE_INTEGER", (float)SQLITE_INTEGER );
pObject->SetMember( "SQLITE_FLOAT", (float)SQLITE_FLOAT );
pObject->SetMember( "SQLITE_BLOB", (float)SQLITE_BLOB );
pObject->SetMember( "SQLITE_NULL", (float)SQLITE_NULL );
pObject->SetMember( "SQLITE3_TEXT", (float)SQLITE3_TEXT );
pObject->SetMember( "SQLITE_ACCESS_EXISTS", (float)SQLITE_ACCESS_EXISTS );
pObject->SetMember( "SQLITE_ACCESS_READWRITE", (float)SQLITE_ACCESS_READWRITE );
pObject->SetMember( "SQLITE_ACCESS_READ", (float)SQLITE_ACCESS_READ );
pObject->SetMember( "SQLITE_CREATE_INDEX", (float)SQLITE_CREATE_INDEX );
pObject->SetMember( "SQLITE_CREATE_TABLE", (float)SQLITE_CREATE_TABLE );
pObject->SetMember( "SQLITE_CREATE_TEMP_INDEX", (float)SQLITE_CREATE_TEMP_INDEX );
pObject->SetMember( "SQLITE_CREATE_TEMP_TABLE", (float)SQLITE_CREATE_TEMP_TABLE );
pObject->SetMember( "SQLITE_CREATE_TEMP_TRIGGER", (float)SQLITE_CREATE_TEMP_TRIGGER );
pObject->SetMember( "SQLITE_CREATE_TEMP_VIEW", (float)SQLITE_CREATE_TEMP_VIEW );
pObject->SetMember( "SQLITE_CREATE_TRIGGER", (float)SQLITE_CREATE_TRIGGER );
pObject->SetMember( "SQLITE_CREATE_VIEW", (float)SQLITE_CREATE_VIEW );
pObject->SetMember( "SQLITE_DELETE", (float)SQLITE_DELETE );
pObject->SetMember( "SQLITE_DROP_INDEX", (float)SQLITE_DROP_INDEX );
pObject->SetMember( "SQLITE_DROP_TABLE", (float)SQLITE_DROP_TABLE );
pObject->SetMember( "SQLITE_DROP_TEMP_INDEX", (float)SQLITE_DROP_TEMP_INDEX );
pObject->SetMember( "SQLITE_DROP_TEMP_TABLE", (float)SQLITE_DROP_TEMP_TABLE );
pObject->SetMember( "SQLITE_DROP_TEMP_TRIGGER", (float)SQLITE_DROP_TEMP_TRIGGER );
pObject->SetMember( "SQLITE_DROP_TEMP_VIEW", (float)SQLITE_DROP_TEMP_VIEW );
pObject->SetMember( "SQLITE_DROP_TRIGGER", (float)SQLITE_DROP_TRIGGER );
pObject->SetMember( "SQLITE_DROP_VIEW", (float)SQLITE_DROP_VIEW );
pObject->SetMember( "SQLITE_INSERT", (float)SQLITE_INSERT );
pObject->SetMember( "SQLITE_PRAGMA", (float)SQLITE_PRAGMA );
pObject->SetMember( "SQLITE_READ", (float)SQLITE_READ );
pObject->SetMember( "SQLITE_SELECT", (float)SQLITE_SELECT );
pObject->SetMember( "SQLITE_TRANSACTION", (float)SQLITE_TRANSACTION );
pObject->SetMember( "SQLITE_UPDATE", (float)SQLITE_UPDATE );
pObject->SetMember( "SQLITE_ATTACH", (float)SQLITE_ATTACH );
pObject->SetMember( "SQLITE_DETACH", (float)SQLITE_DETACH );
pObject->SetMember( "SQLITE_ALTER_TABLE", (float)SQLITE_ALTER_TABLE );
pObject->SetMember( "SQLITE_REINDEX", (float)SQLITE_REINDEX );
pObject->SetMember( "SQLITE_ANALYZE", (float)SQLITE_ANALYZE );
pObject->SetMember( "SQLITE_CREATE_VTABLE", (float)SQLITE_CREATE_VTABLE );
pObject->SetMember( "SQLITE_DROP_VTABLE", (float)SQLITE_DROP_VTABLE );
pObject->SetMember( "SQLITE_FUNCTION", (float)SQLITE_FUNCTION );
pObject->SetMember( "SQLITE_SAVEPOINT", (float)SQLITE_SAVEPOINT );
pObject->SetMember( "SQLITE_COPY", (float)SQLITE_COPY );
pObject->SetMember( "SQLITE_UTF8", (float)SQLITE_UTF8 );
pObject->SetMember( "SQLITE_UTF16LE", (float)SQLITE_UTF16LE );
pObject->SetMember( "SQLITE_UTF16BE", (float)SQLITE_UTF16BE );
pObject->SetMember( "SQLITE_UTF16", (float)SQLITE_UTF16 );
pObject->SetMember( "SQLITE_ANY", (float)SQLITE_ANY );
pObject->SetMember( "SQLITE_UTF16_ALIGNED", (float)SQLITE_UTF16_ALIGNED );
pObject->SetMember( "SQLITE_CONFIG_SINGLETHREAD", (float)SQLITE_CONFIG_SINGLETHREAD );
pObject->SetMember( "SQLITE_CONFIG_MULTITHREAD", (float)SQLITE_CONFIG_MULTITHREAD );
pObject->SetMember( "SQLITE_CONFIG_SERIALIZED", (float)SQLITE_CONFIG_SERIALIZED );
pObject->SetMember( "SQLITE_CONFIG_MALLOC", (float)SQLITE_CONFIG_MALLOC );
pObject->SetMember( "SQLITE_CONFIG_GETMALLOC", (float)SQLITE_CONFIG_GETMALLOC );
pObject->SetMember( "SQLITE_CONFIG_SCRATCH", (float)SQLITE_CONFIG_SCRATCH );
pObject->SetMember( "SQLITE_CONFIG_PAGECACHE", (float)SQLITE_CONFIG_PAGECACHE );
pObject->SetMember( "SQLITE_CONFIG_HEAP", (float)SQLITE_CONFIG_HEAP );
pObject->SetMember( "SQLITE_CONFIG_MEMSTATUS", (float)SQLITE_CONFIG_MEMSTATUS );
pObject->SetMember( "SQLITE_CONFIG_MUTEX", (float)SQLITE_CONFIG_MUTEX );
pObject->SetMember( "SQLITE_CONFIG_GETMUTEX", (float)SQLITE_CONFIG_GETMUTEX );
pObject->SetMember( "SQLITE_CONFIG_LOOKASIDE", (float)SQLITE_CONFIG_LOOKASIDE );
pObject->SetMember( "SQLITE_CONFIG_PCACHE", (float)SQLITE_CONFIG_PCACHE );
pObject->SetMember( "SQLITE_CONFIG_GETPCACHE", (float)SQLITE_CONFIG_GETPCACHE );
pObject->SetMember( "SQLITE_CONFIG_LOG", (float)SQLITE_CONFIG_LOG );
pObject->SetMember( "SQLITE_DBCONFIG_LOOKASIDE", (float)SQLITE_DBCONFIG_LOOKASIDE );
pObject->SetMember( "SQLITE_DBSTATUS_LOOKASIDE_USED", (float)SQLITE_DBSTATUS_LOOKASIDE_USED );
pObject->SetMember( "SQLITE_FCNTL_LOCKSTATE", (float)SQLITE_FCNTL_LOCKSTATE );
pObject->SetMember( "SQLITE_GET_LOCKPROXYFILE", (float)SQLITE_GET_LOCKPROXYFILE );
pObject->SetMember( "SQLITE_SET_LOCKPROXYFILE", (float)SQLITE_SET_LOCKPROXYFILE );
pObject->SetMember( "SQLITE_LAST_ERRNO", (float)SQLITE_LAST_ERRNO );
pObject->SetMember( "SQLITE_DENY", (float)SQLITE_DENY );
pObject->SetMember( "SQLITE_IGNORE", (float)SQLITE_IGNORE );
pObject->SetMember( "SQLITE_INDEX_CONSTRAINT_EQ", (float)SQLITE_INDEX_CONSTRAINT_EQ );
pObject->SetMember( "SQLITE_INDEX_CONSTRAINT_GT", (float)SQLITE_INDEX_CONSTRAINT_GT );
pObject->SetMember( "SQLITE_INDEX_CONSTRAINT_LE", (float)SQLITE_INDEX_CONSTRAINT_LE );
pObject->SetMember( "SQLITE_INDEX_CONSTRAINT_LT", (float)SQLITE_INDEX_CONSTRAINT_LT );
pObject->SetMember( "SQLITE_INDEX_CONSTRAINT_GE", (float)SQLITE_INDEX_CONSTRAINT_GE );
pObject->SetMember( "SQLITE_INDEX_CONSTRAINT_MATCH", (float)SQLITE_INDEX_CONSTRAINT_MATCH );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC", (float)SQLITE_IOCAP_ATOMIC );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC512", (float)SQLITE_IOCAP_ATOMIC512 );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC1K", (float)SQLITE_IOCAP_ATOMIC1K );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC2K", (float)SQLITE_IOCAP_ATOMIC2K );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC4K", (float)SQLITE_IOCAP_ATOMIC4K );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC8K", (float)SQLITE_IOCAP_ATOMIC8K );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC16K", (float)SQLITE_IOCAP_ATOMIC16K );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC32K", (float)SQLITE_IOCAP_ATOMIC32K );
pObject->SetMember( "SQLITE_IOCAP_ATOMIC64K", (float)SQLITE_IOCAP_ATOMIC64K );
pObject->SetMember( "SQLITE_IOCAP_SAFE_APPEND", (float)SQLITE_IOCAP_SAFE_APPEND );
pObject->SetMember( "SQLITE_IOCAP_SEQUENTIAL", (float)SQLITE_IOCAP_SEQUENTIAL );
pObject->SetMember( "SQLITE_IOERR_READ", (float)SQLITE_IOERR_READ );
pObject->SetMember( "SQLITE_IOERR_SHORT_READ", (float)SQLITE_IOERR_SHORT_READ );
pObject->SetMember( "SQLITE_IOERR_WRITE", (float)SQLITE_IOERR_WRITE );
pObject->SetMember( "SQLITE_IOERR_FSYNC", (float)SQLITE_IOERR_FSYNC );
pObject->SetMember( "SQLITE_IOERR_DIR_FSYNC", (float)SQLITE_IOERR_DIR_FSYNC );
pObject->SetMember( "SQLITE_IOERR_TRUNCATE", (float)SQLITE_IOERR_TRUNCATE );
pObject->SetMember( "SQLITE_IOERR_FSTAT", (float)SQLITE_IOERR_FSTAT );
pObject->SetMember( "SQLITE_IOERR_UNLOCK", (float)SQLITE_IOERR_UNLOCK );
pObject->SetMember( "SQLITE_IOERR_RDLOCK", (float)SQLITE_IOERR_RDLOCK );
pObject->SetMember( "SQLITE_IOERR_DELETE", (float)SQLITE_IOERR_DELETE );
pObject->SetMember( "SQLITE_IOERR_BLOCKED", (float)SQLITE_IOERR_BLOCKED );
pObject->SetMember( "SQLITE_IOERR_NOMEM", (float)SQLITE_IOERR_NOMEM );
pObject->SetMember( "SQLITE_IOERR_ACCESS", (float)SQLITE_IOERR_ACCESS );
pObject->SetMember( "SQLITE_IOERR_CHECKRESERVEDLOCK", (float)SQLITE_IOERR_CHECKRESERVEDLOCK );
pObject->SetMember( "SQLITE_IOERR_LOCK", (float)SQLITE_IOERR_LOCK );
pObject->SetMember( "SQLITE_IOERR_CLOSE", (float)SQLITE_IOERR_CLOSE );
pObject->SetMember( "SQLITE_IOERR_DIR_CLOSE", (float)SQLITE_IOERR_DIR_CLOSE );
pObject->SetMember( "SQLITE_LOCKED_SHAREDCACHE", (float)SQLITE_LOCKED_SHAREDCACHE );
pObject->SetMember( "SQLITE_LIMIT_LENGTH", (float)SQLITE_LIMIT_LENGTH );
pObject->SetMember( "SQLITE_LIMIT_SQL_LENGTH", (float)SQLITE_LIMIT_SQL_LENGTH );
pObject->SetMember( "SQLITE_LIMIT_COLUMN", (float)SQLITE_LIMIT_COLUMN );
pObject->SetMember( "SQLITE_LIMIT_EXPR_DEPTH", (float)SQLITE_LIMIT_EXPR_DEPTH );
pObject->SetMember( "SQLITE_LIMIT_COMPOUND_SELECT", (float)SQLITE_LIMIT_COMPOUND_SELECT );
pObject->SetMember( "SQLITE_LIMIT_VDBE_OP", (float)SQLITE_LIMIT_VDBE_OP );
pObject->SetMember( "SQLITE_LIMIT_FUNCTION_ARG", (float)SQLITE_LIMIT_FUNCTION_ARG );
pObject->SetMember( "SQLITE_LIMIT_ATTACHED", (float)SQLITE_LIMIT_ATTACHED );
pObject->SetMember( "SQLITE_LIMIT_LIKE_PATTERN_LENGTH", (float)SQLITE_LIMIT_LIKE_PATTERN_LENGTH );
pObject->SetMember( "SQLITE_LIMIT_VARIABLE_NUMBER", (float)SQLITE_LIMIT_VARIABLE_NUMBER );
pObject->SetMember( "SQLITE_LIMIT_TRIGGER_DEPTH", (float)SQLITE_LIMIT_TRIGGER_DEPTH );
pObject->SetMember( "SQLITE_LOCK_NONE", (float)SQLITE_LOCK_NONE );
pObject->SetMember( "SQLITE_LOCK_SHARED", (float)SQLITE_LOCK_SHARED );
pObject->SetMember( "SQLITE_LOCK_RESERVED", (float)SQLITE_LOCK_RESERVED );
pObject->SetMember( "SQLITE_LOCK_PENDING", (float)SQLITE_LOCK_PENDING );
pObject->SetMember( "SQLITE_LOCK_EXCLUSIVE", (float)SQLITE_LOCK_EXCLUSIVE );
pObject->SetMember( "SQLITE_MUTEX_FAST", (float)SQLITE_MUTEX_FAST );
pObject->SetMember( "SQLITE_MUTEX_RECURSIVE", (float)SQLITE_MUTEX_RECURSIVE );
pObject->SetMember( "SQLITE_MUTEX_STATIC_MASTER", (float)SQLITE_MUTEX_STATIC_MASTER );
pObject->SetMember( "SQLITE_MUTEX_STATIC_MEM", (float)SQLITE_MUTEX_STATIC_MEM );
pObject->SetMember( "SQLITE_MUTEX_STATIC_MEM2", (float)SQLITE_MUTEX_STATIC_MEM2 );
pObject->SetMember( "SQLITE_MUTEX_STATIC_OPEN", (float)SQLITE_MUTEX_STATIC_OPEN );
pObject->SetMember( "SQLITE_MUTEX_STATIC_PRNG", (float)SQLITE_MUTEX_STATIC_PRNG );
pObject->SetMember( "SQLITE_MUTEX_STATIC_LRU", (float)SQLITE_MUTEX_STATIC_LRU );
pObject->SetMember( "SQLITE_MUTEX_STATIC_LRU2", (float)SQLITE_MUTEX_STATIC_LRU2 );
pObject->SetMember( "SQLITE_OPEN_READONLY", (float)SQLITE_OPEN_READONLY );
pObject->SetMember( "SQLITE_OPEN_READWRITE", (float)SQLITE_OPEN_READWRITE );
pObject->SetMember( "SQLITE_OPEN_CREATE", (float)SQLITE_OPEN_CREATE );
pObject->SetMember( "SQLITE_OPEN_DELETEONCLOSE", (float)SQLITE_OPEN_DELETEONCLOSE );
pObject->SetMember( "SQLITE_OPEN_EXCLUSIVE", (float)SQLITE_OPEN_EXCLUSIVE );
pObject->SetMember( "SQLITE_OPEN_AUTOPROXY", (float)SQLITE_OPEN_AUTOPROXY );
pObject->SetMember( "SQLITE_OPEN_MAIN_DB", (float)SQLITE_OPEN_MAIN_DB );
pObject->SetMember( "SQLITE_OPEN_TEMP_DB", (float)SQLITE_OPEN_TEMP_DB );
pObject->SetMember( "SQLITE_OPEN_TRANSIENT_DB", (float)SQLITE_OPEN_TRANSIENT_DB );
pObject->SetMember( "SQLITE_OPEN_MAIN_JOURNAL", (float)SQLITE_OPEN_MAIN_JOURNAL );
pObject->SetMember( "SQLITE_OPEN_TEMP_JOURNAL", (float)SQLITE_OPEN_TEMP_JOURNAL );
pObject->SetMember( "SQLITE_OPEN_SUBJOURNAL", (float)SQLITE_OPEN_SUBJOURNAL );
pObject->SetMember( "SQLITE_OPEN_MASTER_JOURNAL", (float)SQLITE_OPEN_MASTER_JOURNAL );
pObject->SetMember( "SQLITE_OPEN_NOMUTEX", (float)SQLITE_OPEN_NOMUTEX );
pObject->SetMember( "SQLITE_OPEN_FULLMUTEX", (float)SQLITE_OPEN_FULLMUTEX );
pObject->SetMember( "SQLITE_OPEN_SHAREDCACHE", (float)SQLITE_OPEN_SHAREDCACHE );
pObject->SetMember( "SQLITE_OPEN_PRIVATECACHE", (float)SQLITE_OPEN_PRIVATECACHE );
pObject->SetMember( "SQLITE_STATUS_MEMORY_USED", (float)SQLITE_STATUS_MEMORY_USED );
pObject->SetMember( "SQLITE_STATUS_PAGECACHE_USED", (float)SQLITE_STATUS_PAGECACHE_USED );
pObject->SetMember( "SQLITE_STATUS_PAGECACHE_OVERFLOW", (float)SQLITE_STATUS_PAGECACHE_OVERFLOW );
pObject->SetMember( "SQLITE_STATUS_SCRATCH_USED", (float)SQLITE_STATUS_SCRATCH_USED );
pObject->SetMember( "SQLITE_STATUS_SCRATCH_OVERFLOW", (float)SQLITE_STATUS_SCRATCH_OVERFLOW );
pObject->SetMember( "SQLITE_STATUS_MALLOC_SIZE", (float)SQLITE_STATUS_MALLOC_SIZE );
pObject->SetMember( "SQLITE_STATUS_PARSER_STACK", (float)SQLITE_STATUS_PARSER_STACK );
pObject->SetMember( "SQLITE_STATUS_PAGECACHE_SIZE", (float)SQLITE_STATUS_PAGECACHE_SIZE );
pObject->SetMember( "SQLITE_STATUS_SCRATCH_SIZE", (float)SQLITE_STATUS_SCRATCH_SIZE );
pObject->SetMember( "SQLITE_STMTSTATUS_FULLSCAN_STEP", (float)SQLITE_STMTSTATUS_FULLSCAN_STEP );
pObject->SetMember( "SQLITE_STMTSTATUS_SORT", (float)SQLITE_STMTSTATUS_SORT );
pObject->SetMember( "SQLITE_SYNC_NORMAL", (float)SQLITE_SYNC_NORMAL );
pObject->SetMember( "SQLITE_SYNC_FULL", (float)SQLITE_SYNC_FULL );
pObject->SetMember( "SQLITE_SYNC_DATAONLY", (float)SQLITE_SYNC_DATAONLY );
pObject->SetMember( "SQLITE_TESTCTRL_FIRST", (float)SQLITE_TESTCTRL_FIRST );
pObject->SetMember( "SQLITE_TESTCTRL_PRNG_SAVE", (float)SQLITE_TESTCTRL_PRNG_SAVE );
pObject->SetMember( "SQLITE_TESTCTRL_PRNG_RESTORE", (float)SQLITE_TESTCTRL_PRNG_RESTORE );
pObject->SetMember( "SQLITE_TESTCTRL_PRNG_RESET", (float)SQLITE_TESTCTRL_PRNG_RESET );
pObject->SetMember( "SQLITE_TESTCTRL_BITVEC_TEST", (float)SQLITE_TESTCTRL_BITVEC_TEST );
pObject->SetMember( "SQLITE_TESTCTRL_FAULT_INSTALL", (float)SQLITE_TESTCTRL_FAULT_INSTALL );
pObject->SetMember( "SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS", (float)SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS );
pObject->SetMember( "SQLITE_TESTCTRL_PENDING_BYTE", (float)SQLITE_TESTCTRL_PENDING_BYTE );
pObject->SetMember( "SQLITE_TESTCTRL_ASSERT", (float)SQLITE_TESTCTRL_ASSERT );
pObject->SetMember( "SQLITE_TESTCTRL_ALWAYS", (float)SQLITE_TESTCTRL_ALWAYS );
pObject->SetMember( "SQLITE_TESTCTRL_RESERVE", (float)SQLITE_TESTCTRL_RESERVE );
pObject->SetMember( "SQLITE_TESTCTRL_OPTIMIZATIONS", (float)SQLITE_TESTCTRL_OPTIMIZATIONS );
pObject->SetMember( "SQLITE_TESTCTRL_ISKEYWORD", (float)SQLITE_TESTCTRL_ISKEYWORD );
pObject->SetMember( "SQLITE_TESTCTRL_LAST", (float)SQLITE_TESTCTRL_LAST );
}
SAFE_UNREF(pObject);
return 0;
}
//-----------------------------------------------------------------------------
// Called when the DLL is being unloaded.
//-----------------------------------------------------------------------------
int Shutdown(lua_State* L)
{
sqlite3_shutdown();
return 0;
}
//-----------------------------------------------------------------------------
// Module initialization
//-----------------------------------------------------------------------------
GMOD_MODULE( Init, Shutdown );
| lgpl-2.1 |
yeyaowei/New-Menu | src/main/java/com/rhwteam/yeyaowei/NewMenu/Utils/InternetUtil.java | 1580 | package com.rhwteam.yeyaowei.NewMenu.Utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.rhwteam.yeyaowei.NewMenu.ConfigVar;
public class InternetUtil {
public static String LoadText(String strURL)
{
if(ConfigVar.onlinecheck)
{
try {
return getNetContent(strURL);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
return null;
}
public static String getNetContent(String url) throws IOException {
URL u = new URL(url);
return getStreamContent(u.openStream());
}
public static String getStreamContent(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String c = "", line;
while((line = reader.readLine()) != null)
c += "\n" + line;
return c.substring(1);
}
public static void writeToStream(OutputStream os, String content) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(os);
writer.write(content);
writer.flush(); writer.close();
}
public static String post(String url, String content) throws IOException {
URL u = new URL(url);
URLConnection c = u.openConnection();
c.setDoOutput(true);
writeToStream(c.getOutputStream(), content);
return getStreamContent(c.getInputStream());
}
}
| lgpl-2.1 |
jozilla/Cassowary.net | Cassowary/Tests/LayoutTest.cs | 35766 | /*
Cassowary.net: an incremental constraint solver for .NET
(http://lumumba.uhasselt.be/jo/projects/cassowary.net/)
Copyright (C) 2005-2006 Jo Vermeulen (jo.vermeulen@uhasselt.be)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation; either version 2.1
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
namespace Cassowary.Tests
{
public class LayoutTest
{
public static void Main(string[] args)
{
_solver = new ClSimplexSolver();
// initialize the needed variables
BuildVariables();
// create the constraints
try
{
BuildConstraints();
}
catch (ExClRequiredFailure rf)
{
Console.Error.WriteLine(rf.StackTrace);
}
catch (ExClInternalError ie)
{
Console.Error.WriteLine(ie.StackTrace);
}
// solve it
try
{
_solver.Solve();
}
catch (ExClInternalError ie)
{
Console.Error.WriteLine(ie.StackTrace);
}
// print out the values
Console.WriteLine("Variables: ");
PrintVariables();
}
protected static void BuildVariables()
{
////////////////////////////////////////////////////////////////
// Individual widgets //
////////////////////////////////////////////////////////////////
update_top = new ClVariable("update.top", 0);
update_bottom = new ClVariable("update.bottom", 23);
update_left = new ClVariable("update.left", 0);
update_right = new ClVariable("update.right", 75);
update_height = new ClVariable("update.height", 23);
update_width = new ClVariable("update.width", 75);
newpost_top = new ClVariable("newpost.top", 0);
newpost_bottom = new ClVariable("newpost.bottom", 23);
newpost_left = new ClVariable("newpost.left", 0);
newpost_right = new ClVariable("newpost.right", 75);
newpost_width = new ClVariable("newpost.width", 75);
newpost_height = new ClVariable("newpost.height", 23);
quit_bottom = new ClVariable("quit.bottom", 23);
quit_right = new ClVariable("quit.right", 75);
quit_height = new ClVariable("quit.height", 23);
quit_width = new ClVariable("quit.width", 75);
quit_left = new ClVariable("quit.left", 0);
quit_top = new ClVariable("quit.top", 0);
l_title_top = new ClVariable("l_title.top", 0);
l_title_bottom = new ClVariable("l_title.bottom", 23);
l_title_left = new ClVariable("l_title.left", 0);
l_title_right = new ClVariable("l_title.right", 100);
l_title_height = new ClVariable("l_title.height", 23);
l_title_width = new ClVariable("l_title.width", 100);
title_top = new ClVariable("title.top", 0);
title_bottom = new ClVariable("title.bottom", 20);
title_left = new ClVariable("title.left.", 0);
title_right = new ClVariable("title.right", 100);
title_height = new ClVariable("title.height", 20);
title_width = new ClVariable("title.width", 100);
l_body_top = new ClVariable("l_body.top", 0);
l_body_bottom = new ClVariable("l_body.bottom", 23);
l_body_left = new ClVariable("l_body.left", 0);
l_body_right = new ClVariable("l_body.right", 100);
l_body_height = new ClVariable("l_body.height.", 23);
l_body_width = new ClVariable("l_body.width", 100);
blogentry_top = new ClVariable("blogentry.top", 0);
blogentry_bottom = new ClVariable("blogentry.bottom", 315);
blogentry_left = new ClVariable("blogentry.left", 0);
blogentry_right = new ClVariable("blogentry.right", 400);
blogentry_height = new ClVariable("blogentry.height", 315);
blogentry_width = new ClVariable("blogentry.width", 400);
l_recent_top = new ClVariable("l_recent.top", 0);
l_recent_bottom = new ClVariable("l_recent.bottom", 23);
l_recent_left = new ClVariable("l_recent.left", 0);
l_recent_right = new ClVariable("l_recent.right", 100);
l_recent_height = new ClVariable("l_recent.height", 23);
l_recent_width = new ClVariable("l_recent.width", 100);
articles_top = new ClVariable("articles.top", 0);
articles_bottom = new ClVariable("articles.bottom", 415);
articles_left = new ClVariable("articles.left", 0);
articles_right = new ClVariable("articles.right", 180);
articles_height = new ClVariable("articles.height", 415);
articles_width = new ClVariable("articles.width", 100);
////////////////////////////////////////////////////////////////
// Container widgets //
////////////////////////////////////////////////////////////////
topRight_top = new ClVariable("topRight.top", 0);
//topRight_top = new ClVariable("topRight.top", 0);
topRight_bottom = new ClVariable("topRight.bottom", 100);
//topRight_bottom = new ClVariable("topRight.bottom", 100);
topRight_left = new ClVariable("topRight.left", 0);
//topRight_left = new ClVariable("topRight.left", 0);
topRight_right = new ClVariable("topRight.right", 200);
//topRight_right = new ClVariable("topRight.right", 200);
topRight_height = new ClVariable("topRight.height", 100);
//topRight_height = new ClVariable("topRight.height", 100);
topRight_width = new ClVariable("topRight.width", 200);
//topRight_width = new ClVariable("topRight.width", 200);
//topRight_width = new ClVariable("topRight.width", 200);
bottomRight_top = new ClVariable("bottomRight.top", 0);
//bottomRight_top = new ClVariable("bottomRight.top", 0);
bottomRight_bottom = new ClVariable("bottomRight.bottom", 100);
//bottomRight_bottom = new ClVariable("bottomRight.bottom", 100);
bottomRight_left = new ClVariable("bottomRight.left", 0);
//bottomRight_left = new ClVariable("bottomRight.left", 0);
bottomRight_right = new ClVariable("bottomRight.right", 200);
//bottomRight_right = new ClVariable("bottomRight.right", 200);
bottomRight_height = new ClVariable("bottomRight.height", 100);
//bottomRight_height = new ClVariable("bottomRight.height", 100);
bottomRight_width = new ClVariable("bottomRight.width", 200);
//bottomRight_width = new ClVariable("bottomRight.width", 200);
right_top = new ClVariable("right.top", 0);
//right_top = new ClVariable("right.top", 0);
right_bottom = new ClVariable("right.bottom", 100);
//right_bottom = new ClVariable("right.bottom", 100);
//right_bottom = new ClVariable("right.bottom", 100);
right_left = new ClVariable("right.left", 0);
//right_left = new ClVariable("right.left", 0);
right_right = new ClVariable("right.right", 200);
//right_right = new ClVariable("right.right", 200);
right_height = new ClVariable("right.height", 100);
//right_height = new ClVariable("right.height", 100);
right_width = new ClVariable("right.width", 200);
//right_width = new ClVariable("right.width", 200);
//right_width = new ClVariable("right.width", 200);
left_top = new ClVariable("left.top", 0);
//left_top = new ClVariable("left.top", 0);
left_bottom = new ClVariable("left.bottom", 100);
//left_bottom = new ClVariable("left.bottom", 100);
left_left = new ClVariable("left.left", 0);
//left_left = new ClVariable("left.left", 0);
left_right = new ClVariable("left.right", 200);
//left_right = new ClVariable("left.right", 200);
left_height = new ClVariable("left.height", 100);
//left_height = new ClVariable("left.height", 100);
left_width = new ClVariable("left.width", 200);
//left_width = new ClVariable("left.width", 200);
fr_top = new ClVariable("fr.top", 0);
fr_bottom = new ClVariable("fr.bottom", 100);
fr_left = new ClVariable("fr.left", 0);
fr_right = new ClVariable("fr.right", 200);
fr_height = new ClVariable("fr.height", 100);
fr_width = new ClVariable("fr.width", 200);
}
protected static void BuildConstraints()
{
BuildStayConstraints();
BuildRequiredConstraints();
BuildStrongConstraints();
}
protected static void BuildStayConstraints()
{
_solver.AddStay(update_height);
_solver.AddStay(update_width);
_solver.AddStay(newpost_height);
_solver.AddStay(newpost_width);
_solver.AddStay(quit_height);
_solver.AddStay(quit_width);
_solver.AddStay(l_title_height);
_solver.AddStay(l_title_width);
_solver.AddStay(title_height);
_solver.AddStay(title_width);
_solver.AddStay(l_body_height);
_solver.AddStay(l_body_width);
_solver.AddStay(blogentry_height);
// let's keep blogentry.width in favor of other stay constraints!
// remember we later specify title.width to be equal to blogentry.width
_solver.AddStay(blogentry_width, ClStrength.Strong);
_solver.AddStay(l_recent_height);
_solver.AddStay(l_recent_width);
_solver.AddStay(articles_height);
_solver.AddStay(articles_width);
}
protected static void BuildRequiredConstraints() {
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(bottomRight_height), bottomRight_top), new ClLinearExpression(bottomRight_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(bottomRight_width), bottomRight_left), new ClLinearExpression(bottomRight_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(bottomRight_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(bottomRight_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(bottomRight_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(bottomRight_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(update_height), update_top), new ClLinearExpression(update_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(update_width), update_left), new ClLinearExpression(update_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(update_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(update_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(update_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(update_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(update_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(update_bottom, Cl.LEQ, bottomRight_height));
_solver.AddConstraint(new ClLinearInequality(update_right, Cl.LEQ, bottomRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(newpost_height), newpost_top), new ClLinearExpression(newpost_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(newpost_width), newpost_left), new ClLinearExpression(newpost_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(newpost_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(newpost_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(newpost_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(newpost_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(newpost_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(newpost_bottom, Cl.LEQ, bottomRight_height));
_solver.AddConstraint(new ClLinearInequality(newpost_right, Cl.LEQ, bottomRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(quit_height), quit_top), new ClLinearExpression(quit_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(quit_width), quit_left), new ClLinearExpression(quit_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(quit_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(quit_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(quit_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(quit_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(quit_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(quit_bottom, Cl.LEQ, bottomRight_height));
_solver.AddConstraint(new ClLinearInequality(quit_right, Cl.LEQ, bottomRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(topRight_height), topRight_top), new ClLinearExpression(topRight_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(topRight_width), topRight_left), new ClLinearExpression(topRight_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(topRight_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(topRight_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(topRight_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(topRight_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(topRight_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(l_title_height), l_title_top), new ClLinearExpression(l_title_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(l_title_width), l_title_left), new ClLinearExpression(l_title_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_title_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_title_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_title_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_title_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_title_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_title_bottom, Cl.LEQ, topRight_height));
_solver.AddConstraint(new ClLinearInequality(l_title_right, Cl.LEQ, topRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(title_height), title_top), new ClLinearExpression(title_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(title_width), title_left), new ClLinearExpression(title_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(title_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(title_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(title_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(title_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(title_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(title_bottom, Cl.LEQ, topRight_height));
_solver.AddConstraint(new ClLinearInequality(title_right, Cl.LEQ, topRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(l_body_height), l_body_top), new ClLinearExpression(l_body_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(l_body_width), l_body_left), new ClLinearExpression(l_body_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_body_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_body_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_body_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_body_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_body_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_body_bottom, Cl.LEQ, topRight_height));
_solver.AddConstraint(new ClLinearInequality(l_body_right, Cl.LEQ, topRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(blogentry_height), blogentry_top), new ClLinearExpression(blogentry_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(blogentry_width), blogentry_left), new ClLinearExpression(blogentry_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(blogentry_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(blogentry_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(blogentry_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(blogentry_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(blogentry_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(blogentry_bottom, Cl.LEQ, topRight_height));
_solver.AddConstraint(new ClLinearInequality(blogentry_right, Cl.LEQ, topRight_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(left_height), left_top), new ClLinearExpression(left_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(left_width), left_left), new ClLinearExpression(left_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(l_recent_height), l_recent_top), new ClLinearExpression(l_recent_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(l_recent_width), l_recent_left), new ClLinearExpression(l_recent_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_recent_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_recent_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_recent_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_recent_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_recent_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(l_recent_bottom, Cl.LEQ, left_height));
_solver.AddConstraint(new ClLinearInequality(l_recent_right, Cl.LEQ, left_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(articles_height), articles_top), new ClLinearExpression(articles_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(articles_width), articles_left), new ClLinearExpression(articles_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(articles_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(articles_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(articles_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(articles_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(articles_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(articles_bottom, Cl.LEQ, left_height));
_solver.AddConstraint(new ClLinearInequality(articles_right, Cl.LEQ, left_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(left_height), left_top), new ClLinearExpression(left_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(left_width), left_left), new ClLinearExpression(left_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(right_height), right_top), new ClLinearExpression(right_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(right_width), right_left), new ClLinearExpression(right_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(right_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(right_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(right_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(right_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(right_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(topRight_bottom, Cl.LEQ, right_height));
_solver.AddConstraint(new ClLinearInequality(topRight_right, Cl.LEQ, right_width));
_solver.AddConstraint(new ClLinearInequality(bottomRight_bottom, Cl.LEQ, right_height));
_solver.AddConstraint(new ClLinearInequality(bottomRight_right, Cl.LEQ, right_width));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(fr_height), fr_top), new ClLinearExpression(fr_bottom), ClStrength.Required));
_solver.AddConstraint(new ClLinearEquation(Cl.Plus(new ClLinearExpression(fr_width), fr_left), new ClLinearExpression(fr_right), ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(fr_top, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(fr_bottom, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(fr_left, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(fr_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(fr_right, Cl.GEQ, 0, ClStrength.Required));
_solver.AddConstraint(new ClLinearInequality(left_bottom, Cl.LEQ, fr_height));
_solver.AddConstraint(new ClLinearInequality(left_right, Cl.LEQ, fr_width));
_solver.AddConstraint(new ClLinearInequality(right_bottom, Cl.LEQ, fr_height));
_solver.AddConstraint(new ClLinearInequality(right_right, Cl.LEQ, fr_width));
}
protected static void BuildStrongConstraints()
{
_solver.AddConstraint(new ClLinearInequality(update_right, Cl.LEQ, newpost_left, ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(newpost_right, Cl.LEQ, quit_left, ClStrength.Strong));
//_solver.AddConstraint(new ClLinearEquation(bottomRight_width, new ClLinearExpression(topRight_width), ClStrength.Strong));
//_solver.AddConstraint(new ClLinearEquation(right_width, new ClLinearExpression(topRight_width), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(bottomRight_bottom, new ClLinearExpression(right_bottom), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(newpost_height, new ClLinearExpression(update_height), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(newpost_width, new ClLinearExpression(update_width), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(update_height, new ClLinearExpression(quit_height), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(quit_width, new ClLinearExpression(update_width), ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(l_title_bottom, Cl.LEQ, title_top, ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(title_bottom, Cl.LEQ, l_body_top, ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(l_body_bottom, Cl.LEQ, blogentry_top, ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(title_width, new ClLinearExpression(blogentry_width), ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(l_recent_bottom, Cl.LEQ, articles_top, ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(topRight_bottom, Cl.LEQ, bottomRight_top, ClStrength.Strong));
_solver.AddConstraint(new ClLinearInequality(left_right, Cl.LEQ, right_left, ClStrength.Strong));
//_solver.AddConstraint(new ClLinearEquation(left_height, new ClLinearExpression(right_height), ClStrength.Strong));
//_solver.AddConstraint(new ClLinearEquation(fr_height, new ClLinearExpression(right_height), ClStrength.Strong));
// alignment
_solver.AddConstraint(new ClLinearEquation(l_title_left, new ClLinearExpression(title_left), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(title_left, new ClLinearExpression(blogentry_left), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(l_body_left, new ClLinearExpression(blogentry_left), ClStrength.Strong));
_solver.AddConstraint(new ClLinearEquation(l_recent_left, new ClLinearExpression(articles_left), ClStrength.Strong));
}
protected static void PrintVariables()
{
Console.WriteLine(update_top);
Console.WriteLine(update_bottom);
Console.WriteLine(update_left);
Console.WriteLine(update_right);
Console.WriteLine(update_height);
Console.WriteLine(update_width);
Console.WriteLine(newpost_top);
Console.WriteLine(newpost_bottom);
Console.WriteLine(newpost_left);
Console.WriteLine(newpost_right);
Console.WriteLine(newpost_height);
Console.WriteLine(newpost_width);
Console.WriteLine(quit_top);
Console.WriteLine(quit_bottom);
Console.WriteLine(quit_left);
Console.WriteLine(quit_right);
Console.WriteLine(quit_height);
Console.WriteLine(quit_width);
Console.WriteLine(l_title_top);
Console.WriteLine(l_title_bottom);
Console.WriteLine(l_title_left);
Console.WriteLine(l_title_right);
Console.WriteLine(l_title_height);
Console.WriteLine(l_title_width);
Console.WriteLine(title_top);
Console.WriteLine(title_bottom);
Console.WriteLine(title_left);
Console.WriteLine(title_right);
Console.WriteLine(title_height);
Console.WriteLine(title_width);
Console.WriteLine(l_body_top);
Console.WriteLine(l_body_bottom);
Console.WriteLine(l_body_left);
Console.WriteLine(l_body_right);
Console.WriteLine(l_body_height);
Console.WriteLine(l_body_width);
Console.WriteLine(blogentry_top);
Console.WriteLine(blogentry_bottom);
Console.WriteLine(blogentry_left);
Console.WriteLine(blogentry_right);
Console.WriteLine(blogentry_height);
Console.WriteLine(blogentry_width);
Console.WriteLine(l_recent_top);
Console.WriteLine(l_recent_bottom);
Console.WriteLine(l_recent_left);
Console.WriteLine(l_recent_right);
Console.WriteLine(l_recent_height);
Console.WriteLine(l_recent_width);
Console.WriteLine(articles_top);
Console.WriteLine(articles_bottom);
Console.WriteLine(articles_left);
Console.WriteLine(articles_right);
Console.WriteLine(articles_height);
Console.WriteLine(articles_width);
Console.WriteLine(topRight_top);
Console.WriteLine(topRight_bottom);
Console.WriteLine(topRight_left);
Console.WriteLine(topRight_right);
Console.WriteLine(topRight_height);
Console.WriteLine(topRight_width);
Console.WriteLine(bottomRight_top);
Console.WriteLine(bottomRight_bottom);
Console.WriteLine(bottomRight_left);
Console.WriteLine(bottomRight_right);
Console.WriteLine(bottomRight_height);
Console.WriteLine(bottomRight_width);
Console.WriteLine(right_top);
Console.WriteLine(right_bottom);
Console.WriteLine(right_left);
Console.WriteLine(right_right);
Console.WriteLine(right_height);
Console.WriteLine(right_width);
Console.WriteLine(left_top);
Console.WriteLine(left_bottom);
Console.WriteLine(left_left);
Console.WriteLine(left_right);
Console.WriteLine(left_height);
Console.WriteLine(left_width);
Console.WriteLine(fr_top);
Console.WriteLine(fr_bottom);
Console.WriteLine(fr_left);
Console.WriteLine(fr_right);
Console.WriteLine(fr_height);
Console.WriteLine(fr_width);
}
private static ClSimplexSolver _solver;
private static ClVariable update_top;
private static ClVariable update_bottom;
private static ClVariable update_left;
private static ClVariable update_right;
private static ClVariable update_height;
private static ClVariable update_width;
private static ClVariable newpost_top;
private static ClVariable newpost_bottom;
private static ClVariable newpost_left;
private static ClVariable newpost_right;
private static ClVariable newpost_height;
private static ClVariable newpost_width;
private static ClVariable quit_top;
private static ClVariable quit_bottom;
private static ClVariable quit_left;
private static ClVariable quit_right;
private static ClVariable quit_height;
private static ClVariable quit_width;
private static ClVariable l_title_top;
private static ClVariable l_title_bottom;
private static ClVariable l_title_left;
private static ClVariable l_title_right;
private static ClVariable l_title_height;
private static ClVariable l_title_width;
private static ClVariable title_top;
private static ClVariable title_bottom;
private static ClVariable title_left;
private static ClVariable title_right;
private static ClVariable title_height;
private static ClVariable title_width;
private static ClVariable l_body_top;
private static ClVariable l_body_bottom;
private static ClVariable l_body_left;
private static ClVariable l_body_right;
private static ClVariable l_body_height;
private static ClVariable l_body_width;
private static ClVariable blogentry_top;
private static ClVariable blogentry_bottom;
private static ClVariable blogentry_left;
private static ClVariable blogentry_right;
private static ClVariable blogentry_height;
private static ClVariable blogentry_width;
private static ClVariable l_recent_top;
private static ClVariable l_recent_bottom;
private static ClVariable l_recent_left;
private static ClVariable l_recent_right;
private static ClVariable l_recent_height;
private static ClVariable l_recent_width;
private static ClVariable articles_top;
private static ClVariable articles_bottom;
private static ClVariable articles_left;
private static ClVariable articles_right;
private static ClVariable articles_height;
private static ClVariable articles_width;
////////////////////////////////////////////////////////////////
// Container widgets //
////////////////////////////////////////////////////////////////
private static ClVariable topRight_top;
private static ClVariable topRight_bottom;
private static ClVariable topRight_left;
private static ClVariable topRight_right;
private static ClVariable topRight_height;
private static ClVariable topRight_width;
private static ClVariable bottomRight_top;
private static ClVariable bottomRight_bottom;
private static ClVariable bottomRight_left;
private static ClVariable bottomRight_right;
private static ClVariable bottomRight_height;
private static ClVariable bottomRight_width;
private static ClVariable right_top;
private static ClVariable right_bottom;
private static ClVariable right_left;
private static ClVariable right_right;
private static ClVariable right_height;
private static ClVariable right_width;
private static ClVariable left_top;
private static ClVariable left_bottom;
private static ClVariable left_left;
private static ClVariable left_right;
private static ClVariable left_height;
private static ClVariable left_width;
private static ClVariable fr_top;
private static ClVariable fr_bottom;
private static ClVariable fr_left;
private static ClVariable fr_right;
private static ClVariable fr_height;
private static ClVariable fr_width;
}
}
| lgpl-2.1 |
jzuijlek/Lucee | core/src/main/java/lucee/commons/lang/types/RefIntegerSync.java | 2106 | /**
*
* Copyright (c) 2016, Lucee Assosication Switzerland
* Copyright (c) 2014, the Railo Company Ltd. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
**/
package lucee.commons.lang.types;
/**
* Integer Type that can be modified
*/
public class RefIntegerSync implements RefInteger {
private int value;
/**
* @param value
*/
public RefIntegerSync(int value) {
this.value = value;
}
public RefIntegerSync() {}
/**
* @param value
*/
@Override
public synchronized void setValue(int value) {
this.value = value;
}
/**
* operation plus
*
* @param value
*/
@Override
public synchronized void plus(int value) {
this.value += value;
}
/**
* operation minus
*
* @param value
*/
@Override
public synchronized void minus(int value) {
this.value -= value;
}
/**
* @return returns value as integer
*/
@Override
public synchronized Integer toInteger() {
return Integer.valueOf(value);
}
/**
* @return returns value as integer
*/
@Override
public synchronized Double toDouble() {
return new Double(value);
}
@Override
public synchronized double toDoubleValue() {
return value;
}
@Override
public synchronized int toInt() {
return value;
}
@Override
public synchronized String toString() {
return String.valueOf(value);
}
} | lgpl-2.1 |
bittercoder/reportingcloud | src/ReportingCloud.Designer/PropertyVisibility.cs | 5600 | /*
·--------------------------------------------------------------------·
| ReportingCloud - Designer |
| Copyright (c) 2010, FlexibleCoder. |
| https://sourceforge.net/projects/reportingcloud |
·--------------------------------------------------------------------·
| This library is free software; you can redistribute it and/or |
| modify it under the terms of the GNU Lesser General Public |
| License as published by the Free Software Foundation; either |
| version 2.1 of the License, or (at your option) any later version. |
| |
| This library is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| Lesser General Public License for more details. |
| |
| GNU LGPL: http://www.gnu.org/copyleft/lesser.html |
·--------------------------------------------------------------------·
*/
using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.ComponentModel; // need this for the properties metadata
using System.Drawing.Design;
using System.Xml;
using System.Globalization;
using System.Windows.Forms;
using System.Windows.Forms.Design;
namespace ReportingCloud.Designer
{
/// <summary>
/// PropertyAction -
/// </summary>
[TypeConverter(typeof(PropertyVisibilityConverter)),
Editor(typeof(PropertyVisibilityUIEditor), typeof(System.Drawing.Design.UITypeEditor))]
internal class PropertyVisibility:IReportItem
{
PropertyReportItem pri;
internal PropertyVisibility(PropertyReportItem ri)
{
pri = ri;
}
public override string ToString()
{
string result = "";
DesignXmlDraw dr = pri.Draw;
XmlNode visNode = dr.GetNamedChildNode(pri.Node, "Visibility");
if (visNode != null)
{
XmlNode hNode = dr.GetNamedChildNode(pri.Node, "Visibility");
XmlNode vNode = dr.GetNamedChildNode(hNode, "Hidden");
if (vNode != null)
result = string.Format("Hidden: {0}", vNode.InnerText);
}
return result;
}
#region IReportItem Members
public PropertyReportItem GetPRI()
{
return this.pri;
}
#endregion
}
internal class PropertyVisibilityConverter : StringConverter
{
public override bool GetStandardValuesExclusive(ITypeDescriptorContext context)
{
return false;
}
public override bool CanConvertTo(ITypeDescriptorContext context,
System.Type destinationType)
{
if (destinationType == typeof(PropertyVisibility))
return true;
return base.CanConvertTo(context, destinationType);
}
public override object ConvertTo(ITypeDescriptorContext context,
CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string) && value is PropertyVisibility)
{
PropertyVisibility pv = value as PropertyVisibility;
return pv.ToString();
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
internal class PropertyVisibilityUIEditor : UITypeEditor
{
internal PropertyVisibilityUIEditor()
{
}
public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
{
return UITypeEditorEditStyle.Modal;
}
public override object EditValue(ITypeDescriptorContext context,
IServiceProvider provider,
object value)
{
if ((context == null) || (provider == null))
return base.EditValue(context, provider, value);
// Access the Property Browser's UI display service
IWindowsFormsEditorService editorService =
(IWindowsFormsEditorService)provider.GetService(typeof(IWindowsFormsEditorService));
if (editorService == null)
return base.EditValue(context, provider, value);
// Create an instance of the UI editor form
IReportItem iri = context.Instance as IReportItem;
if (iri == null)
return base.EditValue(context, provider, value);
PropertyReportItem pre = iri.GetPRI();
PropertyVisibility pv = value as PropertyVisibility;
if (pv == null)
return base.EditValue(context, provider, value);
using (SingleCtlDialog scd = new SingleCtlDialog(pre.DesignCtl, pre.Draw, pre.Nodes, SingleCtlTypeEnum.VisibilityCtl, null))
{
// Display the UI editor dialog
if (editorService.ShowDialog(scd) == DialogResult.OK)
{
// Return the new property value from the UI editor form
return new PropertyAction(pre);
}
return base.EditValue(context, provider, value);
}
}
}
} | lgpl-2.1 |
Telekinesis/Telepathy-qt4-0.8.0 | TelepathyQt4/manager-file.cpp | 20921 | /**
* This file is part of TelepathyQt4
*
* @copyright Copyright (C) 2008-2010 Collabora Ltd. <http://www.collabora.co.uk/>
* @copyright Copyright (C) 2008-2010 Nokia Corporation
* @license LGPL 2.1
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <TelepathyQt4/ManagerFile>
#include "TelepathyQt4/debug-internal.h"
#include <TelepathyQt4/Constants>
#include <TelepathyQt4/KeyFile>
#include <QtCore/QDir>
#include <QtCore/QHash>
#include <QtCore/QString>
#include <QtCore/QStringList>
#include <QtDBus/QDBusVariant>
namespace Tp
{
struct TELEPATHY_QT4_NO_EXPORT ManagerFile::Private
{
Private();
Private(const QString &cnName);
void init();
bool parse(const QString &fileName);
bool isValid() const;
bool hasParameter(const QString &protocol, const QString ¶mName) const;
ParamSpec *getParameter(const QString &protocol, const QString ¶mName);
QStringList protocols() const;
ParamSpecList parameters(const QString &protocol) const;
QVariant valueForKey(const QString ¶m, const QString &dbusSignature);
struct ProtocolInfo
{
ProtocolInfo() {}
ProtocolInfo(const ParamSpecList ¶ms, const PresenceSpecList &statuses)
: params(params),
statuses(statuses)
{
}
ParamSpecList params;
QString vcardField;
QString englishName;
QString iconName;
RequestableChannelClassList rccs;
PresenceSpecList statuses;
AvatarSpec avatarRequirements;
};
QString cmName;
KeyFile keyFile;
QHash<QString, ProtocolInfo> protocolsMap;
bool valid;
};
ManagerFile::Private::Private()
: valid(false)
{
}
ManagerFile::Private::Private(const QString &cmName)
: cmName(cmName),
valid(false)
{
init();
}
void ManagerFile::Private::init()
{
// TODO: should we cache the configDirs anywhere?
QStringList configDirs;
QString xdgDataHome = QString::fromLocal8Bit(qgetenv("XDG_DATA_HOME"));
if (xdgDataHome.isEmpty()) {
configDirs << QDir::homePath() + QLatin1String("/.local/share/data/telepathy/managers/");
}
else {
configDirs << xdgDataHome + QLatin1String("/telepathy/managers/");
}
QString xdgDataDirsEnv = QString::fromLocal8Bit(qgetenv("XDG_DATA_DIRS"));
if (xdgDataDirsEnv.isEmpty()) {
configDirs << QLatin1String("/usr/local/share/telepathy/managers/");
configDirs << QLatin1String("/usr/share/telepathy/managers/");
}
else {
QStringList xdgDataDirs = xdgDataDirsEnv.split(QLatin1Char(':'));
foreach (const QString xdgDataDir, xdgDataDirs) {
configDirs << xdgDataDir + QLatin1String("/telepathy/managers/");
}
}
foreach (const QString configDir, configDirs) {
QString fileName = configDir + cmName + QLatin1String(".manager");
if (QFile::exists(fileName)) {
debug() << "parsing manager file" << fileName;
protocolsMap.clear();
if (!parse(fileName)) {
warning() << "error parsing manager file" << fileName;
continue;
}
valid = true;
return;
}
}
}
bool ManagerFile::Private::parse(const QString &fileName)
{
keyFile.setFileName(fileName);
if (keyFile.status() != KeyFile::NoError) {
return false;
}
/* read supported protocols and parameters */
QString protocol;
QStringList groups = keyFile.allGroups();
foreach (const QString group, groups) {
if (group.startsWith(QLatin1String("Protocol "))) {
protocol = group.right(group.length() - 9);
keyFile.setGroup(group);
ParamSpecList paramSpecList;
SimpleStatusSpecMap statuses;
QString param;
QStringList params = keyFile.keys();
foreach (param, params) {
ParamSpec spec;
SimpleStatusSpec status;
spec.flags = 0;
QStringList values = keyFile.value(param).split(QLatin1String(" "));
if (param.startsWith(QLatin1String("param-"))) {
spec.name = param.right(param.length() - 6);
if (values.length() == 0) {
warning() << "param" << spec.name << "set but no signature defined";
return false;
}
if (spec.name.endsWith(QLatin1String("password"))) {
spec.flags |= ConnMgrParamFlagSecret;
}
spec.signature = values[0];
if (values.contains(QLatin1String("secret"))) {
spec.flags |= ConnMgrParamFlagSecret;
}
if (values.contains(QLatin1String("dbus-property"))) {
spec.flags |= ConnMgrParamFlagDBusProperty;
}
if (values.contains(QLatin1String("required"))) {
spec.flags |= ConnMgrParamFlagRequired;
}
if (values.contains(QLatin1String("register"))) {
spec.flags |= ConnMgrParamFlagRegister;
}
paramSpecList.append(spec);
} else if (param.startsWith(QLatin1String("status-"))) {
QString statusName = param.right(param.length() - 7);
if (values.length() == 0) {
warning() << "status" << statusName << "set but no type defined";
return false;
}
bool ok;
status.type = values[0].toUInt(&ok);
if (!ok) {
warning() << "status" << statusName << "set but type is not an uint";
return false;
}
if (values.contains(QLatin1String("settable"))) {
status.maySetOnSelf = true;
} else {
status.maySetOnSelf = false;
}
if (values.contains(QLatin1String("message"))) {
status.canHaveMessage = true;
} else {
status.canHaveMessage = false;
}
if (statuses.contains(statusName)) {
warning() << "status" << statusName << "defined more than once, "
"replacing it";
}
statuses.insert(statusName, status);
}
}
protocolsMap.insert(protocol, ProtocolInfo(paramSpecList, PresenceSpecList(statuses)));
/* now that we have all param-* created, let's find their default values */
foreach (param, params) {
if (param.startsWith(QLatin1String("default-"))) {
QString paramName = param.right(param.length() - 8);
if (!hasParameter(protocol, paramName)) {
warning() << "param" << paramName
<< "has default value set, but not a definition";
continue;
}
ParamSpec *spec = getParameter(protocol, paramName);
spec->flags |= ConnMgrParamFlagHasDefault;
/* map based on the param dbus signature, otherwise use
* QString */
QVariant value = valueForKey(param, spec->signature);
if (value.type() == QVariant::Invalid) {
warning() << "param" << paramName
<< "has invalid signature";
protocolsMap.clear();
return false;
}
spec->defaultValue = QDBusVariant(value);
}
}
ProtocolInfo &info = protocolsMap[protocol];
info.vcardField = keyFile.value(QLatin1String("VCardField"));
info.englishName = keyFile.value(QLatin1String("EnglishName"));
if (info.englishName.isEmpty()) {
QStringList words = protocol.split(QLatin1Char('-'));
for (int i = 0; i < words.size(); ++i) {
words[i][0] = words[i].at(0).toUpper();
}
info.englishName = words.join(QLatin1String(" "));
}
info.iconName = keyFile.value(QLatin1String("Icon"));
if (info.iconName.isEmpty()) {
info.iconName = QString(QLatin1String("im-%1")).arg(protocol);
}
QStringList supportedMimeTypes = keyFile.valueAsStringList(
QLatin1String("SupportedAvatarMIMETypes"));
uint minHeight = keyFile.value(QLatin1String("MinimumAvatarHeight")).toUInt();
uint maxHeight = keyFile.value(QLatin1String("MaximumAvatarHeight")).toUInt();
uint recommendedHeight = keyFile.value(
QLatin1String("RecommendedAvatarHeight")).toUInt();
uint minWidth = keyFile.value(QLatin1String("MinimumAvatarWidth")).toUInt();
uint maxWidth = keyFile.value(QLatin1String("MaximumAvatarWidth")).toUInt();
uint recommendedWidth = keyFile.value(
QLatin1String("RecommendedAvatarWidth")).toUInt();
uint maxBytes = keyFile.value(QLatin1String("MaximumAvatarBytes")).toUInt();
info.avatarRequirements = AvatarSpec(supportedMimeTypes,
minHeight, maxHeight, recommendedHeight,
minWidth, maxWidth, recommendedWidth,
maxBytes);
QStringList rccGroups = keyFile.valueAsStringList(
QLatin1String("RequestableChannelClasses"));
RequestableChannelClass rcc;
foreach (const QString &rccGroup, rccGroups) {
keyFile.setGroup(rccGroup);
foreach (const QString &key, keyFile.keys()) {
int spaceIdx = key.indexOf(QLatin1String(" "));
if (spaceIdx == -1) {
continue;
}
QString propertyName = key.mid(0, spaceIdx);
QString signature = key.mid(spaceIdx + 1);
QString param = keyFile.value(key);
QVariant value = valueForKey(key, signature);
rcc.fixedProperties.insert(propertyName, value);
}
rcc.allowedProperties = keyFile.valueAsStringList(
QLatin1String("allowed"));
info.rccs.append(rcc);
rcc.fixedProperties.clear();
rcc.allowedProperties.clear();
}
}
}
return true;
}
bool ManagerFile::Private::isValid() const
{
return ((keyFile.status() == KeyFile::NoError) && (valid));
}
bool ManagerFile::Private::hasParameter(const QString &protocol,
const QString ¶mName) const
{
ParamSpecList paramSpecList = protocolsMap[protocol].params;
foreach (const ParamSpec ¶mSpec, paramSpecList) {
if (paramSpec.name == paramName) {
return true;
}
}
return false;
}
ParamSpec *ManagerFile::Private::getParameter(const QString &protocol,
const QString ¶mName)
{
ParamSpecList ¶mSpecList = protocolsMap[protocol].params;
for (int i = 0; i < paramSpecList.size(); ++i) {
ParamSpec ¶mSpec = paramSpecList[i];
if (paramSpec.name == paramName) {
return ¶mSpec;
}
}
return NULL;
}
QStringList ManagerFile::Private::protocols() const
{
return protocolsMap.keys();
}
ParamSpecList ManagerFile::Private::parameters(const QString &protocol) const
{
return protocolsMap.value(protocol).params;
}
QVariant ManagerFile::Private::valueForKey(const QString ¶m,
const QString &dbusSignature)
{
QString value = keyFile.rawValue(param);
return parseValueWithDBusSignature(value, dbusSignature);
}
/**
* \class ManagerFile
* \ingroup utils
* \headerfile TelepathyQt4/manager-file.h <TelepathyQt4/ManagerFile>
*
* \brief The ManagerFile class provides an easy way to read Telepathy manager
* files according to the \telepathy_spec.
*
* \todo Consider making this private, because the ConnectionManager and Account classes provide a
* nice view to the data parsed by this class anyway (fd.o #41655).
*/
/**
* Create a ManagerFile object used to read .manager compliant files.
*/
ManagerFile::ManagerFile()
: mPriv(new Private())
{
}
/**
* Create a ManagerFile object used to read .manager compliant files.
*
* \param cmName Name of the connection manager to read the file for.
*/
ManagerFile::ManagerFile(const QString &cmName)
: mPriv(new Private(cmName))
{
}
/**
* Create a ManagerFile object used to read .manager compliant files.
*/
ManagerFile::ManagerFile(const ManagerFile &other)
: mPriv(new Private())
{
mPriv->cmName = other.mPriv->cmName;
mPriv->keyFile = other.mPriv->keyFile;
mPriv->protocolsMap = other.mPriv->protocolsMap;
mPriv->valid = other.mPriv->valid;
}
/**
* Class destructor.
*/
ManagerFile::~ManagerFile()
{
delete mPriv;
}
ManagerFile &ManagerFile::operator=(const ManagerFile &other)
{
mPriv->cmName = other.mPriv->cmName;
mPriv->keyFile = other.mPriv->keyFile;
mPriv->protocolsMap = other.mPriv->protocolsMap;
mPriv->valid = other.mPriv->valid;
return *this;
}
/**
* Check whether or not a ManagerFile object is valid. If the file for the
* specified connection manager cannot be found it will be considered invalid.
*
* \return true if valid, false otherwise.
*/
bool ManagerFile::isValid() const
{
return mPriv->isValid();
}
/**
* Return a list of all protocols defined in the manager file.
*
* \return List of all protocols defined in the file.
*/
QStringList ManagerFile::protocols() const
{
return mPriv->protocols();
}
/**
* Return a list of parameters for the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return List of ParamSpec of a specific protocol defined in the file, or an
* empty list if the protocol is not defined.
*/
ParamSpecList ManagerFile::parameters(const QString &protocol) const
{
return mPriv->parameters(protocol);
}
/**
* Return the name of the most common vCard field used for the given \a protocol's
* contact identifiers, normalized to lower case.
*
* \param protocol Name of the protocol to look for.
* \return The most common vCard field used for the given protocol's contact
* identifiers, or an empty string if there is no such field or the
* protocol is not defined.
*/
QString ManagerFile::vcardField(const QString &protocol) const
{
return mPriv->protocolsMap.value(protocol).vcardField;
}
/**
* Return the English-language name of the given \a protocol, such as "AIM" or "Yahoo!".
*
* The name can be used as a fallback if an application doesn't have a localized name for the
* protocol.
*
* If the manager file doesn't specify the english name, it is inferred from the protocol name, such
* that for example "google-talk" becomes "Google Talk", but "local-xmpp" becomes "Local Xmpp".
*
* \param protocol Name of the protocol to look for.
* \return An English-language name for the given \a protocol.
*/
QString ManagerFile::englishName(const QString &protocol) const
{
return mPriv->protocolsMap.value(protocol).englishName;
}
/**
* Return the name of an icon for the given \a protocol in the system's icon
* theme, such as "im-msn".
*
* If the manager file doesn't specify the icon name, "im-<protocolname>" is assumed.
*
* \param protocol Name of the protocol to look for.
* \return The likely name of an icon for the given \a protocol.
*/
QString ManagerFile::iconName(const QString &protocol) const
{
return mPriv->protocolsMap.value(protocol).iconName;
}
/**
* Return a list of channel classes which might be requestable from a connection
* to the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return A list of channel classes which might be requestable from a
* connection to the given \a protocol or a default constructed
* RequestableChannelClassList instance if the protocol is not defined.
*/
RequestableChannelClassList ManagerFile::requestableChannelClasses(
const QString &protocol) const
{
return mPriv->protocolsMap.value(protocol).rccs;
}
/**
* Return a list of PresenceSpec representing the possible presence statuses
* from a connection to the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return A list of PresenceSpec representing the possible presence statuses
* from a connection to the given \a protocol or an empty list
* if the protocol is not defined.
*/
PresenceSpecList ManagerFile::allowedPresenceStatuses(const QString &protocol) const
{
return mPriv->protocolsMap.value(protocol).statuses;
}
/**
* Return the requirements (size limits, supported MIME types, etc)
* for avatars used on the given \a protocol.
*
* \param protocol Name of the protocol to look for.
* \return The requirements for avatars used on the given \a protocol or an invalid
* AvatarSpec if the protocol is not defined.
*/
AvatarSpec ManagerFile::avatarRequirements(const QString &protocol) const
{
return mPriv->protocolsMap.value(protocol).avatarRequirements;
}
QVariant::Type ManagerFile::variantTypeFromDBusSignature(const QString &signature)
{
QVariant::Type type;
if (signature == QLatin1String("b")) {
type = QVariant::Bool;
} else if (signature == QLatin1String("n") || signature == QLatin1String("i")) {
type = QVariant::Int;
} else if (signature == QLatin1String("q") || signature == QLatin1String("u")) {
type = QVariant::UInt;
} else if (signature == QLatin1String("x")) {
type = QVariant::LongLong;
} else if (signature == QLatin1String("t")) {
type = QVariant::ULongLong;
} else if (signature == QLatin1String("d")) {
type = QVariant::Double;
} else if (signature == QLatin1String("as")) {
type = QVariant::StringList;
} else if (signature == QLatin1String("s") || signature == QLatin1String("o")) {
type = QVariant::String;
} else {
type = QVariant::Invalid;
}
return type;
}
QVariant ManagerFile::parseValueWithDBusSignature(const QString &value,
const QString &dbusSignature)
{
QVariant::Type type = variantTypeFromDBusSignature(dbusSignature);
if (type == QVariant::Invalid) {
return QVariant(type);
}
switch (type) {
case QVariant::Bool:
{
if (value.toLower() == QLatin1String("true") ||
value == QLatin1String("1")) {
return QVariant(true);
} else {
return QVariant(false);
}
break;
}
case QVariant::Int:
return QVariant(value.toInt());
case QVariant::UInt:
return QVariant(value.toUInt());
case QVariant::LongLong:
return QVariant(value.toLongLong());
case QVariant::ULongLong:
return QVariant(value.toULongLong());
case QVariant::Double:
return QVariant(value.toDouble());
case QVariant::StringList:
{
QStringList list;
QByteArray rawValue = value.toAscii();
if (KeyFile::unescapeStringList(rawValue, 0, rawValue.size(), list)) {
return QVariant(list);
} else {
return QVariant(QVariant::Invalid);
}
}
default:
break;
}
return QVariant(value);
}
} // Tp
| lgpl-2.1 |
cejug/yougi | java/src/main/java/org/cejug/yougi/web/controller/CityMBean.java | 4114 | /* Yougi is a web application conceived to manage user groups or
* communities focused on a certain domain of knowledge, whose members are
* constantly sharing information and participating in social and educational
* events. Copyright (C) 2011 Hildeberto Mendonça.
*
* This application is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This application is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* There is a full copy of the GNU Lesser General Public License along with
* this library. Look for the file license.txt at the root level. If you do not
* find it, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA.
* */
package org.cejug.yougi.web.controller;
import org.cejug.yougi.business.CityBean;
import org.cejug.yougi.business.TimezoneBean;
import org.cejug.yougi.business.UserAccountBean;
import org.cejug.yougi.entity.*;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import java.io.Serializable;
import java.util.List;
/**
* @author Hildeberto Mendonca - http://www.hildeberto.com
*/
@ManagedBean
@RequestScoped
public class CityMBean implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
private CityBean cityBean;
@EJB
private TimezoneBean timezoneBean;
@EJB
private UserAccountBean userAccountBean;
@ManagedProperty(value = "#{param.id}")
private String id;
@ManagedProperty(value="#{locationMBean}")
private LocationMBean locationMBean;
private City city;
private List<City> cities;
private List<Timezone> timezones;
public CityMBean() {
this.city = new City();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public LocationMBean getLocationMBean() {
return locationMBean;
}
public void setLocationMBean(LocationMBean locationMBean) {
this.locationMBean = locationMBean;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public List<City> getCities() {
if(this.cities == null) {
this.cities = cityBean.findAll();
}
return this.cities;
}
public List<UserAccount> getInhabitants() {
return userAccountBean.findInhabitantsFrom(this.city);
}
public List<Timezone> getTimezones() {
if(this.timezones == null) {
this.timezones = timezoneBean.findTimezones();
}
return this.timezones;
}
@PostConstruct
public void load() {
if (this.id != null && !this.id.isEmpty()) {
this.city = cityBean.find(id);
locationMBean.initialize();
if (this.city.getCountry() != null) {
locationMBean.setSelectedCountry(this.city.getCountry().getAcronym());
}
if (this.city.getProvince() != null) {
locationMBean.setSelectedProvince(this.city.getProvince().getId());
}
}
}
public String save() {
Country country = this.locationMBean.getCountry();
if (country != null) {
this.city.setCountry(country);
}
Province province = this.locationMBean.getProvince();
if (province != null) {
this.city.setProvince(province);
}
cityBean.save(this.city);
return "cities?faces-redirect=true";
}
public String remove() {
cityBean.remove(city.getId());
return "cities?faces-redirect=true";
}
} | lgpl-2.1 |
bitrepository/reference | bitrepository-client/src/main/java/org/bitrepository/access/getchecksums/conversation/ChecksumsCompletePillarEvent.java | 3182 | /*
* #%L
* Bitrepository Access
*
* $Id$
* $HeadURL$
* %%
* Copyright (C) 2010 - 2011 The State and University Library, The Royal Library and The State Archives, Denmark
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
package org.bitrepository.access.getchecksums.conversation;
import org.bitrepository.bitrepositoryelements.ChecksumSpecTYPE;
import org.bitrepository.bitrepositoryelements.ResultingChecksums;
import org.bitrepository.client.eventhandler.ContributorCompleteEvent;
/**
* Contains the result of a checksum request sent to a single pillar.
*/
public class ChecksumsCompletePillarEvent extends ContributorCompleteEvent {
/** @see #getChecksums(). */
private final ResultingChecksums result;
/** @see #getChecksumType(). */
private final ChecksumSpecTYPE checksumType;
/** Whether this complete event only contains a partail result set.*/
private final boolean isPartialResult;
/**
* @param pillarID The pillar which generated the result
* @param collectionID The ID of the collection
* @param result The result returned by the pillar.
* @param checksumType The checksum specification type.
* @param isPartialResult Whether the complete event contains only a partial results set.
*/
public ChecksumsCompletePillarEvent(String pillarID, String collectionID, ResultingChecksums result,
ChecksumSpecTYPE checksumType, boolean isPartialResult) {
super(pillarID, collectionID);
this.result = result;
this.checksumType = checksumType;
this.isPartialResult = isPartialResult;
}
/**
* @return The checksum result from a single pillar.
*/
public ResultingChecksums getChecksums() {
return result;
}
/**
* @return The checksum calculation specifics (e.g. the algorithm and optionally salt).
*/
public ChecksumSpecTYPE getChecksumType() {
return checksumType;
}
/**
* @return Whether it is a partial result set.
*/
public boolean isPartialResult() {
return isPartialResult;
}
@Override
public String additionalInfo() {
StringBuilder infoSB = new StringBuilder(super.additionalInfo());
if (result != null && result.getChecksumDataItems() != null) {
infoSB.append(", NumberOfChecksums=" +
result.getChecksumDataItems().size());
}
infoSB.append(", PartialResult=" + isPartialResult);
return infoSB.toString();
}
}
| lgpl-2.1 |
davidedmundson/telepathy-hangups | telepathy/server/channel.py | 17733 | # telepathy-python - Base classes defining the interfaces of the Telepathy framework
#
# Copyright (C) 2005, 2006 Collabora Limited
# Copyright (C) 2005, 2006 Nokia Corporation
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
import dbus
import dbus.service
from telepathy.constants import (CONNECTION_HANDLE_TYPE_NONE,
CHANNEL_TEXT_MESSAGE_TYPE_NORMAL,
HANDLE_TYPE_NONE)
from telepathy.errors import InvalidArgument, NotImplemented
from telepathy.interfaces import (CHANNEL_INTERFACE,
CHANNEL_INTERFACE_CONFERENCE,
CHANNEL_INTERFACE_DTMF,
CHANNEL_INTERFACE_GROUP,
CHANNEL_INTERFACE_HOLD,
CHANNEL_INTERFACE_PASSWORD,
CHANNEL_TYPE_CONTACT_LIST,
CHANNEL_TYPE_FILE_TRANSFER,
CHANNEL_TYPE_ROOM_LIST,
CHANNEL_TYPE_STREAMED_MEDIA,
CHANNEL_TYPE_TEXT,
MEDIA_SESSION_HANDLER,
MEDIA_STREAM_HANDLER)
from telepathy._generated.Channel import Channel as _Channel
from telepathy.server.properties import DBusProperties
from telepathy.server.handle import NoneHandle
class Channel(_Channel, DBusProperties):
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the base channel object.
Parameters:
connection - the parent Connection object
props - initial channel properties
"""
self._conn = connection
self._chan_manager = manager
object_path = self._conn.get_channel_path(object_path)
_Channel.__init__(self, self._conn._name, object_path)
self._type = props[CHANNEL_INTERFACE + '.ChannelType']
self._requested = props[CHANNEL_INTERFACE + '.Requested']
tht = props.get(CHANNEL_INTERFACE + '.TargetHandleType', HANDLE_TYPE_NONE)
if tht == HANDLE_TYPE_NONE:
self._handle = NoneHandle()
else:
self._handle = self._conn.handle(
props[CHANNEL_INTERFACE + '.TargetHandleType'],
props[CHANNEL_INTERFACE + '.TargetHandle'])
self._interfaces = set()
DBusProperties.__init__(self)
self._implement_property_get(CHANNEL_INTERFACE,
{'ChannelType': lambda: dbus.String(self.GetChannelType()),
'Interfaces': lambda: dbus.Array(self.GetInterfaces(), signature='s'),
'TargetHandle': lambda: dbus.UInt32(self._handle.get_id()),
'TargetHandleType': lambda: dbus.UInt32(self._handle.get_type()),
'TargetID': lambda: dbus.String(self._handle.get_name()),
'Requested': lambda: self._requested})
self._add_immutable_properties({
'ChannelType': CHANNEL_INTERFACE,
'TargetHandle': CHANNEL_INTERFACE,
'Interfaces': CHANNEL_INTERFACE,
'TargetHandleType': CHANNEL_INTERFACE,
'TargetID': CHANNEL_INTERFACE,
'Requested': CHANNEL_INTERFACE
})
def _add_immutables(self, props):
#backward compatibility
self._add_immutable_properties(props)
@dbus.service.method(CHANNEL_INTERFACE, in_signature='', out_signature='')
def Close(self):
self.Closed()
# Do all these separately in case one works but another doesn't.
try:
self._chan_manager.remove_channel(self)
except:
pass
try:
self._conn.remove_channel(self)
except:
pass
try:
self.remove_from_connection()
except:
pass
@dbus.service.method(CHANNEL_INTERFACE, in_signature='', out_signature='s')
def GetChannelType(self):
""" Returns the interface name for the type of this channel. """
return self._type
@dbus.service.method(CHANNEL_INTERFACE, in_signature='', out_signature='uu')
def GetHandle(self):
""" Returns the handle type and number if this channel represents a
communication with a particular contact, room or server-stored list, or
zero if it is transient and defined only by its contents. """
return (self._handle.get_type(), self._handle.get_id())
@dbus.service.method(CHANNEL_INTERFACE, in_signature='', out_signature='as')
def GetInterfaces(self):
"""
Get the optional interfaces implemented by the channel.
Returns:
an array of the D-Bus interface names
"""
return self._interfaces
from telepathy._generated.Channel_Type_Contact_List \
import ChannelTypeContactList as _ChannelTypeContactListIface
class ChannelTypeContactList(Channel, _ChannelTypeContactListIface):
__doc__ = _ChannelTypeContactListIface.__doc__
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the channel.
Parameters:
connection - the parent Telepathy Connection object
"""
Channel.__init__(self, connection, manager, props,
object_path=object_path)
def Close(self):
raise NotImplemented("Contact lists can't be closed")
from telepathy._generated.Channel_Type_File_Transfer \
import ChannelTypeFileTransfer as _ChannelTypeFileTransferIface
class ChannelTypeFileTransfer(Channel, _ChannelTypeFileTransferIface):
__doc__ = _ChannelTypeFileTransferIface.__doc__
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the channel.
Parameters:
connection - the parent Telepathy Connection object
"""
Channel.__init__(self, connection, manager, props,
object_path=object_path)
from telepathy._generated.Channel_Interface_SASL_Authentication \
import ChannelInterfaceSASLAuthentication
from telepathy._generated.Channel_Type_Server_Authentication \
import ChannelTypeServerAuthentication as _ChannelTypeServerAuthenticationIface
class ChannelTypeServerAuthentication(Channel, _ChannelTypeServerAuthenticationIface):
__doc__ = _ChannelTypeServerAuthenticationIface.__doc__
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the channel.
Parameters:
connection - the parent Telepathy Connection object
"""
Channel.__init__(self, connection, manager, props,
object_path=object_path)
from telepathy._generated.Channel_Type_Streamed_Media \
import ChannelTypeStreamedMedia as _ChannelTypeStreamedMediaIface
class ChannelTypeStreamedMedia(Channel, _ChannelTypeStreamedMediaIface):
__doc__ = _ChannelTypeStreamedMediaIface.__doc__
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the channel.
Parameters:
connection - the parent Telepathy Connection object
"""
Channel.__init__(self, connection, manager, props,
object_path=object_path)
from telepathy._generated.Channel_Type_Room_List \
import ChannelTypeRoomList as _ChannelTypeRoomListIface
class ChannelTypeRoomList(Channel, _ChannelTypeRoomListIface):
__doc__ = _ChannelTypeRoomListIface.__doc__
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the channel.
Parameters:
connection - the parent Telepathy Connection object
"""
Channel.__init__(self, connection, manager, props,
object_path=object_path)
self._listing_rooms = False
self._rooms = {}
self._add_immutable_properties({'Server': CHANNEL_TYPE_ROOM_LIST})
@dbus.service.method(CHANNEL_TYPE_ROOM_LIST, in_signature='', out_signature='b')
def GetListingRooms(self):
return self._listing_rooms
@dbus.service.signal(CHANNEL_TYPE_ROOM_LIST, signature='b')
def ListingRooms(self, listing):
self._listing_rooms = listing
from telepathy._generated.Channel_Type_Text \
import ChannelTypeText as _ChannelTypeTextIface
class ChannelTypeText(Channel, _ChannelTypeTextIface):
__doc__ = _ChannelTypeTextIface.__doc__
def __init__(self, connection, manager, props, object_path=None):
"""
Initialise the channel.
Parameters:
connection - the parent Telepathy Connection object
"""
Channel.__init__(self, connection, manager, props,
object_path=object_path)
self._pending_messages = {}
self._message_types = [CHANNEL_TEXT_MESSAGE_TYPE_NORMAL]
@dbus.service.method(CHANNEL_TYPE_TEXT, in_signature='', out_signature='au')
def GetMessageTypes(self):
"""
Return an array indicating which types of message may be sent on this
channel.
Returns:
an array of integer message types as defined above
"""
return self._message_types
@dbus.service.method(CHANNEL_TYPE_TEXT, in_signature='au', out_signature='')
def AcknowledgePendingMessages(self, ids):
"""
Inform the channel that you have handled messages by displaying them to
the user (or equivalent), so they can be removed from the pending queue.
Parameters:
ids - the message to acknowledge
Possible Errors:
InvalidArgument (a given message ID was not found, no action taken)
"""
for id in ids:
if id not in self._pending_messages:
raise InvalidArgument("the given message ID was not found")
for id in ids:
del self._pending_messages[id]
@dbus.service.method(CHANNEL_TYPE_TEXT, in_signature='b', out_signature='a(uuuuus)')
def ListPendingMessages(self, clear):
"""
List the messages currently in the pending queue, and optionally
remove then all.
Parameters:
clear - a boolean indicating whether the queue should be cleared
Returns:
an array of structs containing:
a numeric identifier
a unix timestamp indicating when the message was received
an integer handle of the contact who sent the message
an integer of the message type
a bitwise OR of the message flags
a string of the text of the message
"""
messages = []
for id in list(self._pending_messages.keys()):
(timestamp, sender, type, flags, text) = self._pending_messages[id]
message = (id, timestamp, sender, type, flags, text)
messages.append(message)
if clear:
del self._pending_messages[id]
messages.sort(cmp=lambda x,y:cmp(x[1], y[1]))
return messages
@dbus.service.signal(CHANNEL_TYPE_TEXT, signature='uuuuus')
def Received(self, id, timestamp, sender, type, flags, text):
if id in self._pending_messages:
raise ValueError("You can't receive the same message twice.")
else:
self._pending_messages[id] = (timestamp, sender, type, flags, text)
from telepathy._generated.Channel_Interface_Chat_State \
import ChannelInterfaceChatState
from telepathy._generated.Channel_Interface_Conference \
import ChannelInterfaceConference as _ChannelInterfaceConference
class ChannelInterfaceConference(_ChannelInterfaceConference):
def __init__(self):
_ChannelInterfaceConference.__init__(self)
self._conference_channels = set()
self._conference_initial_channels = set()
self._conference_initial_invitees = set()
self._conference_invitation_message = ""
self._conference_original_channels = {}
# D-Bus properties for conference interface
self._implement_property_get(CHANNEL_INTERFACE_CONFERENCE, {
'Channels':
lambda: dbus.Array(self._conference_channels, signature='o'),
'InitialChannels':
lambda: dbus.Array(self._conference_initial_channels,
signature='o'),
'InitialInviteeHandles':
lambda: dbus.Array(
[h.get_id() for h in self._conference_initial_invitees],
signature='u'),
'InitialInviteeIDs':
lambda: dbus.Array(
[h.get_name() for h in self._conference_initial_invitees],
signature='s'),
'InvitationMessage':
lambda: dbus.String(self._conference_invitation_message),
'OriginalChannels':
lambda: dbus.Dictionary(self._conference_original_channels,
signature='uo')
})
# Immutable conference properties
self._add_immutable_properties({
'InitialChannels': CHANNEL_INTERFACE_CONFERENCE,
'InitialInviteeIDs': CHANNEL_INTERFACE_CONFERENCE,
'InitialInviteeHandles': CHANNEL_INTERFACE_CONFERENCE,
'InvitationMessage': CHANNEL_INTERFACE_CONFERENCE
})
from telepathy._generated.Channel_Interface_DTMF import ChannelInterfaceDTMF
from telepathy._generated.Channel_Interface_Group \
import ChannelInterfaceGroup as _ChannelInterfaceGroup
class ChannelInterfaceGroup(_ChannelInterfaceGroup):
def __init__(self):
_ChannelInterfaceGroup.__init__(self)
self._implement_property_get(CHANNEL_INTERFACE_GROUP,
{'GroupFlags': lambda: dbus.UInt32(self.GetGroupFlags()),
'Members': lambda: dbus.Array(self.GetMembers(), signature='u'),
'RemotePendingMembers': lambda: dbus.Array(self.GetRemotePendingMembers(), signature='u'),
'SelfHandle': lambda: dbus.UInt32(self.GetSelfHandle())})
self._group_flags = 0
self._members = set()
self._local_pending = set()
self._remote_pending = set()
@dbus.service.method(CHANNEL_INTERFACE_GROUP, in_signature='', out_signature='u')
def GetGroupFlags(self):
return self._group_flags
@dbus.service.signal(CHANNEL_INTERFACE_GROUP, signature='uu')
def GroupFlagsChanged(self, added, removed):
self._group_flags |= added
self._group_flags &= ~removed
@dbus.service.method(CHANNEL_INTERFACE_GROUP, in_signature='', out_signature='au')
def GetMembers(self):
return self._members
@dbus.service.method(CHANNEL_INTERFACE_GROUP, in_signature='', out_signature='u')
def GetSelfHandle(self):
self_handle = self._conn.GetSelfHandle()
if (self_handle in self._members or
self_handle in self._local_pending or
self_handle in self._remote_pending):
return self_handle
else:
return 0
@dbus.service.method(CHANNEL_INTERFACE_GROUP, in_signature='', out_signature='au')
def GetLocalPendingMembers(self):
return self._local_pending
@dbus.service.method(CHANNEL_INTERFACE_GROUP, in_signature='', out_signature='au')
def GetRemotePendingMembers(self):
return self._remote_pending
@dbus.service.method(CHANNEL_INTERFACE_GROUP, in_signature='', out_signature='auauau')
def GetAllMembers(self):
return (self._members, self._local_pending, self._remote_pending)
@dbus.service.signal(CHANNEL_INTERFACE_GROUP, signature='sauauauauuu')
def MembersChanged(self, message, added, removed, local_pending, remote_pending, actor, reason):
self._members.update(added)
self._members.difference_update(removed)
self._local_pending.update(local_pending)
self._local_pending.difference_update(added)
self._local_pending.difference_update(removed)
self._remote_pending.update(remote_pending)
self._remote_pending.difference_update(added)
self._remote_pending.difference_update(removed)
from telepathy._generated.Channel_Interface_Hold import ChannelInterfaceHold
# ChannelInterfaceMediaSignalling is in telepathy.server.media
from telepathy._generated.Channel_Interface_Password \
import ChannelInterfacePassword as _ChannelInterfacePassword
class ChannelInterfacePassword(_ChannelInterfacePassword):
def __init__(self):
_ChannelInterfacePassword.__init__(self)
self._password_flags = 0
self._password = ''
@dbus.service.method(CHANNEL_INTERFACE_PASSWORD, in_signature='', out_signature='u')
def GetPasswordFlags(self):
return self._password_flags
@dbus.service.signal(CHANNEL_INTERFACE_PASSWORD, signature='uu')
def PasswordFlagsChanged(self, added, removed):
self._password_flags |= added
self._password_flags &= ~removed
from telepathy._generated.Channel_Interface_Call_State import ChannelInterfaceCallState
| lgpl-2.1 |
bmwiedemann/video3d | mergepics.py | 1252 | #!/usr/bin/python
# Copyright 2013 Bernhard M. Wiedemann <bernhard+video3d at lsmod de>
# Licensed under GPL-2.0 (see COPYING)
# convert certain 2d video into 3d
import sys
import re
import gd
crop = 18
files = list(sys.argv)
outf = files.pop(0) # drop program name
outf = files.pop(0)
if len(files) == 1: # convenience function to use next file as 2nd input
m = re.match(r"(.*?)(\d+)(\.png)$", files[0])
files.append(m.group(1) + ("%04d" % (int(m.group(2)) + 1)) + m.group(3))
#print files, outf
if len(files) != 2:
print "usage: mergepics.py outimg img1 img2"
exit(1)
sys.stderr.write("processing image " + files[0] + "\n")
imgs = []
for f in files:
img = gd.image(f)
imgs.append(img)
xy = imgs[0].size()
if crop > 0:
img = gd.image((xy[0] - crop, xy[1]), True)
imgs[0].copyTo(img, (0, 0), (0, 0), (xy[0] - crop, xy[1]))
imgs[0] = img
img = gd.image((xy[0] - crop, xy[1]), True)
imgs[1].copyTo(img, (0, 0), (crop, 0), (xy[0] - crop, xy[1]))
imgs[1] = img
xy = imgs[0].size()
for y in range(0, xy[1] - 1):
if y & 1 == 0:
continue # skip even lines
imgs[1].copyTo(imgs[0], (0, y), (0, y), (xy[0], 1))
#copyTo(image[, (dx,dy)[, (sx,sy)[, (w,h)]]])
imgs[0].writePng(outf)
| lgpl-2.1 |
whdc/ieo-beast | src/dr/app/pathogen/TreesPanel.java | 28586 | /*
* PriorsPanel.java
*
* Copyright (C) 2002-2006 Alexei Drummond and Andrew Rambaut
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* BEAST is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.app.pathogen;
import dr.app.gui.chart.*;
import dr.app.gui.util.LongTask;
import dr.evolution.tree.NodeRef;
import dr.evolution.tree.Tree;
import dr.math.MathUtils;
import dr.stats.DiscreteStatistics;
import dr.stats.Regression;
import dr.stats.Variate;
import dr.util.NumberFormatter;
import figtree.panel.FigTreePanel;
import figtree.treeviewer.TreePaneSelector;
import figtree.treeviewer.TreeSelectionListener;
import jam.framework.Exportable;
import jam.table.TableRenderer;
import jebl.evolution.graphs.Node;
import jebl.evolution.taxa.Taxon;
import jebl.evolution.trees.RootedTree;
import javax.swing.*;
import javax.swing.plaf.BorderUIResource;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.PrintWriter;
import java.io.Writer;
import java.text.DecimalFormat;
import java.util.*;
import java.util.List;
/**
* @author Andrew Rambaut
* @author Alexei Drummond
* @version $Id: PriorsPanel.java,v 1.9 2006/09/05 13:29:34 rambaut Exp $
*/
public class TreesPanel extends JPanel implements Exportable {
StatisticsModel statisticsModel;
JTable statisticsTable = null;
private Tree tree = null;
private Tree currentTree = null;
private Tree bestFittingRootTree = null;
private final PathogenFrame frame;
private final JTabbedPane tabbedPane = new JTabbedPane();
private final JTextArea textArea = new JTextArea();
private final JCheckBox showMRCACheck = new JCheckBox("Show ancestor traces");
// JTreeDisplay treePanel;
private final FigTreePanel treePanel;
JChartPanel rootToTipPanel;
JChart rootToTipChart;
ScatterPlot rootToTipPlot;
private static final boolean SHOW_NODE_DENSITY = true;
JChartPanel nodeDensityPanel;
JChart nodeDensityChart;
ScatterPlot nodeDensityPlot;
JChartPanel residualPanel;
JChart residualChart;
ScatterPlot residualPlot;
ParentPlot mrcaPlot;
Map<Node, Integer> pointMap = new HashMap<Node, Integer>();
Set<Integer> selectedPoints = new HashSet<Integer>();
private boolean bestFittingRoot;
private TemporalRooting.RootingFunction rootingFunction;
private TemporalRooting temporalRooting = null;
public TreesPanel(PathogenFrame parent, Tree tree) {
frame = parent;
statisticsModel = new StatisticsModel();
statisticsTable = new JTable(statisticsModel);
statisticsTable.getColumnModel().getColumn(0).setCellRenderer(
new TableRenderer(SwingConstants.RIGHT, new Insets(0, 4, 0, 4)));
statisticsTable.getColumnModel().getColumn(1).setCellRenderer(
new TableRenderer(SwingConstants.LEFT, new Insets(0, 4, 0, 4)));
JScrollPane scrollPane = new JScrollPane(statisticsTable,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
// JToolBar toolBar1 = new JToolBar();
// toolBar1.setFloatable(false);
// toolBar1.setOpaque(false);
// toolBar1.setLayout(new FlowLayout(java.awt.FlowLayout.LEFT, 0, 0));
Box controlPanel1 = new Box(BoxLayout.PAGE_AXIS);
controlPanel1.setOpaque(false);
JPanel panel3 = new JPanel(new BorderLayout(0, 0));
panel3.setOpaque(false);
rootingCheck = new JCheckBox("Best-fitting root");
panel3.add(rootingCheck, BorderLayout.CENTER);
controlPanel1.add(panel3);
final JComboBox rootingFunctionCombo = new JComboBox(TemporalRooting.RootingFunction.values());
/*
JPanel panel4 = new JPanel(new BorderLayout(0,0));
panel4.setOpaque(false);
panel4.add(new JLabel("Function: "), BorderLayout.WEST);
panel4.add(rootingFunctionCombo, BorderLayout.CENTER);
controlPanel1.add(panel4);
*/
JPanel panel1 = new JPanel(new BorderLayout(0, 0));
panel1.setOpaque(false);
panel1.add(scrollPane, BorderLayout.CENTER);
panel1.add(controlPanel1, BorderLayout.NORTH);
treePanel = new FigTreePanel(FigTreePanel.Style.SIMPLE);
tabbedPane.add("Tree", treePanel);
treePanel.getTreeViewer().setSelectionMode(TreePaneSelector.SelectionMode.TAXA);
treePanel.getTreeViewer().addTreeSelectionListener(new TreeSelectionListener() {
public void selectionChanged() {
treeSelectionChanged();
}
});
rootToTipChart = new JChart(new LinearAxis(), new LinearAxis(Axis.AT_ZERO, Axis.AT_MINOR_TICK));
ChartSelector selector1 = new ChartSelector(rootToTipChart);
rootToTipPanel = new JChartPanel(rootToTipChart, "", "time", "divergence");
JPanel panel = new JPanel(new BorderLayout());
panel.add(rootToTipPanel, BorderLayout.CENTER);
panel.add(showMRCACheck, BorderLayout.SOUTH);
panel.setOpaque(false);
tabbedPane.add("Root-to-tip", panel);
residualChart = new JChart(new LinearAxis(), new LinearAxis(Axis.AT_ZERO, Axis.AT_MINOR_TICK));
ChartSelector selector2 = new ChartSelector(residualChart);
residualPanel = new JChartPanel(residualChart, "", "time", "residual");
residualPanel.setOpaque(false);
tabbedPane.add("Residuals", residualPanel);
// textArea.setEditable(false);
JPanel panel2 = new JPanel(new BorderLayout(0, 0));
panel2.setOpaque(false);
panel2.add(tabbedPane, BorderLayout.CENTER);
// panel2.add(textArea, BorderLayout.SOUTH);
if (SHOW_NODE_DENSITY) {
nodeDensityChart = new JChart(new LinearAxis(), new LinearAxis(Axis.AT_ZERO, Axis.AT_MINOR_TICK));
nodeDensityPanel = new JChartPanel(nodeDensityChart, "", "time", "node density");
JPanel panel4 = new JPanel(new BorderLayout());
panel4.add(nodeDensityPanel, BorderLayout.CENTER);
panel4.setOpaque(false);
ChartSelector selector3 = new ChartSelector(nodeDensityChart);
tabbedPane.add("Node density", panel4);
}
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, panel1, panel2);
splitPane.setDividerLocation(220);
splitPane.setContinuousLayout(true);
splitPane.setBorder(BorderFactory.createEmptyBorder());
splitPane.setOpaque(false);
setOpaque(false);
setLayout(new BorderLayout(0, 0));
setBorder(new BorderUIResource.EmptyBorderUIResource(new java.awt.Insets(12, 12, 12, 12)));
add(splitPane, BorderLayout.CENTER);
rootingCheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setBestFittingRoot(rootingCheck.isSelected(), (TemporalRooting.RootingFunction) rootingFunctionCombo.getSelectedItem());
}
});
rootingFunctionCombo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setBestFittingRoot(rootingCheck.isSelected(), (TemporalRooting.RootingFunction) rootingFunctionCombo.getSelectedItem());
}
});
showMRCACheck.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
setupPanel();
}
});
setTree(tree);
}
public List<String> getSelectedTips() {
List<String> tips = new ArrayList<String>();
jebl.evolution.trees.Tree tree = treePanel.getTreeViewer().getTrees().get(0);
for (Node node : treePanel.getTreeViewer().getSelectedTips()) {
tips.add(tree.getTaxon(node).getName());
}
return tips;
}
private void treeSelectionChanged() {
Set<Node> selectedTips = treePanel.getTreeViewer().getSelectedTips();
frame.getCopyAction().setEnabled(selectedTips != null && selectedTips.size() > 0);
selectedPoints = new HashSet<Integer>();
for (Node node : selectedTips) {
selectedPoints.add(pointMap.get(node));
}
if (rootToTipPlot != null) {
rootToTipPlot.setSelectedPoints(selectedPoints);
}
if (residualPlot != null) {
residualPlot.setSelectedPoints(selectedPoints);
}
if (SHOW_NODE_DENSITY && nodeDensityPlot != null) {
nodeDensityPlot.setSelectedPoints(selectedPoints);
}
selectMRCA();
}
private void plotSelectionChanged(final Set<Integer> selectedPoints) {
this.selectedPoints = selectedPoints;
Set<String> selectedTaxa = new HashSet<String>();
for (Integer i : selectedPoints) {
selectedTaxa.add(tree.getTaxon(i).toString());
}
treePanel.getTreeViewer().selectTaxa(selectedTaxa);
selectMRCA();
}
private void selectMRCA() {
if (mrcaPlot == null) return;
if (selectedPoints != null && selectedPoints.size() > 0) {
Set<String> selectedTaxa = new HashSet<String>();
for (Integer i : selectedPoints) {
selectedTaxa.add(tree.getTaxon(i).toString());
}
Regression r = temporalRooting.getRootToTipRegression(currentTree);
NodeRef mrca = Tree.Utils.getCommonAncestorNode(currentTree, selectedTaxa);
double mrcaDistance1 = temporalRooting.getRootToTipDistance(currentTree, mrca);
double mrcaTime1 = r.getX(mrcaDistance1);
if (tree.isExternal(mrca)) {
mrca = tree.getParent(mrca);
}
double mrcaDistance = temporalRooting.getRootToTipDistance(currentTree, mrca);
double mrcaTime = r.getX(mrcaDistance);
mrcaPlot.setSelectedPoints(selectedPoints, mrcaTime, mrcaDistance);
} else {
mrcaPlot.clearSelection();
}
repaint();
}
public void timeScaleChanged() {
bestFittingRootTree = null;
if (rootingCheck.isSelected()) {
rootingCheck.setSelected(false);
} else {
setupPanel();
}
}
public JComponent getExportableComponent() {
return (JComponent) tabbedPane.getSelectedComponent();
}
public void setTree(Tree tree) {
this.tree = tree;
setupPanel();
}
public void setBestFittingRoot(boolean bestFittingRoot, final TemporalRooting.RootingFunction rootingFunction) {
this.bestFittingRoot = bestFittingRoot;
if (this.rootingFunction != rootingFunction) {
bestFittingRootTree = null;
this.rootingFunction = rootingFunction;
}
if (this.bestFittingRoot && bestFittingRootTree == null) {
findRoot();
}
setupPanel();
}
public Tree getTree() {
return tree;
}
public Tree getTreeAsViewed() {
return currentTree;
}
public void writeDataFile(Writer writer) {
PrintWriter pw = new PrintWriter(writer);
String labels[] = temporalRooting.getTipLabels(currentTree);
double yValues[] = temporalRooting.getRootToTipDistances(currentTree);
if (temporalRooting.isContemporaneous()) {
double meanY = DiscreteStatistics.mean(yValues);
pw.println("tip\tdistance\tdeviation");
for (int i = 0; i < yValues.length; i++) {
pw.println(labels[i] + "\t" + "\t" + yValues[i] + "\t" + (yValues[i] - meanY));
}
} else {
double xValues[] = temporalRooting.getTipDates(currentTree);
Regression r = temporalRooting.getRootToTipRegression(currentTree);
double[] residuals = temporalRooting.getRootToTipResiduals(currentTree, r);
pw.println("tip\tdate\tdistance\tresidual");
for (int i = 0; i < xValues.length; i++) {
pw.println(labels[i] + "\t" + xValues[i] + "\t" + yValues[i] + "\t" + residuals[i]);
}
}
}
public void setupPanel() {
StringBuilder sb = new StringBuilder();
NumberFormatter nf = new NumberFormatter(6);
if (tree != null) {
temporalRooting = new TemporalRooting(tree);
currentTree = this.tree;
if (bestFittingRoot && bestFittingRootTree != null) {
currentTree = bestFittingRootTree;
sb.append("Best-fitting root");
} else {
sb.append("User root");
}
if (temporalRooting.isContemporaneous()) {
if (tabbedPane.getSelectedIndex() == 2) {
tabbedPane.setSelectedIndex(1);
}
tabbedPane.setEnabledAt(2, false);
} else {
tabbedPane.setEnabledAt(2, true);
}
RootedTree jtree = Tree.Utils.asJeblTree(currentTree);
if (temporalRooting.isContemporaneous()) {
double[] dv = temporalRooting.getRootToTipDistances(currentTree);
List<Double> values = new ArrayList<Double>();
for (double d : dv) {
values.add(d);
}
rootToTipChart.removeAllPlots();
NumericalDensityPlot dp = new NumericalDensityPlot(values, 20, null);
dp.setLineColor(new Color(9, 70, 15));
double yOffset = (Double) dp.getYData().getMax() / 2;
List<Double> dummyValues = new ArrayList<Double>();
for (int i = 0; i < values.size(); i++) {
// add a random y offset to give some visual spread
double y = MathUtils.nextGaussian() * ((Double) dp.getYData().getMax() * 0.05);
dummyValues.add(yOffset + y);
}
rootToTipPlot = new ScatterPlot(values, dummyValues);
rootToTipPlot.setMarkStyle(Plot.CIRCLE_MARK, 5, new BasicStroke(0.5F), new Color(44, 44, 44), new Color(249, 202, 105));
rootToTipPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
rootToTipPlot.addListener(new Plot.Adaptor() {
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
rootToTipChart.addPlot(rootToTipPlot);
rootToTipChart.addPlot(dp);
rootToTipPanel.setXAxisTitle("root-to-tip divergence");
rootToTipPanel.setYAxisTitle("proportion");
residualChart.removeAllPlots();
sb.append(", contemporaneous tips");
sb.append(", mean root-tip distance: " + nf.format(DiscreteStatistics.mean(dv)));
sb.append(", coefficient of variation: " + nf.format(DiscreteStatistics.stdev(dv) / DiscreteStatistics.mean(dv)));
sb.append(", stdev: " + nf.format(DiscreteStatistics.stdev(dv)));
sb.append(", variance: " + nf.format(DiscreteStatistics.variance(dv)));
showMRCACheck.setVisible(false);
} else {
Regression r = temporalRooting.getRootToTipRegression(currentTree);
double[] residuals = temporalRooting.getRootToTipResiduals(currentTree, r);
pointMap.clear();
for (int i = 0; i < currentTree.getExternalNodeCount(); i++) {
NodeRef tip = currentTree.getExternalNode(i);
Node node = jtree.getNode(Taxon.getTaxon(currentTree.getNodeTaxon(tip).getId()));
node.setAttribute("residual", residuals[i]);
pointMap.put(node, i);
}
rootToTipChart.removeAllPlots();
if (showMRCACheck.isSelected()) {
double[] dv = temporalRooting.getParentRootToTipDistances(currentTree);
List<Double> parentDistances = new ArrayList<Double>();
for (int i = 0; i < dv.length; i++) {
parentDistances.add(i, dv[i]);
}
List<Double> parentTimes = new ArrayList<Double>();
for (int i = 0; i < parentDistances.size(); i++) {
parentTimes.add(i, r.getX(parentDistances.get(i)));
}
mrcaPlot = new ParentPlot(r.getXData(), r.getYData(), parentTimes, parentDistances);
mrcaPlot.setLineColor(new Color(105, 202, 105));
mrcaPlot.setLineStroke(new BasicStroke(0.5F));
rootToTipChart.addPlot(mrcaPlot);
}
rootToTipPlot = new ScatterPlot(r.getXData(), r.getYData());
rootToTipPlot.addListener(new Plot.Adaptor() {
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
rootToTipPlot.setMarkStyle(Plot.CIRCLE_MARK, 5, new BasicStroke(0.5F), new Color(44, 44, 44), new Color(249, 202, 105));
rootToTipPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
rootToTipChart.addPlot(rootToTipPlot);
rootToTipChart.addPlot(new RegressionPlot(r));
rootToTipChart.getXAxis().addRange(r.getXIntercept(), (Double) r.getXData().getMax());
rootToTipPanel.setXAxisTitle("time");
rootToTipPanel.setYAxisTitle("root-to-tip divergence");
residualChart.removeAllPlots();
Variate.D values = (Variate.D) r.getYResidualData();
NumericalDensityPlot dp = new NumericalDensityPlot(values, 20);
dp.setLineColor(new Color(103, 128, 144));
double yOffset = (Double) dp.getYData().getMax() / 2;
Double[] dummyValues = new Double[values.getCount()];
for (int i = 0; i < dummyValues.length; i++) {
// add a random y offset to give some visual spread
double y = MathUtils.nextGaussian() * ((Double) dp.getYData().getMax() * 0.05);
dummyValues[i] = yOffset + y;
}
Variate.D yOffsetValues = new Variate.D(dummyValues);
residualPlot = new ScatterPlot(values, yOffsetValues);
residualPlot.addListener(new Plot.Adaptor() {
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
residualPlot.setMarkStyle(Plot.CIRCLE_MARK, 5, new BasicStroke(0.5F), new Color(44, 44, 44), new Color(249, 202, 105));
residualPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
residualChart.addPlot(residualPlot);
residualChart.addPlot(dp);
residualPanel.setXAxisTitle("residual");
residualPanel.setYAxisTitle("proportion");
// residualChart.removeAllPlots();
// residualPlot = new ScatterPlot(r.getXData(), r.getYResidualData());
// residualPlot.addListener(new Plot.Adaptor() {
// public void selectionChanged(final Set<Integer> selectedPoints) {
// plotSelectionChanged(selectedPoints);
// }
// });
// residualChart.addPlot(residualPlot);
// residualPanel.setXAxisTitle("residual");
// residualPanel.setYAxisTitle("proportion");
if (SHOW_NODE_DENSITY) {
Regression r2 = temporalRooting.getNodeDensityRegression(currentTree);
nodeDensityChart.removeAllPlots();
nodeDensityPlot = new ScatterPlot(r2.getXData(), r2.getYData());
nodeDensityPlot.addListener(new Plot.Adaptor() {
public void selectionChanged(final Set<Integer> selectedPoints) {
plotSelectionChanged(selectedPoints);
}
});
nodeDensityPlot.setMarkStyle(Plot.CIRCLE_MARK, 5, new BasicStroke(0.5F), new Color(44, 44, 44), new Color(249, 202, 105));
nodeDensityPlot.setHilightedMarkStyle(new BasicStroke(0.5F), new Color(44, 44, 44), UIManager.getColor("List.selectionBackground"));
nodeDensityChart.addPlot(nodeDensityPlot);
nodeDensityChart.addPlot(new RegressionPlot(r2));
nodeDensityChart.getXAxis().addRange(r2.getXIntercept(), (Double) r2.getXData().getMax());
nodeDensityPanel.setXAxisTitle("time");
nodeDensityPanel.setYAxisTitle("node density");
}
sb.append(", dated tips");
sb.append(", date range: " + nf.format(temporalRooting.getDateRange()));
sb.append(", slope (rate): " + nf.format(r.getGradient()));
sb.append(", x-intercept (TMRCA): " + nf.format(r.getXIntercept()));
sb.append(", corr. coeff: " + nf.format(r.getCorrelationCoefficient()));
sb.append(", R^2: " + nf.format(r.getRSquared()));
showMRCACheck.setVisible(true);
}
treePanel.setTree(jtree);
treePanel.setColourBy("residual");
} else {
treePanel.setTree(null);
rootToTipChart.removeAllPlots();
sb.append("No trees loaded");
}
textArea.setText(sb.toString());
statisticsModel.fireTableStructureChanged();
repaint();
}
private javax.swing.Timer timer = null;
private void findRoot() {
// bestFittingRootTree = temporalRooting.findRoot(tree);
final FindRootTask analyseTask = new FindRootTask();
final ProgressMonitor progressMonitor = new ProgressMonitor(frame,
"Finding best-fit root",
"", 0, tree.getNodeCount());
progressMonitor.setMillisToPopup(0);
progressMonitor.setMillisToDecideToPopup(0);
timer = new javax.swing.Timer(10, new ActionListener() {
public void actionPerformed(ActionEvent evt) {
progressMonitor.setProgress(analyseTask.getCurrent());
if (progressMonitor.isCanceled() || analyseTask.done()) {
progressMonitor.close();
analyseTask.stop();
timer.stop();
}
}
});
analyseTask.go();
timer.start();
}
class FindRootTask extends LongTask {
public FindRootTask() {
}
public int getCurrent() {
return temporalRooting.getCurrentRootBranch();
}
public int getLengthOfTask() {
return temporalRooting.getTotalRootBranches();
}
public String getDescription() {
return "Calculating demographic reconstruction...";
}
public String getMessage() {
return null;
}
public Object doWork() {
bestFittingRootTree = temporalRooting.findRoot(tree, rootingFunction);
EventQueue.invokeLater(
new Runnable() {
public void run() {
setupPanel();
}
});
return null;
}
}
public TemporalRooting getTemporalRooting() {
return temporalRooting;
}
class StatisticsModel extends AbstractTableModel {
String[] rowNamesDatedTips = {"Date range", "Slope (rate)", "X-Intercept (TMRCA)", "Correlation Coefficient", "R squared", "Residual Mean Squared"};
String[] rowNamesContemporaneousTips = {"Mean root-tip", "Coefficient of variation", "Stdev", "Variance"};
private DecimalFormat formatter = new DecimalFormat("0.####E0");
private DecimalFormat formatter2 = new DecimalFormat("####0.####");
public StatisticsModel() {
}
public int getColumnCount() {
return 2;
}
public int getRowCount() {
if (temporalRooting == null) {
return 0;
} else if (temporalRooting.isContemporaneous()) {
return rowNamesContemporaneousTips.length;
} else {
return rowNamesDatedTips.length;
}
}
public Object getValueAt(int row, int col) {
double value = 0;
if (temporalRooting.isContemporaneous()) {
if (col == 0) {
return rowNamesContemporaneousTips[row];
}
double values[] = temporalRooting.getRootToTipDistances(currentTree);
switch (row) {
case 0:
value = DiscreteStatistics.mean(values);
break;
case 1:
value = DiscreteStatistics.stdev(values) / DiscreteStatistics.mean(values);
break;
case 2:
value = DiscreteStatistics.stdev(values);
break;
case 3:
value = DiscreteStatistics.variance(values);
break;
}
} else {
Regression r = temporalRooting.getRootToTipRegression(currentTree);
if (col == 0) {
return rowNamesDatedTips[row];
}
switch (row) {
case 0:
value = temporalRooting.getDateRange();
break;
case 1:
value = r.getGradient();
break;
case 2:
value = r.getXIntercept();
break;
case 3:
value = r.getCorrelationCoefficient();
break;
case 4:
value = r.getRSquared();
break;
case 5:
value = r.getResidualMeanSquared();
break;
}
}
if (value > 0 && (Math.abs(value) < 0.1 || Math.abs(value) >= 100000.0)) {
return formatter.format(value);
} else return formatter2.format(value);
}
public String getColumnName(int column) {
if (column > 0) {
return "";
}
if (temporalRooting == null) {
return "No tree loaded";
} else if (temporalRooting.isContemporaneous()) {
return "Contemporaneous Tips";
} else {
return "Dated Tips";
}
}
public Class getColumnClass(int c) {
return getValueAt(0, c).getClass();
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(getColumnName(0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getColumnName(j));
}
buffer.append("\n");
for (int i = 0; i < getRowCount(); i++) {
buffer.append(getValueAt(i, 0));
for (int j = 1; j < getColumnCount(); j++) {
buffer.append("\t");
buffer.append(getValueAt(i, j));
}
buffer.append("\n");
}
return buffer.toString();
}
}
private JCheckBox rootingCheck;
}
| lgpl-2.1 |
gurbrinder/Arduino | app/src/cc/arduino/contributions/libraries/ui/DropdownBuiltInLibrariesItem.java | 2059 | /*
* This file is part of Arduino.
*
* Copyright 2015 Arduino LLC (http://www.arduino.cc/)
*
* Arduino is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* As a special exception, you may use this file as part of a free software
* library without restriction. Specifically, if other files instantiate
* templates or use macros or inline functions from this file, or you compile
* this file and link it with other files to produce an executable, this
* file does not by itself cause the resulting executable to be covered by
* the GNU General Public License. This exception does not however
* invalidate any other reasons why the executable file might be covered by
* the GNU General Public License.
*/
package cc.arduino.contributions.libraries.ui;
import cc.arduino.contributions.filters.BuiltInPredicate;
import cc.arduino.contributions.packages.DownloadableContribution;
import cc.arduino.contributions.ui.DropdownItem;
import com.google.common.base.Predicate;
import static processing.app.I18n._;
public class DropdownBuiltInLibrariesItem implements DropdownItem<DownloadableContribution> {
public String toString() {
return _("Built-in");
}
@Override
public Predicate<DownloadableContribution> getFilterPredicate() {
return new BuiltInPredicate();
}
@Override
public boolean equals(Object obj) {
return obj instanceof DropdownBuiltInLibrariesItem;
}
}
| lgpl-2.1 |
kazuyaujihara/NCDK | NCDK/QSAR/Descriptors/Moleculars/HBondAcceptorCountDescriptor.cs | 5949 | /* Copyright (C) 2004-2007 The Chemistry Development Kit (CDK) project
*
* Contact: cdk-devel@lists.sourceforge.net
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2.1
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*/
using NCDK.Aromaticities;
using NCDK.Tools.Manipulator;
namespace NCDK.QSAR.Descriptors.Moleculars
{
/// <summary>
/// This descriptor calculates the number of hydrogen bond acceptors using a slightly simplified version of the
/// <see href="http://www.chemie.uni-erlangen.de/model2001/abstracts/rester.html">PHACIR atom types</see>.
/// </summary>
/// <remarks>
/// The following groups are counted as hydrogen bond acceptors:
/// <list type="bullet">
/// <item>any oxygen where the formal charge of the oxygen is non-positive (i.e. formal charge <= 0) <b>except</b></item>
/// <item>an aromatic ether oxygen (i.e. an ether oxygen that is adjacent to at least one aromatic carbon)</item>
/// <item>an oxygen that is adjacent to a nitrogen</item>
/// <item>any nitrogen where the formal charge of the nitrogen is non-positive (i.e. formal charge <= 0) <b>except</b></item>
/// </list>
/// <para>
/// This descriptor works properly with AtomContainers whose atoms contain <b>implicit hydrogens</b> or <b>explicit
/// hydrogens</b>.
/// </para>
/// </remarks>
// @author ulif
// @cdk.created 2005-22-07
// @cdk.module qsarmolecular
// @cdk.dictref qsar-descriptors:hBondacceptors
[DescriptorSpecification(DescriptorTargets.AtomContainer, "http://www.blueobelisk.org/ontologies/chemoinformatics-algorithms/#hBondacceptors")]
public class HBondAcceptorCountDescriptor : AbstractDescriptor, IMolecularDescriptor
{
private readonly bool checkAromaticity;
public HBondAcceptorCountDescriptor(bool checkAromaticity = false)
{
this.checkAromaticity = checkAromaticity;
}
[DescriptorResult]
public class Result : AbstractDescriptorResult
{
public Result(int value)
{
this.NumberOfHBondAcceptor = value;
}
[DescriptorResultProperty("nHBAcc")]
public int NumberOfHBondAcceptor { get; private set; }
public int Value => NumberOfHBondAcceptor;
}
/// <summary>
/// Calculates the number of H bond acceptors.
/// </summary>
/// <returns>number of H bond acceptors</returns>
public Result Calculate(IAtomContainer container)
{
// do aromaticity detection
if (checkAromaticity)
{
container = (IAtomContainer)container.Clone(); // don't mod original
AtomContainerManipulator.PercieveAtomTypesAndConfigureAtoms(container);
Aromaticity.CDKLegacy.Apply(container);
}
int hBondAcceptors = 0;
// labelled for loop to allow for labelled continue statements within the loop
foreach (var atom in container.Atoms)
{
// looking for suitable nitrogen atoms
if (atom.AtomicNumber.Equals(AtomicNumbers.N) && atom.FormalCharge <= 0)
{
// excluding nitrogens that are adjacent to an oxygen
var bonds = container.GetConnectedBonds(atom);
int nPiBonds = 0;
foreach (var bond in bonds)
{
if (bond.GetConnectedAtom(atom).AtomicNumber.Equals(AtomicNumbers.O))
goto continue_atomloop;
if (BondOrder.Double.Equals(bond.Order))
nPiBonds++;
}
// if the nitrogen is aromatic and there are no pi bonds then it's
// lone pair cannot accept any hydrogen bonds
if (atom.IsAromatic && nPiBonds == 0)
continue;
hBondAcceptors++;
}
// looking for suitable oxygen atoms
else if (atom.AtomicNumber.Equals(AtomicNumbers.O) && atom.FormalCharge <= 0)
{
//excluding oxygens that are adjacent to a nitrogen or to an aromatic carbon
var neighbours = container.GetConnectedBonds(atom);
foreach (var bond in neighbours)
{
var neighbor = bond.GetOther(atom);
switch (neighbor.AtomicNumber)
{
case AtomicNumbers.N:
goto continue_atomloop;
case AtomicNumbers.C:
if (neighbor.IsAromatic && bond.Order != BondOrder.Double)
goto continue_atomloop;
break;
}
}
hBondAcceptors++;
}
continue_atomloop:
;
}
return new Result(hBondAcceptors);
}
IDescriptorResult IMolecularDescriptor.Calculate(IAtomContainer mol) => Calculate(mol);
}
}
| lgpl-2.1 |
HailStorm32/Q.bo_stacks | qbo_self_recognizer/src/qbo_self_recognizer/srv/_QboRecognize.py | 6317 | """autogenerated by genpy from qbo_self_recognizer/QboRecognizeRequest.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class QboRecognizeRequest(genpy.Message):
_md5sum = "d41d8cd98f00b204e9800998ecf8427e"
_type = "qbo_self_recognizer/QboRecognizeRequest"
_has_header = False #flag to mark the presence of a Header object
_full_text = """
"""
__slots__ = []
_slot_types = []
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(QboRecognizeRequest, self).__init__(*args, **kwds)
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
pass
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
pass
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
"""autogenerated by genpy from qbo_self_recognizer/QboRecognizeResponse.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
class QboRecognizeResponse(genpy.Message):
_md5sum = "4a7936398cbe09a7d47b0d9fc1e9e7f3"
_type = "qbo_self_recognizer/QboRecognizeResponse"
_has_header = False #flag to mark the presence of a Header object
_full_text = """bool recognized
"""
__slots__ = ['recognized']
_slot_types = ['bool']
def __init__(self, *args, **kwds):
"""
Constructor. Any message fields that are implicitly/explicitly
set to None will be assigned a default value. The recommend
use is keyword arguments as this is more robust to future message
changes. You cannot mix in-order arguments and keyword arguments.
The available fields are:
recognized
:param args: complete set of field values, in .msg order
:param kwds: use keyword arguments corresponding to message field names
to set specific fields.
"""
if args or kwds:
super(QboRecognizeResponse, self).__init__(*args, **kwds)
#message fields cannot be None, assign default values for those that are
if self.recognized is None:
self.recognized = False
else:
self.recognized = False
def _get_types(self):
"""
internal API method
"""
return self._slot_types
def serialize(self, buff):
"""
serialize message into buffer
:param buff: buffer, ``StringIO``
"""
try:
buff.write(_struct_B.pack(self.recognized))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize(self, str):
"""
unpack serialized message in str into this message instance
:param str: byte array of serialized message, ``str``
"""
try:
end = 0
start = end
end += 1
(self.recognized,) = _struct_B.unpack(str[start:end])
self.recognized = bool(self.recognized)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
def serialize_numpy(self, buff, numpy):
"""
serialize message with numpy array types into buffer
:param buff: buffer, ``StringIO``
:param numpy: numpy python module
"""
try:
buff.write(_struct_B.pack(self.recognized))
except struct.error as se: self._check_types(struct.error("%s: '%s' when writing '%s'" % (type(se), str(se), str(_x))))
except TypeError as te: self._check_types(ValueError("%s: '%s' when writing '%s'" % (type(te), str(te), str(_x))))
def deserialize_numpy(self, str, numpy):
"""
unpack serialized message in str into this message instance using numpy for array types
:param str: byte array of serialized message, ``str``
:param numpy: numpy python module
"""
try:
end = 0
start = end
end += 1
(self.recognized,) = _struct_B.unpack(str[start:end])
self.recognized = bool(self.recognized)
return self
except struct.error as e:
raise genpy.DeserializationError(e) #most likely buffer underfill
_struct_I = genpy.struct_I
_struct_B = struct.Struct("<B")
class QboRecognize(object):
_type = 'qbo_self_recognizer/QboRecognize'
_md5sum = '4a7936398cbe09a7d47b0d9fc1e9e7f3'
_request_class = QboRecognizeRequest
_response_class = QboRecognizeResponse
| lgpl-2.1 |
dotfeng/Deafmutism | Deafmutism/src/net/fengg/app/deafmutism/AppExceptions.java | 7173 | /**
*
* @author Feng
*/
package net.fengg.app.deafmutism;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread.UncaughtExceptionHandler;
import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.http.HttpException;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
/**
*
* @author Feng
*
*/
public class AppExceptions extends Exception implements
UncaughtExceptionHandler {
/**
*
*/
private static final long serialVersionUID = 8821946901284487917L;
private final static boolean Debug = false;// 是否保存错误日志
/** 定义异常类型 */
public final static byte TYPE_NETWORK = 0x01;
public final static byte TYPE_SOCKET = 0x02;
public final static byte TYPE_HTTP_CODE = 0x03;
public final static byte TYPE_HTTP_ERROR = 0x04;
public final static byte TYPE_XML = 0x05;
public final static byte TYPE_IO = 0x06;
public final static byte TYPE_RUN = 0x07;
private byte type;
private int code;
public static final String TAG = "mDefaultHandler";
private UncaughtExceptionHandler mDefaultHandler;
/**
* @return the type
*/
public byte getType() {
return type;
}
/**
* @return the code
*/
public int getCode() {
return code;
}
private AppExceptions() {
this.mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
}
public AppExceptions(byte type, int code, Exception exception) {
super(exception);
this.type = type;
this.code = code;
if (Debug) {
this.saveErrorLog(exception);
}
}
Context context;
public void makeToast(Context context) {
this.context = context;
switch (this.getType()) {
case TYPE_HTTP_CODE:
String err = context.getString(R.string.http_status_code_error,
this.getCode());
Toast.makeText(context, err, Toast.LENGTH_SHORT).show();
break;
case TYPE_HTTP_ERROR:
Toast.makeText(context, R.string.http_exception_error,
Toast.LENGTH_SHORT).show();
break;
case TYPE_SOCKET:
Toast.makeText(context, R.string.socket_exception_error,
Toast.LENGTH_SHORT).show();
break;
case TYPE_NETWORK:
Toast.makeText(context, R.string.network_not_connected,
Toast.LENGTH_SHORT).show();
break;
case TYPE_XML:
Toast.makeText(context, R.string.xml_parser_failed,
Toast.LENGTH_SHORT).show();
break;
case TYPE_IO:
Toast.makeText(context, R.string.io_exception_error,
Toast.LENGTH_SHORT).show();
break;
case TYPE_RUN:
Toast.makeText(context, R.string.app_run_code_error,
Toast.LENGTH_SHORT).show();
break;
}
}
/**
* 保存异常信息到SD卡
*
* @param exception
*/
private void saveErrorLog(Exception exception) {
String logName = "errorlog.txt";
String savePath = "";
String filePath = "";
FileWriter fw = null;
PrintWriter pw = null;
String sdstate = Environment.getExternalStorageState();
if (sdstate == Environment.MEDIA_MOUNTED) {
savePath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + R.string.app_name+"/Log/";
File file = new File(savePath);
if (!file.exists()) {
file.mkdir();
}
} else {
File file = context.getCacheDir();
savePath = file.toString() + File.separator;
}
filePath = savePath + logName;
if (savePath.equals("")) {
return;
}
File file = new File(filePath);
if (!file.exists()) {
try {
file.createNewFile();
fw = new FileWriter(file, true);
pw = new PrintWriter(fw);
exception.printStackTrace(pw);
pw.close();
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (pw != null)
pw.close();
if (fw != null)
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static AppExceptions http(int code) {
return new AppExceptions(TYPE_HTTP_CODE, code, null);
}
public static AppExceptions http(Exception e) {
return new AppExceptions(TYPE_HTTP_ERROR, 0, e);
}
public static AppExceptions socket(Exception e) {
return new AppExceptions(TYPE_SOCKET, 0, e);
}
public static AppExceptions io(Exception e) {
if (e instanceof UnknownHostException || e instanceof ConnectException) {
return new AppExceptions(TYPE_NETWORK, 0, e);
} else if (e instanceof IOException) {
return new AppExceptions(TYPE_IO, 0, e);
}
return run(e);
}
public static AppExceptions xml(Exception e) {
return new AppExceptions(TYPE_XML, 0, e);
}
public static AppExceptions network(Exception e) {
if (e instanceof UnknownHostException || e instanceof ConnectException) {
return new AppExceptions(TYPE_NETWORK, 0, e);
} else if (e instanceof HttpException) {
return http(e);
} else if (e instanceof SocketException) {
return socket(e);
}
return http(e);
}
public static AppExceptions run(Exception e) {
return new AppExceptions(TYPE_RUN, 0, e);
}
@Override
public void uncaughtException(Thread thread, Throwable ex) {
if (!handleException(ex) && mDefaultHandler != null) {
mDefaultHandler.uncaughtException(thread, ex);
}
}
/**
* 自定义异常处理:收集错误信息&发送错误报告
*
* @param ex
* @return true:处理了该异常信息;否则返回false
*/
private boolean handleException(Throwable ex) {
if (ex == null) {
return false;
}
final Context context = AppManager.getAppManager().getCurrentActivity();
if (context == null) {
return false;
}
final String crashReport = getCrashReport(context, ex);
// 显示异常信息&发送报告
new Thread() {
public void run() {
Looper.prepare();
makeToast(context);
sendAppCrashReport(context, crashReport);
Looper.loop();
}
/**
* 发送异常信息到服务器
*
* @param context
* @param crashReport
*/
private void sendAppCrashReport(Context context, String crashReport) {
Log.d(TAG, "an error occured when collect crash info");
}
}.start();
return true;
}
/**
* 获取APP崩溃异常报告
*
* @param ex
* @return
*/
private String getCrashReport(Context context, Throwable ex) {
PackageInfo pinfo = ((AppContext) context.getApplicationContext())
.getPackageInfo();
StringBuffer exceptionStr = new StringBuffer();
exceptionStr.append("Version: " + pinfo.versionName + "("
+ pinfo.versionCode + ")\n");
exceptionStr.append("Android: " + android.os.Build.VERSION.RELEASE
+ "(" + android.os.Build.MODEL + ")\n");
exceptionStr.append("Exception: " + ex.getMessage() + "\n");
StackTraceElement[] elements = ex.getStackTrace();
for (int i = 0; i < elements.length; i++) {
exceptionStr.append(elements[i].toString() + "\n");
}
return exceptionStr.toString();
}
/**
* 获取APP异常崩溃处理对象
*
* @param context
* @return
*/
public static AppExceptions getAppExceptionHandler() {
return new AppExceptions();
}
}
| lgpl-2.1 |
drawapp8/cantk | cantk/controls/js/ui-device.js | 7971 | /*
* File: ui-device.js
* Author: Li XianJing <xianjimli@hotmail.com>
* Brief: Device
*
* Copyright (c) 2011 - 2015 Li XianJing <xianjimli@hotmail.com>
*
*/
function UIDevice() {
return;
}
UIDevice.PORTRAIT = 0;
UIDevice.LANDSCAPE = 1;
UIDevice.prototype = new UIElement();
UIDevice.prototype.isUIDevice = true;
UIDevice.prototype.doToJson = function(o) {
UIElement.prototype.doToJson(this, o);
o.config = this.config;
return;
}
UIDevice.prototype.drawSelectMarks = function(canvas) {
}
UIDevice.prototype.doFromJson = function(js) {
UIElement.prototype.doFromJson.call(this, js);
if(js.config) {
this.config = dupDeviceConfig(js.config);
}
return;
}
UIDevice.prototype.getDirection = function() {
return (this.h > this.w) ? UIDevice.PORTRAIT : UIDevice.LANDSCAPE;
}
UIDevice.prototype.setDirection = function(direction) {
var currDirection = this.getDirection();
if(direction === currDirection) {
return;
}
var oldJson = JSON.stringify(this.toJson());
var w = this.w;
var h = this.h;
var delta = (h - w)/2;
this.left = this.left - delta;
this.top = this.top + delta;
var screenX = 0;
var screenY = 0;
var screenW = this.config.screenW;
var screenH = this.config.screenH;
if(currDirection === UIDevice.PORTRAIT) {
this.top = 100;
screenX = this.config.screenY;
screenY = w - (this.config.screenX + this.config.screenW);
}
else {
this.top = 0;
screenY = this.config.screenX;
screenX = h - (this.config.screenY + this.config.screenH);
}
this.w = h;
this.h = w;
this.config.screenX = screenX;
this.config.screenY = screenY;
this.config.screenW = screenH;
this.config.screenH = screenW;
var newJson = JSON.stringify(this.toJson());
this.exec(new PropertyCommand(this, oldJson, newJson));
return;
}
UIDevice.prototype.setName = function(name) {
this.name = name;
this.loadConfig();
return;
}
UIDevice.prototype.beforePropertyChanged = function() {
this.oldConfig = dupDeviceConfig(this.config);
return;
}
UIDevice.prototype.afterPropertyChanged = function() {
if(!isDeviceConfigEqual(this.oldConfig, this.config)) {
this.notifyDeviceConfigChanged(this.oldConfig, this.config);
}
this.relayout();
return;
}
UIDevice.prototype.onDeviceConfigChanged = function(oldConfig, newConfig) {
this.relayoutChildren();
return;
}
UIDevice.prototype.loadConfig = function() {
var config = cantkGetDeviceConfig(this.name);
if(!config) {
config = cantkGetDeviceConfig("iphone5");
}
if(config) {
this.config = config;
}
return;
}
UIDevice.prototype.initUIDevice = function(type, w, h, name, bg) {
this.initUIElement(type);
this.setDefSize(w, h);
this.setName(name);
this.loadConfig();
this.setTextType(Shape.TEXT_NONE);
this.setImage(UIElement.IMAGE_DEFAULT, bg);
this.setUserResizable(false);
this.rectSelectable = false;
this.events = {};
return this;
}
UIDevice.prototype.drawBgImage = function(canvas) {
var image = this.getHtmlImageByType(UIElement.IMAGE_DEFAULT);
if(image) {
var hw = this.h/this.w;
var ihw = image.height/image.width;
if((hw <= 1 && ihw <= 1) || (hw >= 1 && ihw >= 1)) {
this.drawImageAt(canvas, image, this.images.display, 0, 0, this.w, this.h);
}
else {
canvas.save();
canvas.translate(this.h/2, this.h/2);
canvas.rotate(-Math.PI/2);
canvas.translate(-this.h/2, -this.h/2);
this.drawImageAt(canvas, image, this.images.display, 0, 0, this.h, this.w);
canvas.restore();
}
}
return;
}
UIDevice.prototype.getScreen = function() {
for(var i = 0; i < this.children.length; i++) {
var child = this.children[i];
if(child.isUIScreen) {
return child;
}
}
return null;
}
UIDevice.prototype.enterPreview = function(previewCurrentWindow) {
var app = this.getApp();
var screen = this.getScreen();
var windowManager = this.getWindowManager();
if(!windowManager || !screen || !app) {
return;
}
if(!windowManager.isInDesignMode()) {
return;
}
var current = windowManager.getCurrent();
app.saveTemp();
app.clearCommandHistory();
var button = this.findChildByName("button-preview", false);
if(button) {
button.setText(dappGetText("Edit"));
}
windowManager.saveState();
this.setMode(Shape.MODE_PREVIEW);
screen.setMode(Shape.MODE_PREVIEW, true);
ResLoader.reset();
app.loadUserScripts();
windowManager.systemInit();
windowManager.setInitWindow(null);
if(previewCurrentWindow) {
windowManager.setInitWindow(current);
}
return;
}
UIDevice.prototype.exitPreview = function() {
var screen = this.getScreen();
var windowManager = this.getWindowManager();
if(!windowManager || !screen || !this.app) {
return;
}
if(windowManager.mode != Shape.MODE_PREVIEW) {
return;
}
var button = this.findChildByName("button-preview", false);
if(button) {
button.setText(dappGetText("Preview"));
}
if(this.app) {
this.app.clearCommandHistory();
}
windowManager.systemExit();
this.setMode(Shape.MODE_EDITING);
screen.setMode(Shape.MODE_EDITING, true);
windowManager.restoreState();
windowManager.clearState();
this.setSelected(true);
UIElement.timeScale = 1;
return;
}
UIDevice.prototype.shapeCanBeChild = function(shape) {
if(shape.isUIDevice) {
var json = shape.toJson();
json.x = this.left;
json.y = this.top;
this.fromJson(json);
this.relayoutChildren();
if(this.app) {
this.app.clearCommandHistory();
}
return false;
}
return (shape.isUIScreen && this.getScreen() === null);
}
UIDevice.prototype.relayoutChildren = function() {
if(this.disableRelayout) {
return;
}
var x = 0;
var y = 0;
var w = 0;
var h = 0;
var device = this;
for(var i = 0; i < this.children.length; i++) {
var shape = this.children[i];
if(shape.isUIScreen) {
x = this.config.screenX;
y = this.config.screenY;
w = this.config.screenW;
h = this.config.screenH;
shape.widthAttr = UIElement.WIDTH_FIX;
shape.heightAttr = UIElement.HEIGHT_FIX;
shape.setLeftTop(x, y);
shape.setSize(w, h);
shape.relayout();
}
else {
shape.setVisible(false);
}
}
return true;
}
UIDevice.prototype.afterSetView = function() {
this.relayoutChildren();
return;
}
UIDevice.prototype.getWindowManager = function() {
var screen = this.getScreen();
return screen ? screen.getWindowManager() : null;
}
UIDevice.prototype.paintSelfOnly =function(canvas) {
var image = this.getHtmlImageByType(UIElement.IMAGE_DEFAULT);
if(!image) {
canvas.beginPath();
drawRoundRect(canvas, this.w, this.h, 40);
canvas.fill();
canvas.stroke();
}
return;
}
UIDevice.prototype.onKeyDownRunning = function(code) {
var wm = this.getWindowManager();
return wm.onKeyDownRunning(code);
}
UIDevice.prototype.onKeyUpRunning = function(code) {
var wm = this.getWindowManager();
if(code == KeyEvent.DOM_VK_P) {
this.snapIt();
}
return wm.onKeyUpRunning(code);
}
UIDevice.prototype.snapIt = function() {
var el = null;
var snapDevice = cantkGetQueryParam("snap-device");
var snapScreen = cantkGetQueryParam("snap-screen");
if(snapDevice) {
el = this;
}
if(snapScreen) {
el = this.getWindowManager();
}
if(!el) {
return;
}
var value = null;
value = cantkGetQueryParam("width");
var width = value ? parseInt(value) : el.w;
value = cantkGetQueryParam("height");
var height = value ? parseInt(value) : el.h;
var tcanvas = cantkGetTempCanvas(width, height);
var ctx = tcanvas.getContext("2d");
var xscale = width/el.w;
var yscale = height/el.h;
ctx.save();
ctx.scale(xscale, yscale);
ctx.translate(-el.x, -el.y);
el.paint(ctx);
ctx.restore();
window.open(tcanvas.toDataURL(), "_blank");
return;
}
function UIDeviceCreator(name, version, w, h) {
var args = ["ui-device", "ui-device", null, 1];
ShapeCreator.apply(this, args);
this.createShape = function(createReason) {
var g = new UIDevice();
g.initUIDevice(this.type, w, h, name+version, null);
return g;
}
return;
}
ShapeFactoryGet().addShapeCreator(new UIDeviceCreator("android", "", 420, 700));
| lgpl-2.1 |
bharathravi/tinysql | src/ORG/as220/tinySQL/sqlparser/ParameterValue.java | 2483 | /*
*
* Copyright 1996, Brian C. Jepson
* (bjepson@ids.net)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package ORG.as220.tinySQL.sqlparser;
import ORG.as220.tinySQL.tinySQLException;
import ORG.as220.tinySQL.tsRow;
import ORG.as220.tinySQL.util.EmptyEnumeration;
import java.util.Enumeration;
import java.util.HashMap;
/**
* A ParameterValue is a placeholder for PreparedStatement-Parameters.
* such a parameter can replace any String or numeric value, but it
* cannot parameterize structural data, such as column definitions, tables
* or operators.
*/
public class ParameterValue implements LValue
{
private Object value;
private boolean valueSet = false;
public ParameterValue()
{
}
/**
* If no value is set, throw a exception. A value can be set to null,
* you can check the parameter using the isEmpty() method.
*/
public Object evaluate(tsRow row) throws tinySQLException
{
if (!valueSet)
throw new tinySQLException("Parameter not set");
return value;
}
public boolean isEmpty()
{
return valueSet == false;
}
public void clear()
{
valueSet = false;
value = null;
}
public void setValue(Object value)
{
valueSet = true;
this.value = value;
}
public Object getValue()
{
return value;
}
public String getName()
{
return (hashCode() + "-ParameterValue");
}
public Enumeration getChildren()
{
return EmptyEnumeration.getEnum();
}
public HashMap getRange()
{
HashMap v = new HashMap();
return v;
}
public int getChildCount()
{
return 0;
}
public String toString()
{
return "[" + getName() + "]";
}
}
| lgpl-2.1 |
walafc0/soclib | soclib/module/stub_component/vci_initiator_from_text/caba/utils/vci_cmd_rand_gen/main.cpp | 3991 | /* -*- c++ -*-
*
* SOCLIB_LGPL_HEADER_BEGIN
*
* This file is part of SoCLib, GNU LGPLv2.1.
*
* SoCLib is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 of the License.
*
* SoCLib is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SoCLib; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* SOCLIB_LGPL_HEADER_END
*
* Copyright (c) UPMC, Lip6, SoC
* Etienne Le Grand <etilegr@hotmail.com>, 2009
*/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <time.h>
// Support for the long long type. This type is not in the standard
// but is usually supported by compilers.
#ifndef WIN32
typedef long long int64;
#else
typedef __int64 int64;
#endif
int main(int argc, char* argv[]){
printf("VCI commands file random generator\n");
if (argc<1){
printf("Syntax : vci_cmd_rand_gen [f_file [nbcmd]]\n");
}
char* filename=new char[256];
FILE* f_file;
printf("Enter a name for the output VCI commands file :");
if (argc>1){
filename=argv[1];
printf("%s\n",filename);
}else{
std::cin >> filename;
}
f_file=fopen(filename,"w");
if (f_file==0){
printf("Could not create output file\n");
return 1;
}
int nbcmd;
printf("Number of commands to generate : ");
if (argc>2){
nbcmd=atoi(argv[2]);
printf("%d\n",nbcmd);
}else{
std::cin >> nbcmd;
}
if (nbcmd<1){
printf("Incorrect number of commands to generate\n");
fclose(f_file);
return 2;
}
unsigned int rndinit=(unsigned)time(NULL);
fprintf(f_file,"' Randomly generated VCI commands file\n");
fprintf(f_file,"' Random's seed : %u\n",rndinit);
srand(rndinit);
int srcid, start_srcid=0, size_srcid=16;
int trdid, start_trdid=0, size_trdid=2;
int pktid, start_pktid=0, size_pktid=4;
#ifndef WIN32
int64 addr, start_addr=0, size_addr= 0xFFFFFFFFFFLL;
#else
int64 addr, start_addr=0, size_addr= 0xFFFFFFFFFFL;
#endif
int cmd, start_cmd=1, size_cmd=2;
int plen, start_plen= 1, size_plen=16;
unsigned int wdata, start_wdata=0, size_wdata=0xFFFFFFFF;
int be, start_be=-10, size_be=200;
int i,j;
for (i=nbcmd;i>0;i--){
srcid= rand()%size_srcid + start_srcid;
trdid= rand()%size_trdid + start_trdid;
pktid= rand()%size_pktid + start_pktid;
cmd= rand()%size_cmd + start_cmd;
plen= rand()%size_plen + start_plen;
if (cmd==2)
plen=(plen-1) % 8+1;
do{
addr= ((rand()+((int64)rand()*RAND_MAX+rand())*RAND_MAX)%size_addr + start_addr);
addr=(addr/4)*4;
// Avoid crossing borders of 8 or 16 words
}while ((cmd==2 && ((addr/4)%8+plen>8)) || (cmd==1 && ((addr/4)%16+plen>16)));
wdata=(rand()+rand()*RAND_MAX)%size_wdata + start_wdata;
be= rand()%size_be + start_be;
if (be>15) be=15;
if (be<0) be=0;
fprintf(f_file,"%.2d %d %d ",srcid,trdid,pktid);
switch (cmd){
case 1:
fprintf(f_file,"RE(%.6X%.4X,%.2X|%X)",(int)(addr/0x10000),(int)(addr%0x10000),plen*4,be);
break;
case 2:
fprintf(f_file,"WR(%.6X%.4X,%.2X,%.8X|%X",(int)(addr/0x10000),(int)(addr%0x10000),plen*4,wdata,be);
for (j=plen-1;j>0;j--){
wdata=(rand()+rand()*RAND_MAX)%size_wdata + start_wdata;
be= rand()%size_be + start_be;
if (be>15) be=15;
if (be<0) be=0;
fprintf(f_file,",\n %.8X|%X",wdata,be);
}
fprintf(f_file,")");
break;
}
fprintf(f_file,"\n");
}
printf("Generation terminee avec succes\n");
fclose(f_file);
return 0;
}
| lgpl-2.1 |
free-erp/invoicing | invoicing_client/src/org/free_erp/client/ui/forms/warehouse/CStorageLossDialog.java | 8489 | /*
* Copyright 2013, TengJianfa , and other individual contributors as indicated
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.free_erp.client.ui.forms.warehouse;
import java.awt.Dimension;
import java.awt.Frame;
import com.jdatabeans.beans.CPanel;
import com.jdatabeans.beans.ValueChangedEvent;
import com.jdatabeans.beans.ValueChangedListener;
import com.jdatabeans.beans.data.IDataRow;
import com.jdatabeans.beans.data.IDataSource;
import com.jdatabeans.beans.data.IDbSupport;
import com.jdatabeans.beans.data.JDataDatePicker;
import com.jdatabeans.beans.data.JDataField;
import com.jdatabeans.beans.data.ObjectDataRow;
import com.jdatabeans.beans.data.table.ITableColumnModel;
import com.jdatabeans.beans.data.table.JDataTableColumn;
import com.jdatabeans.print.CPrintDialog;
import org.free_erp.client.ui.forms.CBaseStorageMainDetailDialog;
import org.free_erp.client.ui.forms.CBaseProductSelectDialog;
import org.free_erp.client.ui.main.Main;
import org.free_erp.client.ui.util.ReportUtilities;
import org.free_erp.client.ui.util.ReportVO;
import org.free_erp.service.entity.storage.LossStorageDetailPo;
import org.free_erp.service.entity.storage.LossStoragePo;
import org.free_erp.service.entity.system.Permission;
import org.free_erp.service.logic.IPermissionsService;
import java.awt.Image;
import java.util.Currency;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* ²Ö¿â¹ÜÀí
* ¿â´æ±¨Ëð Dialog
*
* @author TengJianfa mobile:086-13003311398 qq:575633370 www.free-erp.com
*/
public class CStorageLossDialog extends CBaseStorageMainDetailDialog
{
protected JDataDatePicker inDateField;
protected JDataField commentField;
public CStorageLossDialog(Frame parent, IDataSource dataSource, IDbSupport dbSupport)
{
super(parent, dataSource, dbSupport);
initCs();
}
public CStorageLossDialog(Frame parent, IDbSupport dbSupport)
{
super(parent, dbSupport);
initCs();
}
private void initCs()
{
this.setTitle("±¨Ëðµ¥");
}
protected void initColumns()
{
ITableColumnModel columnModel = table.getTableColumnModel();
JDataTableColumn column = new JDataTableColumn();
column.setHeaderText("ÉÌÆ·±àºÅ");
column.setColumnName("product.number");
column.setWidth(120);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("ÉÌÆ·Ãû³Æ");
column.setColumnName("product.name");
column.setWidth(150);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("¹æ¸ñ");
column.setColumnName("product.spec");
column.setWidth(100);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("µ¥Î»");
column.setColumnName("product.smallUnit");
column.setWidth(60);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("¿â´æµ¥¼Û");
column.setColumnName("price");
column.setWidth(80);
column.setValueType(Currency.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("ÕÊÃæÊýÁ¿");
column.setColumnName("oldAmount");
column.setTotalRowVisible(true);
column.setWidth(80);
column.setTotalRowVisible(true);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("ÕÊÃæ½ð¶î");
column.setColumnName("oldMoney");
column.setTotalRowVisible(true);
column.setWidth(100);
column.setTotalRowVisible(true);
column.setValueType(Currency.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("±¨ËðÊýÁ¿");
column.setTotalRowVisible(true);
column.setColumnName("amount");
column.setWidth(80);
column.setTotalRowVisible(true);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("±¨Ëð½ð¶î");
column.setTotalRowVisible(true);
column.setColumnName("totailMoney");
column.setWidth(100);
column.setTotalRowVisible(true);
column.setValueType(Currency.class);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("»õλ");
column.setColumnName("shelf");
column.setWidth(80);
columnModel.addColumn(column);
column = new JDataTableColumn();
column.setHeaderText("±¸×¢");
column.setColumnName("comments");
column.setWidth(180);
columnModel.addColumn(column);
}
@Override
public void newDataRow()
{
LossStoragePo po = new LossStoragePo();
po.setCompany(Main.getMainFrame().getCompany());
IDataRow dataRow = ObjectDataRow.newDataRow(po, "id", this.dbSupport);
this.dataSource.insertDataRow(dataRow);
this.dataSource.last();
}
public CPanel getMainPanel()
{
CPanel topPanel = new CPanel();
topPanel.setPreferredSize(new Dimension(500, 100));
topPanel.setLayout(null);
// idField = new JDataField("number", String.class, this.dataSource);
// idField.setEditable(false);
//idField.setRequired(true);
//idField.setDisplayName("񅧏");
//storageField = new JDataComboBox("storage", Storage.class, this.dataSource, Main.getMainFrame().getObjectsPool().getStorages());
storageField.setRequired(true);
storageField.setDisplayName("²Ö¿âÐÅÏ¢");
//adminField = new JDataComboBox("chargePerson", String.class,this.dataSource, Main.getMainFrame().getObjectsPool().getEmployees());
//departmentField = new JDataComboBox("department", String.class,this.dataSource, Main.getMainFrame().getObjectsPool().getDepartments());
inDateField = new JDataDatePicker("formDate", this.dataSource);
commentField = new JDataField("comments", String.class, this.dataSource);
commentField.setMaxLength(255);
int y = 10;
int x = 80;
topPanel.addComponent(idField, x, y, 150, 20, "µ¥¾Ý±àºÅ", 60);
topPanel.addComponent(storageField, x + 220, y, 180, 20, "²Ö¿â", 60);
topPanel.addComponent(inDateField, x + 490, y, 100, 20, "·¢ÉúÈÕÆÚ", 60);
y += ROW_SPAN;
topPanel.addComponent(adminField, x, y, 150, 20, "±£¹ÜÔ±", 60);
topPanel.addComponent(departmentField, x + 220, y, 180, 20, "²¿ÃÅ", 60);
y += ROW_SPAN;
topPanel.addComponent(commentField, x, y, 590, 20, "±¸×¢", 60);
return topPanel;
}
protected Class getDetailClass()
{
return LossStorageDetailPo.class;
}
@Override
protected void doPrint()
{
Map variables = new HashMap();
ReportVO vo=new ReportVO();
vo.setNumber(idField.getText());
vo.setFromDate((Date)inDateField.getSelectedItem());
vo.setChargePerson(adminField.getText());
vo.setDepartment(departmentField.getText());
vo.setComments(commentField.getText());
vo.setStorageName(storageField.getText());
vo.setTotalMoney(this.sumField.getText());
vo.setStrTotalMoney(this.chineseMoneyField.getText());
vo.setTitle("ÉÌÆ·±¨Ëðµ¥±¨±í");
Image image = Main.getMainFrame().getCompanyLogo();
vo.setImage(image);
variables = ReportUtilities.creatParameterMap(vo);
CPrintDialog printDialog = new CPrintDialog(this, this.getClass().getResourceAsStream("/com/e68erp/demo/client/report/jaspers/StorageLossDetail.jasper"),variables, this.table.getDataSource().getDataRows());
printDialog.setVisible(true);
}
@Override
public CBaseProductSelectDialog getNewProductSelectDialog()
{
return new CStorageLossProductDialog(this, this.table.getDataSource(), this.getStorage());
}
}
| lgpl-2.1 |
EduardoMolina/SU2 | SU2_CFD/src/output/CAdjHeatOutput.cpp | 7845 | /*!
* \file output_adj_heat.cpp
* \brief Main subroutines for flow discrete adjoint output
* \author R. Sanchez
* \version 7.0.3 "Blackbird"
*
* SU2 Project Website: https://su2code.github.io
*
* The SU2 Project is maintained by the SU2 Foundation
* (http://su2foundation.org)
*
* Copyright 2012-2020, SU2 Contributors (cf. AUTHORS.md)
*
* SU2 is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* SU2 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SU2. If not, see <http://www.gnu.org/licenses/>.
*/
#include "../../include/output/CAdjHeatOutput.hpp"
#include "../../../Common/include/geometry/CGeometry.hpp"
#include "../../include/solvers/CSolver.hpp"
CAdjHeatOutput::CAdjHeatOutput(CConfig *config, unsigned short nDim) : COutput(config, nDim, false) {
/*--- Set the default history fields if nothing is set in the config file ---*/
if (nRequestedHistoryFields == 0){
requestedHistoryFields.emplace_back("ITER");
requestedHistoryFields.emplace_back("RMS_RES");
requestedHistoryFields.emplace_back("SENSITIVITY");
nRequestedHistoryFields = requestedHistoryFields.size();
}
if (nRequestedScreenFields == 0){
if (multiZone) requestedScreenFields.emplace_back("OUTER_ITER");
requestedScreenFields.emplace_back("INNER_ITER");
requestedScreenFields.emplace_back("RMS_ADJ_TEMPERATURE");
requestedScreenFields.emplace_back("SENS_GEO");
nRequestedScreenFields = requestedScreenFields.size();
}
if (nRequestedVolumeFields == 0){
requestedVolumeFields.emplace_back("COORDINATES");
requestedVolumeFields.emplace_back("SOLUTION");
requestedVolumeFields.emplace_back("SENSITIVITY");
nRequestedVolumeFields = requestedVolumeFields.size();
}
stringstream ss;
ss << "Zone " << config->GetiZone() << " (Adj. Heat)";
multiZoneHeaderString = ss.str();
/*--- Set the volume filename --- */
volumeFilename = config->GetAdj_FileName();
/*--- Set the surface filename --- */
surfaceFilename = config->GetSurfAdjCoeff_FileName();
/*--- Set the restart filename --- */
restartFilename = config->GetRestart_AdjFileName();
/*--- Add the obj. function extension --- */
restartFilename = config->GetObjFunc_Extension(restartFilename);
/*--- Set the default convergence field --- */
if (convFields.empty() ) convFields.emplace_back("RMS_ADJ_TEMPERATURE");
}
CAdjHeatOutput::~CAdjHeatOutput(void) {}
void CAdjHeatOutput::SetHistoryOutputFields(CConfig *config){
/// BEGIN_GROUP: RMS_RES, DESCRIPTION: The root-mean-square residuals of the conservative variables.
/// DESCRIPTION: Root-mean square residual of the adjoint Pressure.
AddHistoryOutput("RMS_ADJ_TEMPERATURE", "rms[A_T]", ScreenOutputFormat::FIXED, "RMS_RES", "Root-mean square residual of the adjoint temperature.", HistoryFieldType::RESIDUAL);
/// END_GROUP
/// BEGIN_GROUP: MAX_RES, DESCRIPTION: The maximum residuals of the conservative variables.
/// DESCRIPTION: Maximum residual of the adjoint Pressure.
AddHistoryOutput("MAX_ADJ_TEMPERATURE", "max[A_T]", ScreenOutputFormat::FIXED, "MAX_RES", "Maximum residual of the adjoint temperature.", HistoryFieldType::RESIDUAL);
/// BEGIN_GROUP: MAX_RES, DESCRIPTION: The maximum residuals of the conservative variables.
/// DESCRIPTION: Maximum residual of the adjoint Pressure.
AddHistoryOutput("BGS_ADJ_TEMPERATURE", "bgs[A_T]", ScreenOutputFormat::FIXED, "BGS_RES", "BGS residual of the adjoint temperature.", HistoryFieldType::RESIDUAL);
/// BEGIN_GROUP: SENSITIVITY, DESCRIPTION: Sensitivities of different geometrical or boundary values.
/// DESCRIPTION: Sum of the geometrical sensitivities on all markers set in MARKER_MONITORING.
AddHistoryOutput("SENS_GEO", "Sens_Geo", ScreenOutputFormat::SCIENTIFIC, "SENSITIVITY", "Sum of the geometrical sensitivities on all markers set in MARKER_MONITORING.", HistoryFieldType::COEFFICIENT);
/// END_GROUP
}
void CAdjHeatOutput::LoadHistoryData(CConfig *config, CGeometry *geometry, CSolver **solver) {
CSolver* adjheat_solver = solver[ADJHEAT_SOL];
SetHistoryOutputValue("RMS_ADJ_TEMPERATURE", log10(adjheat_solver->GetRes_RMS(0)));
SetHistoryOutputValue("MAX_ADJ_TEMPERATURE", log10(adjheat_solver->GetRes_Max(0)));
if (multiZone) {
SetHistoryOutputValue("BGS_ADJ_TEMPERATURE", log10(adjheat_solver->GetRes_BGS(0)));
}
SetHistoryOutputValue("SENS_GEO", adjheat_solver->GetTotal_Sens_Geo());
}
void CAdjHeatOutput::SetVolumeOutputFields(CConfig *config){
// Grid coordinates
AddVolumeOutput("COORD-X", "x", "COORDINATES", "x-component of the coordinate vector");
AddVolumeOutput("COORD-Y", "y", "COORDINATES", "y-component of the coordinate vector");
if (nDim == 3)
AddVolumeOutput("COORD-Z", "z", "COORDINATES", "z-component of the coordinate vector");
/// BEGIN_GROUP: CONSERVATIVE, DESCRIPTION: The conservative variables of the adjoint solver.
/// DESCRIPTION: Adjoint Pressure.
AddVolumeOutput("ADJ_TEMPERATURE", "Adjoint_Temperature", "SOLUTION" ,"Adjoint Temperature");
/// END_GROUP
/// BEGIN_GROUP: RESIDUAL, DESCRIPTION: Residuals of the conservative variables.
/// DESCRIPTION: Residual of the adjoint Pressure.
AddVolumeOutput("RES_ADJ_TEMPERATURE", "Residual_Adjoint_Temperature", "RESIDUAL", "Residual of the Adjoint Temperature");
/// END_GROUP
/// BEGIN_GROUP: SENSITIVITY, DESCRIPTION: Geometrical sensitivities of the current objective function.
/// DESCRIPTION: Sensitivity x-component.
AddVolumeOutput("SENSITIVITY-X", "Sensitivity_x", "SENSITIVITY", "x-component of the sensitivity vector");
/// DESCRIPTION: Sensitivity y-component.
AddVolumeOutput("SENSITIVITY-Y", "Sensitivity_y", "SENSITIVITY", "y-component of the sensitivity vector");
if (nDim == 3)
/// DESCRIPTION: Sensitivity z-component.
AddVolumeOutput("SENSITIVITY-Z", "Sensitivity_z", "SENSITIVITY", "z-component of the sensitivity vector");
/// DESCRIPTION: Sensitivity in normal direction.
AddVolumeOutput("SENSITIVITY", "Surface_Sensitivity", "SENSITIVITY", "sensitivity in normal direction");
/// END_GROUP
}
void CAdjHeatOutput::LoadVolumeData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint){
CVariable* Node_AdjHeat = solver[ADJHEAT_SOL]->GetNodes();
CPoint* Node_Geo = geometry->node[iPoint];
SetVolumeOutputValue("COORD-X", iPoint, Node_Geo->GetCoord(0));
SetVolumeOutputValue("COORD-Y", iPoint, Node_Geo->GetCoord(1));
if (nDim == 3)
SetVolumeOutputValue("COORD-Z", iPoint, Node_Geo->GetCoord(2));
SetVolumeOutputValue("ADJ_TEMPERATURE", iPoint, Node_AdjHeat->GetSolution(iPoint, 0));
// Residuals
SetVolumeOutputValue("RES_ADJ_TEMPERATURE", iPoint, Node_AdjHeat->GetSolution(iPoint, 0) - Node_AdjHeat->GetSolution_Old(iPoint, 0));
SetVolumeOutputValue("SENSITIVITY-X", iPoint, Node_AdjHeat->GetSensitivity(iPoint, 0));
SetVolumeOutputValue("SENSITIVITY-Y", iPoint, Node_AdjHeat->GetSensitivity(iPoint, 1));
if (nDim == 3)
SetVolumeOutputValue("SENSITIVITY-Z", iPoint, Node_AdjHeat->GetSensitivity(iPoint, 2));
}
void CAdjHeatOutput::LoadSurfaceData(CConfig *config, CGeometry *geometry, CSolver **solver, unsigned long iPoint, unsigned short iMarker, unsigned long iVertex){
SetVolumeOutputValue("SENSITIVITY", iPoint, solver[ADJHEAT_SOL]->GetCSensitivity(iMarker, iVertex));
}
| lgpl-2.1 |
jadahl/jgroups-android | tests/junit-functional/org/jgroups/tests/TimerTest.java | 6219 | // $Id: TimerTest.java,v 1.2 2007/08/10 12:32:14 belaban Exp $
package org.jgroups.tests;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
import org.jgroups.stack.Interval;
import org.jgroups.stack.StaticInterval;
import org.jgroups.util.Util;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
/**
* Test cases for Timer. May fail sometimes, for example if there is GC during the run. Therefore, if run
* standalone, the likelyhood of GC is smaller than when run with the entire testsuite
*
* @author Bela Ban
*/
public class TimerTest extends TestCase {
Timer win=null;
static final int NUM_MSGS=1000;
long[] xmit_timeouts={1000, 2000, 4000, 8000};
double PERCENTAGE_OFF=0.3; // how much can expected xmit_timeout and real timeout differ to still be okay ?
HashMap msgs=new HashMap(); // keys=seqnos (Long), values=Entries
class MyTask extends TimerTask {
Entry entry;
MyTask(Entry entry) {
this.entry=entry;
}
public void run() {
entry.retransmit();
}
}
class Entry {
long start_time=0; // time message was added
long first_xmit=0; // time between start_time and first_xmit should be ca. 1000ms
long second_xmit=0; // time between first_xmit and second_xmit should be ca. 2000ms
long third_xmit=0; // time between third_xmit and second_xmit should be ca. 4000ms
long fourth_xmit=0; // time between third_xmit and second_xmit should be ca. 8000ms
Interval interval=new StaticInterval(xmit_timeouts);
long seqno=0;
Entry(long seqno) {
this.seqno=seqno;
start_time=System.currentTimeMillis();
}
public void retransmit() {
if(first_xmit == 0)
first_xmit=System.currentTimeMillis();
else
if(second_xmit == 0)
second_xmit=System.currentTimeMillis();
else
if(third_xmit == 0)
third_xmit=System.currentTimeMillis();
else
if(fourth_xmit == 0)
fourth_xmit=System.currentTimeMillis();
win.schedule(new MyTask(this), interval.next());
}
public long next() {
return interval.next();
}
/**
* Entry is correct if xmit timeouts are not more than 30% off the mark
*/
boolean isCorrect() {
long t;
long expected;
long diff, delta;
boolean off=false;
t=first_xmit - start_time;
expected=xmit_timeouts[0];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
t=second_xmit - first_xmit;
expected=xmit_timeouts[1];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
t=third_xmit - second_xmit;
expected=xmit_timeouts[2];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
t=fourth_xmit - third_xmit;
expected=xmit_timeouts[3];
diff=Math.abs(expected - t);
delta=(long)(expected * PERCENTAGE_OFF);
if(diff >= delta) off=true;
if(off) {
System.err.println("#" + seqno + ": " + this + ": (" + "entry is more than " +
PERCENTAGE_OFF + " percentage off ");
return false;
}
return true;
}
public String toString() {
StringBuilder sb=new StringBuilder();
sb.append(first_xmit - start_time).append(", ").append(second_xmit - first_xmit).append(", ");
sb.append(third_xmit - second_xmit).append(", ").append(fourth_xmit - third_xmit);
return sb.toString();
}
}
public TimerTest(String name) {
super(name);
}
/**
* Tests whether retransmits are called at correct times for 1000 messages. A retransmit should not be
* more than 30% earlier or later than the scheduled retransmission time
*/
public void testRetransmits() {
Entry entry;
MyTask task;
int num_non_correct_entries=0;
win=new Timer();
// 1. Add NUM_MSGS messages:
System.out.println("-- adding " + NUM_MSGS + " messages:");
for(long i=0; i < NUM_MSGS; i++) {
entry=new Entry(i);
task=new MyTask(entry);
msgs.put(new Long(i), entry);
win.schedule(task, entry.next());
}
System.out.println("-- done");
// 2. Wait for at least 4 xmits/msg: total of 1000 + 2000 + 4000 + 8000ms = 15000ms; wait for 20000ms
System.out.println("-- waiting for 20 secs for all retransmits");
Util.sleep(20000);
// 3. Check whether all Entries have correct retransmission times
for(long i=0; i < NUM_MSGS; i++) {
entry=(Entry)msgs.get(new Long(i));
if(!entry.isCorrect()) {
num_non_correct_entries++;
}
}
if(num_non_correct_entries > 0)
System.err.println("Number of incorrect retransmission timeouts: " + num_non_correct_entries);
else {
for(long i=0; i < NUM_MSGS; i++) {
entry=(Entry)msgs.get(new Long(i));
if(entry != null)
System.out.println(i + ": " + entry);
}
}
assertSame(0, num_non_correct_entries);
try {
win.cancel();
}
catch(Exception ex) {
System.err.println(ex);
}
}
public static Test suite() {
TestSuite suite;
suite=new TestSuite(TimerTest.class);
return (suite);
}
public static void main(String[] args) {
String[] name={TimerTest.class.getName()};
junit.textui.TestRunner.main(name);
}
}
| lgpl-2.1 |
myers/id3v2 | convert.cpp | 1772 | #include <cstdio>
#include <iostream>
#include <id3/tag.h>
#include <cstdlib>
void DeleteTag(int argc, char *argv[], int optind, int whichTags)
{
FILE * fp;
for (size_t nIndex = optind; nIndex < argc; nIndex++)
{
/* cludgy to check if we have the proper perms */
fp = fopen(argv[nIndex], "r+");
if (fp == NULL) { /* file didn't open */
fprintf(stderr, "fopen: %s: ", argv[nIndex]);
perror("id3v2");
continue;
}
fclose(fp);
ID3_Tag myTag;
std::cout << "Stripping id3 tag in \"";
std::cout << argv[nIndex] << "\"...";
myTag.Clear();
myTag.Link(argv[nIndex], ID3TT_ALL);
luint nTags;
switch(whichTags)
{
case 1:
nTags = myTag.Strip(ID3TT_ID3V1);
std::cout << "id3v1 ";
break;
case 2:
nTags = myTag.Strip(ID3TT_ID3V2);
std::cout << "id3v2 ";
break;
case 0:
default:
nTags = myTag.Strip(ID3TT_ID3);
std::cout << "id3v1 and v2 ";
}
std::cout << "stripped." << std::endl;
}
return;
}
void ConvertTag(int argc, char *argv[], int optind)
{
for (size_t nIndex = optind; nIndex < argc; nIndex++)
{
ID3_Tag myTag;
std::cout << "Converting id3v1 tag to id3v2 in ";
std::cout << argv[nIndex] << "...";
myTag.Clear();
myTag.Link(argv[nIndex], ID3TT_ALL);
luint nTags;
nTags = myTag.Update(ID3TT_ID3V2);
if (nTags == ID3TT_NONE)
{
std::cout << std::endl;
perror("id3v2");
std::cerr << "Tags could not be converted" << std::endl;
continue;
}
std::cout << " converted ";
std::cout << std::endl;
}
return;
}
| lgpl-2.1 |
SensorsINI/jaer | src/net/sf/jaer/hardwareinterface/usb/cypressfx3libusb/CypressFX3.java | 65356 | /*
* USBAEMon.java
*
* Created on February 17, 2005, 7:54 AM
*/
package net.sf.jaer.hardwareinterface.usb.cypressfx3libusb;
import java.awt.Desktop;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeSupport;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.IntBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.prefs.Preferences;
import javax.swing.JOptionPane;
import javax.swing.SwingWorker;
import org.usb4java.BufferUtils;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import li.longi.USBTransferThread.RestrictedTransfer;
import li.longi.USBTransferThread.RestrictedTransferCallback;
import li.longi.USBTransferThread.USBTransferThread;
import net.sf.jaer.JaerConstants;
import net.sf.jaer.aemonitor.AEListener;
import net.sf.jaer.aemonitor.AEMonitorInterface;
import net.sf.jaer.aemonitor.AEPacketRaw;
import net.sf.jaer.aemonitor.AEPacketRawPool;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.event.EventPacket;
import net.sf.jaer.eventprocessing.EventFilter;
import net.sf.jaer.eventprocessing.FilterChain;
import net.sf.jaer.graphics.AEViewer;
import net.sf.jaer.hardwareinterface.BlankDeviceException;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
import net.sf.jaer.hardwareinterface.usb.HasUsbStatistics;
import net.sf.jaer.hardwareinterface.usb.ReaderBufferControl;
import net.sf.jaer.hardwareinterface.usb.USBInterface;
import net.sf.jaer.hardwareinterface.usb.USBPacketStatistics;
import net.sf.jaer.stereopsis.StereoPairHardwareInterface;
/**
* Devices that use the CypressFX3 and the USBIO driver, e.g. the DVS retinas,
* the USBAERmini2. This class should not
* normally be constructed but rather a subclass that overrides
* the AEReader should be used.
* <p>
* In this class, you can also set the size of the host buffer with {@link #setAEBufferSize}, giving you more time
* between calls to process the events.
* <p>
* On the device, a timer sends all available events approximately every 10ms -- you don't need to wait for a fixed size
* buffer to be captured to be available to the host. But if events come quickly enough, new events can be available
* much faster than this.
* <p>
* You can also request at any time an early transfer of events with {@link #requestEarlyTransfer}. This will send a
* vendor request to the device to immediately transfer available events, but they won't be available to the host for a
* little while, depending on USBIOInterface and driver latency.
* <p>
* See the main() method for an example of use.
* <p>
* Fires PropertyChangeEvent on the following
* <ul>
* <li>NEW_EVENTS_PROPERTY_CHANGE - on new events from driver
* <li>"readerStarted" - when the reader thread is started
* </ul>
*
*
* @author tobi delbruck/raphael berner
*/
public class CypressFX3 implements AEMonitorInterface, ReaderBufferControl, USBInterface, HasUsbStatistics {
/** Used to store preferences, e.g. buffer sizes and number of buffers. */
protected static Preferences prefs = Preferences.userNodeForPackage(CypressFX3.class);
protected static final Logger log = Logger.getLogger("CypressFX3");
protected AEChip chip;
/**
* A blank Cypress FX2 has VID/PID of 0x04b4/0x8613. This VID/PID pair is
* used to indicate a blank device that needs
* programming.
*/
static final public short VID_BLANK = (short) 0x04b4, PID_BLANK = (short) 0x00f3;
/**
* All the devices here have vendor ID VID which has been allocated to jAER
* by Thesycon
*/
static public final short VID = USBInterface.VID_THESYCON;
/**
* event supplied to listeners when new events are collected. this is final
* because it is just a marker for the
* listeners that new events are available
*/
public final PropertyChangeEvent NEW_EVENTS_PROPERTY_CHANGE = new PropertyChangeEvent(this, "NewEvents", null, null);
/**
* Property change fired when new events are received. The new object in the
* event is AEPacketRaw just received.
*/
public static final String PROPERTY_CHANGE_NEW_EVENTS = "NewEvents";
/**
* Property change fired when a new message is received on the asynchronous
* status endpoint.
*
* @see AsyncStatusThread
*/
public static final String PROPERTY_CHANGE_ASYNC_STATUS_MSG = "AsyncStatusMessage";
/**
* This support can be used to register this interface for property change
* events
*/
public PropertyChangeSupport support = new PropertyChangeSupport(this);
final static byte AE_MONITOR_ENDPOINT_ADDRESS = (byte) 0x82; // this is
// endpoint
// of AE
// fifo on
// Cypress
// FX2, 0x86
// means IN endpoint EP6.
final static byte STATUS_ENDPOINT_ADDRESS = (byte) 0x81; // this is endpoint
// 1 IN for
// device to
// report status
public static final byte VR_FPGA_CONFIG = (byte) 0xBF;
public static final byte VR_FPGA_CONFIG_MULTIPLE = (byte) 0xC2;
protected final static short CONFIG_INDEX = 0;
protected final static short CONFIG_NB_OF_INTERFACES = 1;
protected final static short CONFIG_INTERFACE = 0;
protected final static short CONFIG_ALT_SETTING = 0;
protected final static int CONFIG_TRAN_SIZE = 512;
// following are to support realtime filtering
// the AEPacketRaw is used only within this class. Each packet is extracted
// using the chip extractor object from the
// first filter in the
// realTimeFilterChain to a reused EventPacket.
AEPacketRaw realTimeRawPacket = null; // used to hold raw events that are
// extracted for real time procesing
EventPacket realTimePacket = null; // used to hold extracted real time
// events for processing
/**
* start of events that have been captured but not yet processed by the
* realTimeFilters
*/
private int realTimeEventCounterStart = 0;
/**
* timeout in ms to reopen driver (reloading firmware) if no events are
* received for this time. This timeout will
* restart AE transmission if
* another process (e.g. Biasgen) reloads the firmware. This timer is
* checked on every attempt to acquire events.
*/
public static long NO_AE_REOPEN_TIMEOUT = 3000;
/**
* Time in us of each timestamp count here on host, could be different on
* board.
*/
public final short TICK_US = 1;
/**
* default size of AE buffer for user processes. This is the buffer that is
* written by the hardware capture thread
* that holds events
* that have not yet been transferred via {@link #acquireAvailableEventsFromDriver} to another thread
*
* @see #acquireAvailableEventsFromDriver
* @see AEReader
* @see #setAEBufferSize
*/
public static final int AE_BUFFER_SIZE = 600000; // 100k should handle 5Meps at
// 30FPS, but tobi increased to 600k to handle APS frames from Davis346B at 40FPS
/**
* this is the size of the AEPacketRaw that are part of AEPacketRawPool that
* double buffer the translated events
* between rendering and capture threads
*/
protected int aeBufferSize = CypressFX3.prefs.getInt("CypressFX3.aeBufferSize", CypressFX3.AE_BUFFER_SIZE);
/** the event reader - a buffer pool thread from USBIO subclassing */
protected AEReader aeReader = null;
/** the thread that reads device status messages on EP1 */
protected AsyncStatusThread asyncStatusThread = null;
/** The pool of raw AE packets, used for data transfer */
protected AEPacketRawPool aePacketRawPool = new AEPacketRawPool(this);
private String stringDescription = "CypressFX3"; // default which is
private USBPacketStatistics usbPacketStatistics = new USBPacketStatistics();
// modified by opening
/**
* Populates the device descriptor and the string descriptors and builds the
* String for toString().
*
* @param gUsbIo
* the handle to the UsbIo object.
*/
private void populateDescriptors() {
try {
int status;
// getString device descriptor
if (deviceDescriptor == null) {
deviceDescriptor = new DeviceDescriptor();
status = LibUsb.getDeviceDescriptor(device, deviceDescriptor);
if (status != LibUsb.SUCCESS) {
throw new HardwareInterfaceException("populateDescriptors(): getDeviceDescriptor: " + LibUsb.errorName(status));
}
}
if (deviceDescriptor.iSerialNumber() != 0) {
numberOfStringDescriptors = 3; // SN also defined.
}
else {
numberOfStringDescriptors = 2;
}
stringDescriptor1 = LibUsb.getStringDescriptor(deviceHandle, (byte) 1);
if (stringDescriptor1 == null) {
throw new HardwareInterfaceException("populateDescriptors(): getStringDescriptor1");
}
stringDescriptor2 = LibUsb.getStringDescriptor(deviceHandle, (byte) 2);
if (stringDescriptor2 == null) {
throw new HardwareInterfaceException("populateDescriptors(): getStringDescriptor2");
}
if (numberOfStringDescriptors == 3) {
stringDescriptor3 = LibUsb.getStringDescriptor(deviceHandle, (byte) 3);
if (stringDescriptor3 == null) {
throw new HardwareInterfaceException("populateDescriptors(): getStringDescriptor3");
}
}
// build toString string
if (numberOfStringDescriptors == 3) {
stringDescription = (getStringDescriptors()[1] + " " + getStringDescriptors()[2]);
}
else if (numberOfStringDescriptors == 2) {
stringDescription = (getStringDescriptors()[1] + ": Interface " + device);
}
}
catch (final BlankDeviceException bd) {
stringDescription = "Blank Cypress FX2 : Interface " + device;
}
catch (final Exception e) {
stringDescription = (getClass().getSimpleName() + ": Interface " + device);
}
}
/**
* The count of events acquired but not yet passed to user via
* acquireAvailableEventsFromDriver
*/
protected int eventCounter = 0; // counts events acquired but not yet passed
// to user
/**
* the last events from {@link #acquireAvailableEventsFromDriver}, This
* packet is reused.
*/
protected AEPacketRaw lastEventsAcquired = new AEPacketRaw();
protected boolean inEndpointEnabled = false; // raphael: changed from
// private to protected,
// because i need to access
// this member
/** device open status */
private boolean isOpened = false;
/**
* the device number, out of all potential compatible devices that could be
* opened
*/
protected Device device = null;
protected DeviceHandle deviceHandle = null;
/**
* This constructor is protected because these instances should be
* constructed by the CypressFX3Factory.
* Creates a new instance of USBAEMonitor. Note that it is possible to
* construct several instances
* and use each of them to open and read from the same device.
*
* @param devNumber
* the desired device number, in range returned by
* CypressFX3Factory.getNumInterfacesAvailable
*/
protected CypressFX3(final Device device) {
this.device = device;
}
/**
* acquire a device for exclusive use, other processes can't open the device
* anymore
* used for example for continuous sequencing in matlab
*/
public void acquireDevice() throws HardwareInterfaceException {
CypressFX3.log.log(Level.INFO, "{0} acquiring device for exclusive access", this);
final int status = LibUsb.claimInterface(deviceHandle, 0);
if (status != LibUsb.SUCCESS) {
throw new HardwareInterfaceException("Unable to acquire device for exclusive use: " + LibUsb.errorName(status));
}
}
/** release the device from exclusive use */
public void releaseDevice() throws HardwareInterfaceException {
CypressFX3.log.log(Level.INFO, "{0} releasing device", this);
final int status = LibUsb.releaseInterface(deviceHandle, 0);
if (status != LibUsb.SUCCESS) {
throw new HardwareInterfaceException("Unable to release device from exclusive use: " + LibUsb.errorName(status));
}
}
/**
* Returns the PropertyChangeSupport.
*
* @return the support.
* @see #PROPERTY_CHANGE_ASYNC_STATUS_MSG
* @see #PROPERTY_CHANGE_NEW_EVENTS
*/
public PropertyChangeSupport getSupport() {
return support;
}
/**
* Returns string description of device including the
* USB vendor/project IDs. If the device has not been
* opened then it is minimally opened to populate the deviceDescriptor and
* then closed.
*
* @return the string description of the device.
*/
@Override
public String toString() {
if (numberOfStringDescriptors == 0) {
try {
open_minimal_close(); // populates stringDescription and sets
// numberOfStringDescriptors!=0
}
catch (final Exception e) {
log.warning("caught exception when trying to populate stringDescription: "+e.toString());
}
}
return stringDescription;
}
/**
* Writes the serial number string to the device EEPROM
*
* @param name
* the string. This string has very limited length, e.g. 4 bytes.
* @throws net.sf.jaer.hardwareinterface.HardwareInterfaceException
*/
public void setSerialNumber(final String name) throws HardwareInterfaceException {
if (!isOpen()) {
open();
}
final CharsetEncoder encoder = Charset.forName("US-ASCII").newEncoder();
final ByteBuffer buffer = BufferUtils.allocateByteBuffer(name.length());
encoder.encode(CharBuffer.wrap(name), buffer, true);
encoder.flush(buffer);
// sendVendorRequest(CypressFX3.VR_SET_DEVICE_NAME, (short) 0, (short)
// 0, buffer);
stringDescriptor3 = LibUsb.getStringDescriptor(deviceHandle, (byte) 3);
if (stringDescriptor3 == null) {
CypressFX3.log.warning("Could not get new device name!");
}
else {
CypressFX3.log.info("New Devicename set, close and reopen the device to see the change");
}
}
/**
* adds a listener for new events captured from the device.
* Actually gets called whenever someone looks for new events and there are
* some using
* acquireAvailableEventsFromDriver, not when data is actually captured by
* AEReader.
* Thus it will be limited to the users sampling rate, e.g. the game loop
* rendering rate.
*
* @param listener
* the listener. It is called with a PropertyChangeEvent when new
* events
* are received by a call to {@link #acquireAvailableEventsFromDriver}.
* These events may be accessed by calling {@link #getEvents}.
*/
@Override
public void addAEListener(final AEListener listener) {
support.addPropertyChangeListener(listener);
}
@Override
public void removeAEListener(final AEListener listener) {
support.removePropertyChangeListener(listener);
}
/**
* starts reader buffer pool thread and enables in endpoints for AEs.
* Subclasses *MUST* override this method to
* start their own customized reader
* with their own translateEvents method.
*/
public void startAEReader() throws HardwareInterfaceException {
throw new HardwareInterfaceException(
"This method should not be called - the CypressFX3 subclass should override startAEReader. Probably this is a blank device that requires programming.");
}
long lastTimeEventCaptured = System.currentTimeMillis();
/**
* Gets available events from driver. {@link HardwareInterfaceException} is
* thrown if there is an error. {@link #overrunOccurred} will be reset after
* this call.
* <p>
* This method also starts event acquisition if it is not running already.
*
* Not thread safe but does use the thread-safe swap() method of AEPacketRawPool to swap data with the acquisition
* thread.
*
* @return packet of events acquired.
* @throws HardwareInterfaceException
* @see #setEventAcquisitionEnabled
*
* .
*/
@Override
public AEPacketRaw acquireAvailableEventsFromDriver() throws HardwareInterfaceException {
if (!isOpen()) {
open();
}
// make sure event acquisition is running
if (!inEndpointEnabled) {
setEventAcquisitionEnabled(true);
}
// HardwareInterfaceException.clearException();
// make sure that event translation from driver is allowed to run if
// need be, to avoid holding up event sender
// Thread.currentThread().yield();
// short[] addresses;
// int[] timestamps;
int nEvents;
// getString the 'active' buffer for events (the one that has just been
// written by the hardware thread)
// synchronized(aePacketRawPool){ // synchronize on aeReader so that we
// don't try to access the events at the
// same time
synchronized (aePacketRawPool) {
aePacketRawPool.swap();
lastEventsAcquired = aePacketRawPool.readBuffer();
eventCounter = 0;
realTimeEventCounterStart = 0;
}
nEvents = lastEventsAcquired.getNumEvents();
computeEstimatedEventRate(lastEventsAcquired);
if (nEvents != 0) {
support.firePropertyChange(CypressFX3.PROPERTY_CHANGE_NEW_EVENTS, null, lastEventsAcquired); // call
// listeners
}
return lastEventsAcquired;
}
/**
* the max capacity of this USB2 bus interface is 24MB/sec/4 bytes/event
*/
@Override
public int getMaxCapacity() {
return 6000000;
}
private int estimatedEventRate = 0;
/**
* @return event rate in events/sec as computed from last acquisition.
*
*/
@Override
public int getEstimatedEventRate() {
return estimatedEventRate;
}
/** computes the estimated event rate for a packet of events */
void computeEstimatedEventRate(final AEPacketRaw events) {
if ((events == null) || (events.getNumEvents() < 2)) {
estimatedEventRate = 0;
}
else {
final int[] ts = events.getTimestamps();
final int n = events.getNumEvents();
final int dt = ts[n - 1] - ts[0];
estimatedEventRate = (int) ((1e6f * n) / dt);
}
}
/**
* Returns the number of events acquired by the last call to {@link #acquireAvailableEventsFromDriver }
*
* @return number of events acquired
*/
@Override
public int getNumEventsAcquired() {
return lastEventsAcquired.getNumEvents();
}
/**
* Check the firmware and logic versions against exact required ones and display an error if not met.
*/
protected void checkFirmwareLogic(final int requiredFirmwareVersion, final int requiredLogicRevision)
throws HardwareInterfaceException {
final StringBuilder updateStringBuilder = new StringBuilder("<html>");
boolean needsUpdate=false;
// Verify device firmware version and logic revision.
final int usbFWVersion = getDID() & 0x00FF;
if (usbFWVersion != requiredFirmwareVersion) {
updateStringBuilder
.append(String.format("<p>Device firmware version incorrect. You have version %d; but version %d is required.</p>",
usbFWVersion, requiredFirmwareVersion));
needsUpdate=true;
}
final int logicRevision = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 0);
if (logicRevision != requiredLogicRevision) {
updateStringBuilder
.append(String.format("<p>Device logic version incorrect. You have version %d; but version %d is required.</p>",
logicRevision, requiredLogicRevision));
needsUpdate=true;
}
if (needsUpdate) {
updateStringBuilder
.append("<p>Please update by following the Flashy documentation at <a href=\" " + JaerConstants.HELP_USER_GUIDE_URL_FLASHY+"\">"+JaerConstants.HELP_USER_GUIDE_URL_FLASHY+"</a></p>");
updateStringBuilder.append("<p>Clicking OK will open this URL in browser</p>");
updateStringBuilder.append("<p>After installing DV, you can launch flashy from command line (in linux) or from DV GUI</p>");
final String updateString = updateStringBuilder.toString();
final SwingWorker<Void, Void> strWorker = new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
JOptionPane.showMessageDialog(null, updateString);
if(Desktop.isDesktopSupported()){
try {
Desktop.getDesktop().browse(new URI(JaerConstants.HELP_USER_GUIDE_URL_FLASHY));
} catch (Exception ex) {
Logger.getLogger(CypressFX3.class.getName()).log(Level.WARNING, null, ex);
}
}
return (null);
}
};
strWorker.execute();
// throw new HardwareInterfaceException(updateString);
}
}
/**
* Reset the timestamps to zero. This has two effects. First it sends a
* vendor request down the control endpoint
* to tell the device to reset its own internal timestamp counters. Second,
* it tells the AEReader object to reset
* its
* timestamps, meaning to reset its unwrap counter.
*/
@Override
synchronized public void resetTimestamps() {
CypressFX3.log.info(this + ".resetTimestamps(): zeroing timestamps");
// send vendor request for device to reset timestamps
if (deviceHandle == null) {
throw new RuntimeException("device must be opened before sending this vendor request");
}
try {
final SPIConfigSequence configSequence = new SPIConfigSequence();
configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 2, 1);
configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 2, 0);
configSequence.sendConfigSequence();
}
catch (final HardwareInterfaceException e) {
CypressFX3.log.warning("CypressFX3.resetTimestamps: couldn't send vendor request to reset timestamps");
}
}
/**
* Is true if an overrun occured in the driver (> <code> AE_BUFFER_SIZE</code> events) during the period before the
* last time {@link #acquireAvailableEventsFromDriver } was called. This flag
* is cleared by {@link #acquireAvailableEventsFromDriver}, so you need to
* check it before you acquire the events.
* <p>
* If there is an overrun, the events grabbed are the most ancient; events after the overrun are discarded. The
* timestamps continue on but will probably be lagged behind what they should be.
*
* @return true if there was an overrun.
*/
@Override
public boolean overrunOccurred() {
return lastEventsAcquired.overrunOccuredFlag;
}
/**
* Closes the device. Never throws an exception.
*/
@Override
synchronized public void close() {
if (!isOpen()) {
return;
}
try {
setEventAcquisitionEnabled(false);
if (asyncStatusThread != null) {
asyncStatusThread.stopThread();
}
}
catch (final HardwareInterfaceException e) {
e.printStackTrace();
}
LibUsb.releaseInterface(deviceHandle, 0);
LibUsb.close(deviceHandle);
deviceHandle = null;
deviceDescriptor = null;
inEndpointEnabled = false;
isOpened = false;
}
// not really necessary to stop this thread, i believe, because close will
// unbind already according to usbio docs
public void stopAEReader() {
final AEReader reader = getAeReader();
if (reader != null) {
reader.stopThread();
setAeReader(null);
}
else {
CypressFX3.log.warning("null reader, nothing to stop");
}
}
/**
* @return true if inEndpoint was enabled.
* However, some other connection (e.g. biasgen) could have disabled
* the in transfers.
*/
public boolean isInEndpointEnabled() {
return inEndpointEnabled;
}
/**
* sends a vendor request to enable or disable in transfers of AEs
*
* @param inEndpointEnabled
* true to send vendor request to enable, false to send request
* to disable
*/
public void setInEndpointEnabled(final boolean inEndpointEnabled) throws HardwareInterfaceException {
CypressFX3.log.info("Setting IN endpoint enabled=" + inEndpointEnabled);
if (inEndpointEnabled) {
enableINEndpoint();
}
else {
disableINEndpoint();
}
}
public final static short FPGA_MUX = 0;
public final static short FPGA_DVS = 1; // GenericAERConfig, DVSAERConfig, AERKillConfig
public final static short FPGA_APS = 2;
public final static short FPGA_IMU = 3;
public final static short FPGA_EXTINPUT = 4;
public final static short FPGA_CHIPBIAS = 5; // Biases, Chip Config, Channel Config
public final static short FPGA_SYSINFO = 6;
public final static short FPGA_DAC = 7;
public final static short FPGA_SCANNER = 8;
public final static short FPGA_USB = 9;
public final static short FPGA_ADC = 10;
public class SPIConfigSequence {
private class SPIConfigParameter {
private final byte moduleAddr;
private final byte paramAddr;
private final byte[] param;
public SPIConfigParameter(final short moduleAddr, final short paramAddr, final int param) {
final byte[] configBytes = new byte[4];
configBytes[0] = (byte) ((param >>> 24) & 0x00FF);
configBytes[1] = (byte) ((param >>> 16) & 0x00FF);
configBytes[2] = (byte) ((param >>> 8) & 0x00FF);
configBytes[3] = (byte) ((param >>> 0) & 0x00FF);
this.moduleAddr = (byte) moduleAddr;
this.paramAddr = (byte) paramAddr;
this.param = configBytes;
}
public byte getModuleAddr() {
return moduleAddr;
}
public byte getParamAddr() {
return paramAddr;
}
public byte[] getParam() {
return param;
}
}
private final List<SPIConfigParameter> configList;
public SPIConfigSequence() {
configList = new ArrayList<>();
}
private boolean canAddConfig() {
// Max number of 6 bytes elements in 4096 bytes buffer is 682.
return (configList.size() < 682);
}
public void addConfig(final short moduleAddr, final short paramAddr, final int param) throws HardwareInterfaceException {
if (!canAddConfig()) {
// Send current config, clean up for new one.
sendConfigSequence();
}
configList.add(new SPIConfigParameter(moduleAddr, paramAddr, param));
}
public void sendConfigSequence() throws HardwareInterfaceException {
// Build byte buffer and send it. 6 bytes per config parameter.
final ByteBuffer buffer = BufferUtils.allocateByteBuffer(configList.size() * 6);
for (final SPIConfigParameter cfg : configList) {
buffer.put(cfg.getModuleAddr());
buffer.put(cfg.getParamAddr());
buffer.put(cfg.getParam());
}
sendVendorRequest(CypressFX3.VR_FPGA_CONFIG_MULTIPLE, (short) configList.size(), (short) 0, buffer);
clearConfig();
}
private void clearConfig() {
configList.clear();
}
}
protected int adjustHWParam(final short moduleAddr, final short paramAddr, int param) {
// No change by default.
return (param);
}
public synchronized void spiConfigSend(final short moduleAddr, final short paramAddr, int param) throws HardwareInterfaceException {
// Some values have to be adjusted based on hardware features, so we do that here.
param = adjustHWParam(moduleAddr, paramAddr, param);
final byte[] configBytes = new byte[4];
configBytes[0] = (byte) ((param >>> 24) & 0x00FF);
configBytes[1] = (byte) ((param >>> 16) & 0x00FF);
configBytes[2] = (byte) ((param >>> 8) & 0x00FF);
configBytes[3] = (byte) ((param >>> 0) & 0x00FF);
// System.out.println(String.format("SPI Config sent with modAddr=%d, paramAddr=%d, value=%d.\n", moduleAddr,
// paramAddr, param));
sendVendorRequest(CypressFX3.VR_FPGA_CONFIG, moduleAddr, paramAddr, configBytes);
//
// int returnedParam = 0;
//
// final ByteBuffer configBytesRecv = sendVendorRequestIN(CypressFX3.VR_FPGA_CONFIG, moduleAddr, paramAddr, 4);
//
// returnedParam |= (configBytesRecv.get(0) & 0x00FF) << 24;
// returnedParam |= (configBytesRecv.get(1) & 0x00FF) << 16;
// returnedParam |= (configBytesRecv.get(2) & 0x00FF) << 8;
// returnedParam |= (configBytesRecv.get(3) & 0x00FF) << 0;
//
// System.out.println(String.format("SPI Received back with modAddr=%d, paramAddr=%d, value=0x%x.\n", moduleAddr,
// paramAddr, returnedParam));
//
// if(returnedParam != param && (moduleAddr == 0 || moduleAddr == 1 || moduleAddr == 5 ))
// {
// System.out.println("SPI write error!\n");
// }
}
public synchronized int spiConfigReceive(final short moduleAddr, final short paramAddr) throws HardwareInterfaceException {
int returnedParam = 0;
final ByteBuffer configBytes = sendVendorRequestIN(CypressFX3.VR_FPGA_CONFIG, moduleAddr, paramAddr, 4);
returnedParam |= (configBytes.get(0) & 0x00FF) << 24;
returnedParam |= (configBytes.get(1) & 0x00FF) << 16;
returnedParam |= (configBytes.get(2) & 0x00FF) << 8;
returnedParam |= (configBytes.get(3) & 0x00FF) << 0;
return (returnedParam);
}
protected synchronized void enableINEndpoint() throws HardwareInterfaceException {
if (deviceHandle == null) {
CypressFX3.log.warning("CypressFX3.enableINEndpoint(): null USBIO device");
return;
}
final SPIConfigSequence configSequence = new SPIConfigSequence();
spiConfigSend(CypressFX3.FPGA_MUX, (short) 3, 1);
spiConfigSend(CypressFX3.FPGA_USB, (short) 0, 1);
spiConfigSend(CypressFX3.FPGA_MUX, (short) 1, 1);
spiConfigSend(CypressFX3.FPGA_MUX, (short) 0, 1);
//
// configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 3, 1); // Enable biasgen.
//
// configSequence.addConfig(CypressFX3.FPGA_USB, (short) 0, 1); // Enable USB.
//
// configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 1, 1); // Enable timestamps.
// configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 0, 1); // Enable mux.
//
// configSequence.sendConfigSequence();
inEndpointEnabled = true;
}
/**
* // stop endpoint sending events by sending vendor request 0xb4 to control
* endpoint 0
* // these requests are documented in firmware file FX2_to_extFIFO.c
*/
protected synchronized void disableINEndpoint() {
try {
spiConfigSend(CypressFX3.FPGA_EXTINPUT, (short) 0, 0); // Disable ext detector.
spiConfigSend(CypressFX3.FPGA_IMU, (short) 2, 0); // Disable IMU accel.
spiConfigSend(CypressFX3.FPGA_IMU, (short) 3, 0); // Disable IMU gyro.
spiConfigSend(CypressFX3.FPGA_IMU, (short) 4, 0); // Disable IMU temp.
spiConfigSend(CypressFX3.FPGA_APS, (short) 4, 0); // Disable APS.
spiConfigSend(CypressFX3.FPGA_DVS, (short) 3, 0); // Disable DVS.
spiConfigSend(CypressFX3.FPGA_MUX, (short) 1, 0); // Disable timestamps.
spiConfigSend(CypressFX3.FPGA_MUX, (short) 0, 0); // Disable mux.
spiConfigSend(CypressFX3.FPGA_USB, (short) 0, 0); // Disable USB.
spiConfigSend(CypressFX3.FPGA_MUX, (short) 3, 0); // Disable biasgen
// final SPIConfigSequence configSequence = new SPIConfigSequence();
// configSequence.addConfig(CypressFX3.FPGA_EXTINPUT, (short) 0, 0); // Disable ext detector.
// configSequence.addConfig(CypressFX3.FPGA_IMU, (short) 2, 0); // Disable IMU accel.
// configSequence.addConfig(CypressFX3.FPGA_IMU, (short) 3, 0); // Disable IMU gyro.
// configSequence.addConfig(CypressFX3.FPGA_IMU, (short) 4, 0); // Disable IMU temp.
// configSequence.addConfig(CypressFX3.FPGA_APS, (short) 4, 0); // Disable APS.
// configSequence.addConfig(CypressFX3.FPGA_DVS, (short) 3, 0); // Disable DVS.
//
// configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 1, 0); // Disable timestamps.
// configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 0, 0); // Disable mux.
//
// configSequence.addConfig(CypressFX3.FPGA_USB, (short) 0, 0); // Disable USB.
//
// configSequence.addConfig(CypressFX3.FPGA_MUX, (short) 3, 0); // Disable biasgen.
//
// configSequence.sendConfigSequence();
}
catch (final HardwareInterfaceException e) {
CypressFX3.log.info(
"disableINEndpoint: couldn't send vendor request to disable IN transfers--it could be that device is gone or sendor is OFF and and completing GPIF cycle");
}
inEndpointEnabled = false;
}
@Override
public PropertyChangeSupport getReaderSupport() {
return support;
}
/**
* This threads reads asynchronous status or other data from the device.
* It handles timestamp reset messages from the device and possibly other
* types of data.
* It fires PropertyChangeEvent {@link #PROPERTY_CHANGE_ASYNC_STATUS_MSG} on
* receiving a message
*
* @author tobi delbruck
* @see #getSupport()
*/
private class AsyncStatusThread {
USBTransferThread usbTransfer;
public void stopThread() {
usbTransfer.interrupt();
try {
usbTransfer.join();
}
catch (final InterruptedException e) {
CypressFX3.log.severe("Failed to join AsyncStatusThread");
}
}
}
private int aeReaderFifoSize = CypressFX3.prefs.getInt("CypressFX3.AEReader.fifoSize", 8192);
/**
* sets the buffer size for the aereader thread. optimal size depends on
* event rate, for high event
* rates, at least 8k or 16k bytes should be chosen, and low event rates
* need smaller
* buffer size to produce suitable frame rates
*/
public void setAEReaderFifoSize(final int size) {
aeReaderFifoSize = size;
CypressFX3.prefs.putInt("CypressFX3.AEReader.fifoSize", size);
}
private int aeReaderNumBuffers = CypressFX3.prefs.getInt("CypressFX3.AEReader.numBuffers", 8);
/** sets the number of buffers for the aereader thread. */
public void setAEReaderNumBuffers(final int number) {
aeReaderNumBuffers = number;
CypressFX3.prefs.putInt("CypressFX3.AEReader.numBuffers", number);
}
/**
* AE reader class. the thread continually reads events into buffers. when a
* buffer is read, ProcessData transfers
* and transforms the buffer data to AE address
* and timestamps information and puts it in the addresses and timestamps
* arrays. a call to
* acquireAvailableEventsFromDriver copies the events to enw user
* arrays that can be accessed by getEvents() (this packet is also returned
* by {@link #acquireAvailableEventsFromDriver}). The relevant methods are
* synchronized so are thread safe.
*/
public class AEReader implements ReaderBufferControl {
/**
* the number of capture buffers for the buffer pool for the translated
* address-events.
* These buffers allow for smoother access to buffer space by the event
* capture thread
*/
private int numBuffers;
/**
* size of FIFOs in bytes used in AEReader for event capture from
* device.
* This does not have to be the same size as the FIFOs in the CypressFX3
* (512 bytes). If it is too small, then
* there
* are frequent thread context switches that can greatly slow down
* rendering loops.
*/
private int fifoSize;
USBTransferThread usbTransfer;
CypressFX3 monitor;
public AEReader(final CypressFX3 m) throws HardwareInterfaceException {
monitor = m;
fifoSize = monitor.aeReaderFifoSize;
numBuffers = monitor.aeReaderNumBuffers;
}
public void startThread() {
if (!isOpen()) {
try {
open();
}
catch (final HardwareInterfaceException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
CypressFX3.log.info("Starting AEReader");
usbTransfer = new USBTransferThread(monitor.deviceHandle, CypressFX3.AE_MONITOR_ENDPOINT_ADDRESS, LibUsb.TRANSFER_TYPE_BULK,
new ProcessAEData(), getNumBuffers(), getFifoSize(), null, null, new Runnable() {
@Override
public void run() {
final SwingWorker<Void, Void> shutdownWorker = new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
monitor.close();
return (null);
}
};
shutdownWorker.execute();
}
});
usbTransfer.setName("AEReaderThread");
usbTransfer.start();
getSupport().firePropertyChange("readerStarted", false, true);
}
public void stopThread() {
if(usbTransfer==null){
log.warning("USB transfer thread became null before stopThread was called; doing nothing");
return;
}
usbTransfer.interrupt();
try {
usbTransfer.join();
}
catch (final InterruptedException e) {
CypressFX3.log.severe("Failed to join AEReaderThread");
}
}
@Override
public String toString() {
return "AEReader for " + CypressFX3.this;
}
/**
* Subclasses must override this method to process the raw data to write
* to the raw event packet buffers.
*
* @param buf
* the raw byte buffers
*/
protected void translateEvents(final ByteBuffer buffer) {
CypressFX3.log.severe("Error: This method should never be called, it must be overridden!");
}
class ProcessAEData implements RestrictedTransferCallback {
@Override
public void prepareTransfer(final RestrictedTransfer transfer) {
// Nothing to do here.
}
/**
* Called on completion of read on a data buffer is received from
* USBIO driver.
*
* @param Buf
* the data buffer with raw data
*/
@Override
public void processTransfer(final RestrictedTransfer transfer) {
synchronized (aePacketRawPool) {
if (transfer.status() == LibUsb.TRANSFER_COMPLETED) {
usbPacketStatistics.addSample(transfer);
translateEvents(transfer.buffer());
if ((chip != null) && (chip.getFilterChain() != null)
&& (chip.getFilterChain().getProcessingMode() == FilterChain.ProcessingMode.ACQUISITION)) {
// here we do the realTimeFiltering. We finished
// capturing this buffer's worth of events,
// now process them apply realtime filters and
// realtime (packet level) mapping
// synchronize here so that rendering thread doesn't
// swap the buffer out from under us while
// we process these events
// aePacketRawPool.writeBuffer is also synchronized
// so we the same lock twice which is ok
final AEPacketRaw buffer = aePacketRawPool.writeBuffer();
final int[] addresses = buffer.getAddresses();
final int[] timestamps = buffer.getTimestamps();
realTimeFilter(addresses, timestamps);
}
}
else {
CypressFX3.log.warning("ProcessAEData: Bytes transferred: " + transfer.actualLength() + " Status: "
+ LibUsb.errorName(transfer.status()));
}
}
}
}
/** size of CypressFX3 USB fifo's in bytes. */
public static final int CYPRESS_FIFO_SIZE = 512;
@Override
public int getFifoSize() {
return fifoSize;
}
@Override
public void setFifoSize(int fifoSize) {
if (fifoSize < AEReader.CYPRESS_FIFO_SIZE) {
CypressFX3.log.warning("CypressFX3 fifo size clipped to device FIFO size " + AEReader.CYPRESS_FIFO_SIZE);
fifoSize = AEReader.CYPRESS_FIFO_SIZE;
}
this.fifoSize = fifoSize;
usbTransfer.setBufferSize(fifoSize);
CypressFX3.prefs.putInt("CypressFX3.AEReader.fifoSize", fifoSize);
}
@Override
public int getNumBuffers() {
return numBuffers;
}
@Override
public void setNumBuffers(final int numBuffers) {
this.numBuffers = numBuffers;
usbTransfer.setBufferNumber(numBuffers);
CypressFX3.prefs.putInt("CypressFX3.AEReader.numBuffers", numBuffers);
}
/**
* Applies the filterChain processing on the most recently captured
* data. The processing is done
* by extracting the events just captured and then applying the filter
* chain.
* <strong>The filter outputs are discarded and
* will not be visble in the rendering of the chip output, but may be
* used for motor control or other purposes.
* </strong>
* <p>
* TODO: at present this processing is redundant in that the most recently captured events are copied to a
* different AEPacketRaw, extracted to an EventPacket, and then processed. This effort is duplicated later in
* rendering. This should be fixed somehow.
*
* @param addresses
* the raw input addresses; these are filtered in place
* @param timestamps
* the input timestamps
*/
private void realTimeFilter(final int[] addresses, final int[] timestamps) {
if (!chip.getFilterChain().isAnyFilterEnabled()) {
return;
}
final int nevents = getNumRealTimeEvents();
// initialize packets
if (realTimeRawPacket == null) {
realTimeRawPacket = new AEPacketRaw(nevents); // TODO: expensive
}
else {
realTimeRawPacket.ensureCapacity(nevents);// // copy data to
// real time raw
// packet
// if(addresses==null || timestamps==null){
// log.warning("realTimeFilter: addresses or timestamp array became null");
// }else{
}
try {
System.arraycopy(addresses, realTimeEventCounterStart, realTimeRawPacket.getAddresses(), 0, nevents);
System.arraycopy(timestamps, realTimeEventCounterStart, realTimeRawPacket.getTimestamps(), 0, nevents);
}
catch (final IndexOutOfBoundsException e) {
e.printStackTrace();
}
realTimeEventCounterStart = eventCounter;
// System.out.println("RealTimeEventCounterStart: " +
// realTimeEventCounterStart + " nevents " + nevents +
// " eventCounter " + eventCounter);
realTimeRawPacket.setNumEvents(nevents);
// init extracted packet
// if(realTimePacket==null)
// realTimePacket=new EventPacket(chip.getEventClass());
// extract events for this filter. This duplicates later effort
// during rendering and should be fixed for
// later.
// at present this may mess up everything else because the output
// packet is reused.
// hack for stereo hardware interfaces - for real time processing we
// must label the eye bit here based on
// which eye our hardware
// interface is. note the events are labeled here and the real time
// processing method is called for each low
// level hardware interface.
// But each call will only getString events from one eye. it is
// important that the filterPacket method be
// sychronized (thread safe) because the
// filter object may getString called by both AEReader threads at
// the "same time"
if (chip.getHardwareInterface() instanceof StereoPairHardwareInterface) {
final StereoPairHardwareInterface stereoInterface = (StereoPairHardwareInterface) chip.getHardwareInterface();
if (stereoInterface.getAemonLeft() == CypressFX3.this) {
stereoInterface.labelLeftEye(realTimeRawPacket);
}
else {
stereoInterface.labelRightEye(realTimeRawPacket);
}
}
// regardless, we now extract to typed events for example and
// process
realTimePacket = chip.getEventExtractor().extractPacket(realTimeRawPacket); // ,realTimePacket);
realTimePacket.setRawPacket(realTimeRawPacket);
try {
getChip().getFilterChain().filterPacket(realTimePacket);
}
catch (final Exception e) {
CypressFX3.log.warning(e.toString() + ": disabling all filters");
e.printStackTrace();
for (final EventFilter f : getChip().getFilterChain()) {
f.setFilterEnabled(false);
}
}
// we don't do following because the results are an AEPacketRaw that
// still needs to be written to
// addresses/timestamps
// and this is not done yet. at present results of realtime
// filtering are just not rendered at all.
// that means that user will see raw events, e.g. if
// BackgroundActivityFilter is used, then user will still
// see all
// events because the filters are not applied for normal rendering.
// (If they were applied, then the filters
// would
// be in a funny state becaues they would process the same data more
// than once and out of order, resulting
// in all kinds
// of problems.)
// However, the graphical annotations (like the boxes drawn around
// clusters in RectangularClusterTracker)
// done by the real time processing are still shown when the
// rendering thread calls the
// annotate methods.
// chip.getEventExtractor().reconstructRawPacket(realTimePacket);
}
@Override
public PropertyChangeSupport getReaderSupport() {
return support;
}
}
private int getNumRealTimeEvents() {
return eventCounter - realTimeEventCounterStart;
}
/**
* Allocates internal memory for transferring data from reader to consumer,
* e.g. rendering.
*/
protected void allocateAEBuffers() {
synchronized (aePacketRawPool) {
aePacketRawPool.allocateMemory();
}
}
/**
* @return the size of the double buffer raw packet for AEs
*/
@Override
public int getAEBufferSize() {
return aeBufferSize; // aePacketRawPool.writeBuffer().getCapacity();
}
/**
* set the size of the raw event packet buffer. Default is AE_BUFFER_SIZE.
* You can set this larger if you
* have overruns because your host processing (e.g. rendering) is taking too
* long.
* <p>
* This call discards collected events.
*
* @param size
* of buffer in events
*/
@Override
public void setAEBufferSize(final int size) {
if ((size < 1000) || (size > 2000000)) {
CypressFX3.log
.warning("ignoring unreasonable aeBufferSize of " + size + ", choose a more reasonable size between 1000 and 1000000");
return;
}
aeBufferSize = size;
CypressFX3.prefs.putInt("CypressFX3.aeBufferSize", aeBufferSize);
allocateAEBuffers();
}
/**
* start or stops the event acquisition. sends appropriate vendor request to
* device and starts or stops the AEReader.
* Thread-safe on hardware interface.
*
* @param enable
* boolean to enable or disable event acquisition
*/
@Override
public synchronized void setEventAcquisitionEnabled(final boolean enable) throws HardwareInterfaceException {
// Start reader before sending data enable commands.
if (enable) {
startAEReader();
}
else {
stopAEReader();
}
setInEndpointEnabled(enable);
}
@Override
public boolean isEventAcquisitionEnabled() {
return isInEndpointEnabled();
}
@Override
public String getTypeName() {
return "CypressFX3";
}
/** the first USB string descriptor (Vendor name) (if available) */
protected String stringDescriptor1 = null;
/** the second USB string descriptor (Product name) (if available) */
protected String stringDescriptor2 = null;
/** the third USB string descriptor (Serial number) (if available) */
protected String stringDescriptor3 = null;
/**
* The number of string desriptors - all devices have at least two (Vendor
* and Product strings) but some may have in
* addition
* a third serial number string. Default value is 2. Initialized to zero
* until device descriptors have been
* obtained.
*/
protected int numberOfStringDescriptors = 0;
/**
* returns number of string descriptors
*
* @return number of string descriptors: 2 for TmpDiff128, 3 for
* MonitorSequencer
*/
public int getNumberOfStringDescriptors() {
return numberOfStringDescriptors;
}
/** the USBIO device descriptor */
protected DeviceDescriptor deviceDescriptor = null;
/**
* checks if device has a string identifier that is a non-empty string
*
* @return false if not, true if there is one
*/
private boolean hasStringIdentifier() {
// getString string descriptor
final String stringDescriptor1 = LibUsb.getStringDescriptor(deviceHandle, (byte) 1);
if (stringDescriptor1 == null) {
return false;
}
else if (stringDescriptor1.length() > 0) {
return true;
}
return false;
}
/**
* Constructs a new USB connection and opens it. Does NOT start event
* acquisition.
*
* @see #setEventAcquisitionEnabled
* @throws HardwareInterfaceException
* if there is an error opening device
* @see #open_minimal_close()
*/
@Override
synchronized public void open() throws HardwareInterfaceException {
// device has already been UsbIo Opened by now, in factory
// opens the USBIOInterface device, configures it, binds a reader thread
// with buffer pool to read from the
// device and starts the thread reading events.
// we got a UsbIo object when enumerating all devices and we also made a
// device list. the device has already
// been
// opened from the UsbIo viewpoint, but it still needs firmware
// download, setting up pipes, etc.
if (isOpen()) {
return;
}
int status;
// Open device.
if (deviceHandle == null) {
deviceHandle = new DeviceHandle();
status = LibUsb.open(device, deviceHandle);
if (status != LibUsb.SUCCESS) {
throw new HardwareInterfaceException("open(): failed to open device: " + LibUsb.errorName(status));
}
}
// Check for blank devices (must first get device descriptor).
if (deviceDescriptor == null) {
deviceDescriptor = new DeviceDescriptor();
LibUsb.getDeviceDescriptor(device, deviceDescriptor);
}
if (isBlankDevice()) { // TODO throws null pointer exception if deviceDescriptor is not obtained above, which
// tobi has seen occur
CypressFX3.log.warning("open(): blank device detected, downloading preferred firmware");
isOpened = true;
CypressFX3.log.severe("USE FLASHY FOR FIRMWARE UPLOAD!");
isOpened = false;
boolean success = false;
int triesLeft = 10;
status = 0;
while (!success && (triesLeft > 0)) {
try {
Thread.sleep(1000);
}
catch (final InterruptedException e) {
}
try {
LibUsb.close(deviceHandle);
status = LibUsb.open(device, deviceHandle);
if (status != LibUsb.SUCCESS) {
triesLeft--;
}
else {
success = true;
}
}
catch (final IllegalStateException e) {
// Ignore.
}
}
if (!success) {
throw new HardwareInterfaceException(
"open(): couldn't reopen device after firmware download and re-enumeration: " + LibUsb.errorName(status));
}
else {
throw new HardwareInterfaceException(
"open(): device firmware downloaded successfully, a new instance must be constructed by the factory using the new VID/PID settings");
}
}
// Initialize device.
if (deviceDescriptor.bNumConfigurations() != 1) {
throw new HardwareInterfaceException(
"number of configurations=" + deviceDescriptor.bNumConfigurations() + " is not 1 like it should be");
}
final IntBuffer activeConfig = BufferUtils.allocateIntBuffer();
try {
LibUsb.getConfiguration(deviceHandle, activeConfig);
} catch (IllegalStateException e) {
log.log(Level.SEVERE, "Exception try to LibUsb.getConfiguration: "+ e.toString(), e);
return;
}
if (activeConfig.get() != 1) {
LibUsb.setConfiguration(deviceHandle, 1);
}
try {
LibUsb.claimInterface(deviceHandle, 0);
} catch (Exception e) {
log.log(Level.SEVERE, "Exception try to LibUsb.claimInterface: " + e.toString(), e);
return;
}
populateDescriptors();
isOpened = true;
CypressFX3.log.info("open(): device opened");
if (LibUsb.getDeviceSpeed(device) == LibUsb.SPEED_FULL) {
CypressFX3.log.warning("Device is not operating at USB 2.0 High Speed, performance will be limited to about 300 keps");
}
// start the thread that listens for device status information.
// This is only preset on FX3 devices.
// if (getPID() == DAViSFX3HardwareInterface.PID_FX3) {
// asyncStatusThread = new AsyncStatusThread(this);
// asyncStatusThread.startThread();
// TODO: fix USBTransferThread to only use one thread to handle USB events.
// }
}
/**
* Opens the device just enough to read the device descriptor but does not
* start the reader or writer
* thread. If the device does not have a string descriptor it is assumed
* that firmware must be downloaded to
* device RAM and this is done automatically. The device is <strong>not
* configured by this method. Vendor requests
* and
* probably other functionality will not be available.</strong>. The device
* is left open this method returns.
*
* @throws net.sf.jaer.hardwareinterface.HardwareInterfaceException
* @see #open()
*/
synchronized protected void open_minimal_close() throws HardwareInterfaceException {
// device has already been UsbIo Opened by now, in factory
// opens the USBIOInterface device, configures it, binds a reader thread
// with buffer pool to read from the
// device and starts the thread reading events.
// we got a UsbIo object when enumerating all devices and we also made a
// device list. the device has already
// been
// opened from the UsbIo viewpoint, but it still needs firmware
// download, setting up pipes, etc.
if (isOpen()) {
return;
}
int status;
// Open device.
if (deviceHandle == null) {
deviceHandle = new DeviceHandle();
status = LibUsb.open(device, deviceHandle);
if (status != LibUsb.SUCCESS) {
throw new HardwareInterfaceException("open_minimal_close(): failed to open device: " + LibUsb.errorName(status));
}
}
// Check for blank devices (must first get device descriptor).
if (deviceDescriptor == null) {
deviceDescriptor = new DeviceDescriptor();
LibUsb.getDeviceDescriptor(device, deviceDescriptor);
}
if (isBlankDevice()) {
throw new BlankDeviceException("Blank Cypress FX2");
}
if (!hasStringIdentifier()) { // TODO: does this really ever happen, a
// non-blank device with invalid fw?
CypressFX3.log.warning("open_minimal_close(): blank device detected, downloading preferred firmware");
CypressFX3.log.severe("USE FLASHY FOR FIRMWARE UPLOAD!");
boolean success = false;
int triesLeft = 10;
status = 0;
while (!success && (triesLeft > 0)) {
try {
Thread.sleep(1000);
}
catch (final InterruptedException e) {
}
LibUsb.close(deviceHandle);
status = LibUsb.open(device, deviceHandle);
if (status != LibUsb.SUCCESS) {
triesLeft--;
}
else {
success = true;
}
}
if (!success) {
throw new HardwareInterfaceException(
"open_minimal_close(): couldn't reopen device after firmware download and re-enumeration: " + LibUsb.errorName(status));
}
else {
throw new HardwareInterfaceException(
"open_minimal_close(): device firmware downloaded successfully, a new instance must be constructed by the factory using the new VID/PID settings");
}
}
populateDescriptors();
// And close opened resources again.
LibUsb.close(deviceHandle);
deviceHandle = null;
deviceDescriptor = null;
}
/**
* return the string USB descriptors for the device
*
* @return String[] of length 2 or 3 of USB descriptor strings.
*/
@Override
public String[] getStringDescriptors() {
if (stringDescriptor1 == null) {
CypressFX3.log.warning("USBAEMonitor: getStringDescriptors called but device has not been opened");
final String[] s = new String[numberOfStringDescriptors];
for (int i = 0; i < numberOfStringDescriptors; i++) {
s[i] = "";
}
return s;
}
final String[] s = new String[numberOfStringDescriptors];
s[0] = (stringDescriptor1 == null) ? ("") : (stringDescriptor1);
s[1] = (stringDescriptor2 == null) ? ("") : (stringDescriptor2);
if (numberOfStringDescriptors == 3) {
s[2] = (stringDescriptor3 == null) ? ("") : (stringDescriptor3);
}
return s;
}
@Override
public short getVID_THESYCON_FX2_CPLD() {
if (deviceDescriptor == null) {
CypressFX3.log.warning("USBAEMonitor: getVID called but device has not been opened");
return 0;
}
// int[] n=new int[2]; n is never used
return deviceDescriptor.idVendor();
}
@Override
public short getPID() {
if (deviceDescriptor == null) {
CypressFX3.log.warning("USBAEMonitor: getPID called but device has not been opened");
return 0;
}
return deviceDescriptor.idProduct();
}
/**
* @return bcdDevice (the binary coded decimel device version
*/
@Override
public short getDID() { // this is not part of USB spec in device
// descriptor.
if (deviceDescriptor == null) {
CypressFX3.log.warning("USBAEMonitor: getDID called but device has not been opened");
return 0;
}
return deviceDescriptor.bcdDevice();
}
/**
* reports if interface is {@link #open}.
*
* @return true if already open
*/
@Override
synchronized public boolean isOpen() {
return isOpened;
}
/**
* @return timestamp tick in us
* NOTE: DOES NOT RETURN THE TICK OF THE USBAERmini2 board
*/
@Override
final public int getTimestampTickUs() {
return TICK_US;
}
/**
* returns last events from {@link #acquireAvailableEventsFromDriver}
*
* @return the event packet
*/
@Override
public AEPacketRaw getEvents() {
return lastEventsAcquired;
}
/**
* Sends a vendor request without any data packet, value and index are set
* to zero. This is a blocking method.
*
* @param request
* the vendor request byte, identifies the request on the device
*/
synchronized public void sendVendorRequest(final byte request) throws HardwareInterfaceException {
sendVendorRequest(request, (short) 0, (short) 0);
}
/**
* Sends a vendor request without any data packet but with request, value
* and index. This is a blocking method.
*
* @param request
* the vendor request byte, identifies the request on the device
* @param value
* the value of the request (bValue USB field)
* @param index
* the "index" of the request (bIndex USB field)
*/
synchronized public void sendVendorRequest(final byte request, final short value, final short index) throws HardwareInterfaceException {
sendVendorRequest(request, value, index, (ByteBuffer) null);
}
/**
* Sends a vendor request with a given byte[] as data. This is a blocking
* method.
*
* @param request
* the vendor request byte, identifies the request on the device
* @param value
* the value of the request (bValue USB field)
* @param index
* the "index" of the request (bIndex USB field)
* @param bytes
* the data which is to be transmitted to the device
*/
synchronized public void sendVendorRequest(final byte request, final short value, final short index, final byte[] bytes)
throws HardwareInterfaceException {
sendVendorRequest(request, value, index, bytes, 0, bytes.length);
}
/**
* Sends a vendor request with a given byte[] as data. This is a blocking
* method.
*
* @param request
* the vendor request byte, identifies the request on the device
* @param value
* the value of the request (bValue USB field)
* @param index
* the "index" of the request (bIndex USB field)
* @param bytes
* the data which is to be transmitted to the device
* @param pos
* position at which to start consuming the bytes array
* @param length
* number of bytes to copy, starting at position pos
*/
synchronized public void sendVendorRequest(final byte request, final short value, final short index, final byte[] bytes, final int pos,
final int length) throws HardwareInterfaceException {
final ByteBuffer dataBuffer = BufferUtils.allocateByteBuffer(length);
dataBuffer.put(bytes, pos, length);
sendVendorRequest(request, value, index, dataBuffer);
}
/**
* Sends a vendor request with data (including special bits). This is a
* blocking method.
*
* @param requestType
* the vendor requestType byte (used for special cases, usually
* 0)
* @param request
* the vendor request byte, identifies the request on the device
* @param value
* the value of the request (bValue USB field)
* @param index
* the "index" of the request (bIndex USB field)
* @param dataBuffer
* the data which is to be transmitted to the device (null means
* no data)
*/
synchronized public void sendVendorRequest(final byte request, final short value, final short index, ByteBuffer dataBuffer)
throws HardwareInterfaceException {
if (!isOpen()) {
open();
}
if (dataBuffer == null) {
dataBuffer = BufferUtils.allocateByteBuffer(0);
}
// System.out.println(String.format("Sent VR %X, wValue %X, wIndex %X, wLength %d.\n", request, value, index,
// dataBuffer.limit()));
final byte bmRequestType = (byte) (LibUsb.ENDPOINT_OUT | LibUsb.REQUEST_TYPE_VENDOR | LibUsb.RECIPIENT_DEVICE);
final int status = LibUsb.controlTransfer(deviceHandle, bmRequestType, request, value, index, dataBuffer, 0);
if (status < LibUsb.SUCCESS) {
throw new HardwareInterfaceException(
"Unable to send vendor OUT request " + String.format("0x%x", request) + ": " + LibUsb.errorName(status));
}
if (status != dataBuffer.capacity()) {
throw new HardwareInterfaceException(
"Wrong number of bytes transferred, wanted: " + dataBuffer.capacity() + ", got: " + status);
}
}
/**
* Sends a vendor request to receive (IN direction) data. This is a blocking
* method.
*
* @param request
* the vendor request byte, identifies the request on the device
* @param value
* the value of the request (bValue USB field)
* @param index
* the "index" of the request (bIndex USB field)
* @param dataLength
* amount of data to receive, determines size of returned buffer
* (must be greater than 0)
* @return a buffer containing the data requested from the device
*/
synchronized public ByteBuffer sendVendorRequestIN(final byte request, final short value, final short index, final int dataLength)
throws HardwareInterfaceException {
if (dataLength == 0) {
throw new HardwareInterfaceException("Unable to send vendor IN request with dataLength of zero!");
}
if (!isOpen()) {
open();
}
final ByteBuffer dataBuffer = BufferUtils.allocateByteBuffer(dataLength);
final byte bmRequestType = (byte) (LibUsb.ENDPOINT_IN | LibUsb.REQUEST_TYPE_VENDOR | LibUsb.RECIPIENT_DEVICE);
final int status = LibUsb.controlTransfer(deviceHandle, bmRequestType, request, value, index, dataBuffer, 0);
if (status < LibUsb.SUCCESS) {
throw new HardwareInterfaceException(
"Unable to send vendor IN request " + String.format("0x%x", request) + ": " + LibUsb.errorName(status));
}
if (status != dataLength) {
throw new HardwareInterfaceException("Wrong number of bytes transferred, wanted: " + dataLength + ", got: " + status);
}
// Update ByteBuffer internal limit to show how much was successfully
// read.
// usb4java never touches the ByteBuffer's internals by design, so we do
// it here.
dataBuffer.limit(dataLength);
return (dataBuffer);
}
public AEReader getAeReader() {
return aeReader;
}
public void setAeReader(final AEReader aeReader) {
this.aeReader = aeReader;
}
@Override
public int getFifoSize() {
if (aeReader == null) {
return -1;
}
else {
return aeReader.getFifoSize();
}
}
@Override
public void setFifoSize(final int fifoSize) {
if (aeReader == null) {
return;
}
aeReader.setFifoSize(fifoSize);
}
@Override
public int getNumBuffers() {
if (aeReader == null) {
return 0;
}
else {
return aeReader.getNumBuffers();
}
}
@Override
public void setNumBuffers(final int numBuffers) {
if (aeReader == null) {
return;
}
aeReader.setNumBuffers(numBuffers);
}
@Override
public void setChip(final AEChip chip) {
this.chip = chip;
}
@Override
public AEChip getChip() {
return chip;
}
/** Resets the USB device using USBIO resetDevice */
public void resetUSB() {
if (deviceHandle == null) {
return;
}
final int status = LibUsb.resetDevice(deviceHandle);
if (status != LibUsb.SUCCESS) {
CypressFX3.log.warning("Error resetting device: " + LibUsb.errorName(status));
}
}
/**
* Checks for blank cypress VID/PID.
* Device deviceDescriptor must be populated before calling this method.
*
* @return true if blank
*/
protected boolean isBlankDevice() throws HardwareInterfaceException {
try {
if ((deviceDescriptor.idVendor() == CypressFX3.VID_BLANK) && (deviceDescriptor.idProduct() == CypressFX3.PID_BLANK)) {
// log.warning("blank CypressFX3 detected");
return true;
}
return false;
} catch (java.lang.IllegalStateException ex) {
throw new HardwareInterfaceException("exception when checking for blank device ", ex);
}
}
@Override
public void setShowUsbStatistics(boolean yes) {
usbPacketStatistics.setShowUsbStatistics(yes);
}
@Override
public void setPrintUsbStatistics(boolean yes) {
usbPacketStatistics.setPrintUsbStatistics(yes);
}
@Override
public boolean isShowUsbStatistics() {
return usbPacketStatistics.isShowUsbStatistics();
}
@Override
public boolean isPrintUsbStatistics() {
return usbPacketStatistics.isPrintUsbStatistics();
}
private AtomicBoolean isMaster = new AtomicBoolean(true);
public boolean isTimestampMaster() {
return isMaster.get();
}
protected void updateTimestampMasterStatus() {
final SwingWorker<Void, Void> masterUpdateWorker = new SwingWorker<Void, Void>() {
@Override
public Void doInBackground() {
try {
final int isMasterSPI = spiConfigReceive(CypressFX3.FPGA_SYSINFO, (short) 2);
isMaster.set(isMasterSPI != 0);
}
catch (HardwareInterfaceException e) {
// Ignore exceptions.
}
return (null);
}
};
masterUpdateWorker.execute();
}
}
| lgpl-2.1 |
geotools/geotools | modules/library/main/src/main/java/org/geotools/data/store/FilteringFeatureCollection.java | 3718 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2016, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.data.store;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.geotools.data.DataUtilities;
import org.geotools.data.FeatureReader;
import org.geotools.data.collection.DelegateFeatureReader;
import org.geotools.feature.FeatureCollection;
import org.geotools.feature.FeatureIterator;
import org.geotools.feature.collection.DecoratingFeatureCollection;
import org.geotools.filter.visitor.BindingFilterVisitor;
import org.geotools.geometry.jts.ReferencedEnvelope;
import org.opengis.feature.Feature;
import org.opengis.feature.type.FeatureType;
import org.opengis.filter.Filter;
import org.opengis.filter.sort.SortBy;
/**
* Decorates a feature collection with one that filters content.
*
* @author Justin Deoliveira, The Open Planning Project
*/
public class FilteringFeatureCollection<T extends FeatureType, F extends Feature>
extends DecoratingFeatureCollection<T, F> {
/** The original feature collection. */
FeatureCollection<T, F> delegate;
/** the filter */
Filter filter;
public FilteringFeatureCollection(FeatureCollection<T, F> delegate, Filter filter) {
super(delegate);
this.delegate = delegate;
this.filter = (Filter) filter.accept(new BindingFilterVisitor(delegate.getSchema()), null);
}
@Override
public FeatureCollection<T, F> subCollection(Filter filter) {
throw new UnsupportedOperationException();
}
@Override
public FeatureCollection<T, F> sort(SortBy order) {
throw new UnsupportedOperationException();
}
@Override
public int size() {
int count = 0;
try (FeatureIterator<F> i = features()) {
while (i.hasNext()) {
count++;
i.next();
}
return count;
}
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public Object[] toArray() {
return toArray(new Object[size()]);
}
@Override
public <O> O[] toArray(O[] a) {
List<F> list = new ArrayList<>();
try (FeatureIterator<F> i = features()) {
while (i.hasNext()) {
list.add(i.next());
}
return list.toArray(a);
}
}
@Override
public boolean contains(Object o) {
return delegate.contains(o) && filter.evaluate(o);
}
@Override
public boolean containsAll(Collection<?> c) {
for (Object o : c) {
if (!contains(o)) {
return false;
}
}
return true;
}
@Override
public FeatureIterator<F> features() {
return new FilteringFeatureIterator<>(delegate.features(), filter);
}
public FeatureReader<T, F> reader() throws IOException {
return new DelegateFeatureReader<>(getSchema(), features());
}
@Override
public ReferencedEnvelope getBounds() {
// calculate manually
return DataUtilities.bounds(this);
}
}
| lgpl-2.1 |
teto/libnl_old | python/netlink/route/links/bridge.py | 2038 | #
# Copyright (c) 2011 Thomas Graf <tgraf@suug.ch>
#
"""VLAN network link
"""
from __future__ import absolute_import
from ... import core as netlink
from .. import capi as capi
# Bridge flags
# RTNL_BRIDGE_HAIRPIN_MODE = 0x0001,
# RTNL_BRIDGE_BPDU_GUARD = 0x0002,
# RTNL_BRIDGE_ROOT_BLOCK = 0x0004,
# RTNL_BRIDGE_FAST_LEAVE = 0x0008
class BridgeLink(object):
def __init__(self, link):
if not capi.rtnl_link_is_bridge(link):
raise ValueError("Passed link must be a bridge")
self._link = link
@property
@netlink.nlattr(type=str)
def flags(self):
""" Bridge flags
Setting this property will *Not* reset flags to value you supply in
Examples:
link.flags = '+xxx' # add xxx flag
link.flags = 'xxx' # exactly the same
link.flags = '-xxx' # remove xxx flag
link.flags = [ '+xxx', '-yyy' ] # list operation
"""
flags = capi.rtnl_link_bridge_get_flags(self._link)
# TODO split flags into strings
return
# capi.rtnl_link_vlan_flags2str(flags, 256)[0].split(',')
def _set_flag(self, flag):
if flag.startswith('-'):
i = capi.rtnl_link_vlan_str2flags(flag[1:])
capi.rtnl_link_vlan_unset_flags(self._link, i)
elif flag.startswith('+'):
i = capi.rtnl_link_vlan_str2flags(flag[1:])
capi.rtnl_link_vlan_set_flags(self._link, i)
else:
i = capi.rtnl_link_vlan_str2flags(flag)
capi.rtnl_link_vlan_set_flags(self._link, i)
@flags.setter
def flags(self, value):
if type(value) is list:
for flag in value:
self._set_flag(flag)
else:
self._set_flag(value)
###################################################################
# TODO:
# - ingress map
# - egress map
def brief(self):
return 'bridge-id {0}'.format(self.id)
def init(link):
return BridgeLink(link._rtnl_link)
# return link.vlan
| lgpl-2.1 |
geotools/geotools | modules/plugin/coverage-multidim/netcdf/src/main/java/org/geotools/imageio/netcdf/cv/TimeCoordinateVariable.java | 4407 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2014, Open Source Geospatial Foundation (OSGeo)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
package org.geotools.imageio.netcdf.cv;
import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.logging.Logger;
import org.geotools.imageio.netcdf.utilities.NetCDFCRSUtilities;
import org.geotools.imageio.netcdf.utilities.NetCDFTimeUtilities;
import org.geotools.imageio.netcdf.utilities.NetCDFUtilities;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import ucar.nc2.Attribute;
import ucar.nc2.constants.AxisType;
import ucar.nc2.dataset.CoordinateAxis;
/**
* @author Simone Giannecchini, GeoSolutions SAS
* @author Niels Charlier TODO caching
*/
class TimeCoordinateVariable extends CoordinateVariable<Date> {
/** The LOGGER for this class. */
private static final Logger LOGGER = Logger.getLogger(TimeCoordinateVariable.class.toString());
private String units;
private int baseTimeUnits;
private Date epoch;
/** */
public TimeCoordinateVariable(CoordinateAxis coordinateAxis) {
super(Date.class, coordinateAxis);
units = coordinateAxis.getUnitsString();
/*
* Gets the axis origin. In the particular case of time axis, units are typically written in the form "days since 1990-01-01
* 00:00:00". We extract the part before "since" as the units and the part after "since" as the date.
*/
String origin = null;
final String[] unitsParts = units.split("(?i)\\s+since\\s+");
if (unitsParts.length == 2) {
units = unitsParts[0].trim();
origin = unitsParts[1].trim();
} else {
final Attribute attribute = coordinateAxis.findAttribute("time_origin");
if (attribute != null) {
origin = attribute.getStringValue();
}
}
baseTimeUnits = NetCDFTimeUtilities.getTimeUnits(units, null);
if (baseTimeUnits == -1) {
throw new IllegalArgumentException(
"Couldn't determine time units from unit string '" + units + "'");
}
if (origin != null) {
origin = NetCDFTimeUtilities.trimFractionalPart(origin);
// add 0 digits if absent
origin = NetCDFTimeUtilities.checkDateDigits(origin);
try {
epoch =
(Date)
NetCDFUtilities.getAxisFormat(AxisType.Time, origin)
.parseObject(origin);
} catch (ParseException e) {
LOGGER.warning(
"Error while parsing time Axis. Skip setting the TemporalExtent from coordinateAxis");
}
}
init();
}
@Override
public boolean isNumeric() {
return false;
}
@Override
protected synchronized CoordinateReferenceSystem buildCoordinateReferenceSystem() {
return NetCDFCRSUtilities.buildTemporalCrs(coordinateAxis);
}
@Override
protected Date convertValue(Object o) {
final Calendar cal = new GregorianCalendar();
if (epoch != null) {
cal.setTime(epoch);
} else {
cal.setTimeInMillis(0);
}
cal.setTimeZone(NetCDFTimeUtilities.UTC_TIMEZONE);
final double coordValue = ((Number) o).doubleValue();
long vi = (long) Math.floor(coordValue);
double vd = coordValue - vi;
NetCDFTimeUtilities.addTimeUnit(cal, baseTimeUnits, vi);
if (vd != 0.0) {
NetCDFTimeUtilities.addTimeUnit(
cal,
NetCDFTimeUtilities.getTimeUnits(units, vd),
NetCDFTimeUtilities.getTimeSubUnitsValue(units, vd));
}
return cal.getTime();
}
}
| lgpl-2.1 |
camaradosdeputadosoficial/edemocracia | cd-cancelamentoassinatura-portlet/src/main/java/br/gov/camara/edemocracia/portlets/cancelamentoassinatura/dto/Assinatura.java | 1859 | /**
* Copyright (c) 2009-2014 Câmara dos Deputados. Todos os direitos reservados.
*
* e-Democracia é um software livre; você pode redistribuí-lo e/ou modificá-lo dentro
* dos termos da Licença Pública Geral Menor GNU como publicada pela Fundação do
* Software Livre (FSF); na versão 2.1 da Licença, ou (na sua opinião) qualquer versão.
*
* Este programa é distribuído na esperança de que possa ser útil, mas SEM NENHUMA GARANTIA;
* sem uma garantia implícita de ADEQUAÇÃO a qualquer MERCADO ou APLICAÇÃO EM PARTICULAR.
* Veja a Licença Pública Geral Menor GNU para maiores detalhes.
*/
package br.gov.camara.edemocracia.portlets.cancelamentoassinatura.dto;
/**
* Detalhes de uma assinatura
*
* @author p_7339
*
*/
public class Assinatura {
private String comunidade;
private TipoAssinatura tipo;
private String nome;
private String identificador;
/**
* @return the comunidade
*/
public String getComunidade() {
return comunidade;
}
/**
* @param comunidade the comunidade to set
*/
public void setComunidade(String comunidade) {
this.comunidade = comunidade;
}
/**
* @return the tipo
*/
public TipoAssinatura getTipo() {
return tipo;
}
/**
* @param tipo the tipo to set
*/
public void setTipo(TipoAssinatura tipo) {
this.tipo = tipo;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
/**
* @return the identificador
*/
public String getIdentificador() {
return identificador;
}
/**
* @param identificador the identificador to set
*/
public void setIdentificador(String identificador) {
this.identificador = identificador;
}
}
| lgpl-2.1 |
Zongsoft/Zongsoft.Web | src/Components/CompositeDataBoundControl.cs | 1538 | /*
* Authors:
* 钟峰(Popeye Zhong) <zongsoft@gmail.com>
*
* Copyright (C) 2011-2015 Zongsoft Corporation <http://www.zongsoft.com>
*
* This file is part of Zongsoft.Web.
*
* Zongsoft.Web is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* Zongsoft.Web is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Zongsoft.Web; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
using System;
using System.ComponentModel;
using System.Web.UI;
namespace Zongsoft.Web.Controls
{
public class CompositeDataBoundControl : DataBoundControl, INamingContainer
{
#region 公共属性
[Bindable(true)]
[DefaultValue(null)]
[PropertyMetadata(false)]
public object DataSource
{
get
{
return this.GetPropertyValue(() => this.DataSource);
}
set
{
this.SetPropertyValue(() => this.DataSource, value);
}
}
#endregion
}
}
| lgpl-2.1 |
voidseg/libOSCpp | src/OSCNamespaceItem.cc | 6430 | /* Open SoundControl kit in C++ */
/* Copyright (C) 2002-2004 libOSC++ contributors. See AUTHORS */
/* */
/* This library is free software; you can redistribute it and/or */
/* modify it under the terms of the GNU Lesser General Public */
/* License as published by the Free Software Foundation; either */
/* version 2.1 of the License, or (at your option) any later version. */
/* */
/* This library is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU */
/* Lesser General Public License for more details. */
/* */
/* You should have received a copy of the GNU Lesser General Public */
/* License along with this library; if not, write to the Free Software */
/* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
/* */
/* For questions regarding this program contact */
/* Daniel Holth <dholth@fastmail.fm> or visit */
/* http://wiretap.stetson.edu/ */
#include "OSCNamespaceItem.h"
#include "oscmatch.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;
OSCNamespaceItem::OSCNamespaceItem()
{
this->myCallable = NULL;
this->mySubItems = new OSCNamespaceItem::ItemMap();
}
OSCNamespaceItem::~OSCNamespaceItem()
{
delete this->myCallable;
delete this->mySubItems;
}
// non-polymorphic, non-recursive version.
/// Add OSCNamespaceItem to a tree of OSCNamespaceItems, putting in
/// intermediate items as we go along.
// bool OSCNamespaceItem::add(std::string &name, OSCNamespaceItem *addme)
bool OSCNamespaceItem::add(std::string name, OSCCallable *callback)
{
std::vector<std::string> tokens;
std::string delimiters = "/";
std::string::size_type lastPos = name.find_first_not_of("/", 0);
std::string::size_type pos = name.find_first_of("/", lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
tokens.push_back(name.substr(lastPos, pos - lastPos));
lastPos = name.find_first_not_of(delimiters, pos);
pos = name.find_first_of(delimiters, lastPos);
}
std::vector<std::string>::iterator iter;
std::vector<std::string>::iterator end;
OSCNamespaceItem::ItemMap *subitems;
OSCNamespaceItem::ItemMap::iterator item;
OSCNamespaceItem *current = NULL;
iter = tokens.begin();
end = tokens.end();
subitems = this->mySubItems;
while(iter != end)
{
if((item = subitems->find(*iter)) == subitems->end())
{
std::cout << "adding " << *iter << "\n";
current = new OSCNamespaceItem();
(*subitems)[*iter] = current;
}
else
{
current = item->second;
}
subitems = current->mySubItems;
iter++;
}
if(current)
{
current->setCallable(callback);
}
return true;
}
// For debugging.
bool OSCNamespaceItem::list(int level)
{
ItemMap *subitems;
ItemMap::iterator iter;
ItemMap::iterator end;
subitems = this->mySubItems;
iter = subitems->begin();
end = subitems->end();
while (iter != end)
{
std::cout << std::string(level, ' ') << iter->first << std::endl;
if (iter->second != NULL)
{
iter->second->list(level+1);
}
iter++;
}
return true;
}
bool OSCNamespaceItem::traverse(const std::string &pattern,
TraverseFunction tf, void *cookie) {
std::vector<std::string> address;
return this->search_internal(cookie, tf, address, pattern, 1);
}
bool OSCNamespaceItem::search_internal(void *cookie,
TraverseFunction tf,
std::vector < std::string > &address,
const std::string &pattern,
size_t offset)
{
OSCNamespaceItem *item = NULL;
std::string target;
size_t next;
ItemMap *subitems;
ItemMap::iterator iter;
subitems = this->mySubItems;
next = pattern.find('/', offset);
target = pattern.substr(offset, next - offset);
iter = subitems->find(target);
if(iter != subitems->end())
{
// found it the cheap way... no pattern matching.
address.push_back(target);
if(next == pattern.npos)
{
item = iter->second;
tf(cookie, address, item);
}
else
{
return iter->second->search_internal(cookie,
tf,
address,
pattern,
next+1);
}
}
else if(target.size() > 0)
{
// attempt pattern matching
ItemMap::iterator end;
iter = subitems->begin();
end = subitems->end();
const char* glob = target.c_str();
// cout << "globbing on \"" << target << "\"" << endl;
while(iter != end)
{
if(oscmatch(iter->first.c_str(), glob))
{
// cout << "Matched "
// << glob
// << " "
// << iter->first << endl;
item = iter->second;
address.push_back(iter->first);
if(next == target.npos)
{
tf(cookie, address, item);
}
else
{
iter->second->search_internal(cookie, tf, address,
pattern, next+1);
}
address.pop_back();
}
iter++;
}
}
else
{
// time to list the address, if this is how we want to implement it.
// it is also possible to have a "" entry in the namespace
// that had a special listing callback.
address.push_back(target);
tf(cookie, address, this);
}
return true;
}
| lgpl-2.1 |
kees-jan/RxCpp | libs/boost-test-helper/src/unittest-main.cc | 1724 | /*
* Scroom - Generic viewer for 2D data
* Copyright (C) 2009-2012 Kees-Jan Dijkzeul
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <iostream>
#define BOOST_TEST_ALTERNATIVE_INIT_API
#include <boost/test/unit_test.hpp>
#include <boost/test/results_reporter.hpp>
#include <scroom/unused.h>
bool init_unit_test()
{
return true;
}
int main( int argc, char* argv[] )
{
#ifdef XML_TEST_OUTPUT
if(argc>1)
std::cerr << "You have requested XML output. Your command-line arguments will be ignored" << std::endl;
UNUSED(argv);
// Apparently, order is important here. Weird but true...
const char * alternative[] = {
"--log_format=XML",
"--log_level=all",
"--log_sink=test_results.xml",
"--output_format=XML",
"--report_level=no",
};
int count = sizeof(alternative)/sizeof(alternative[0]);
return ::boost::unit_test::unit_test_main( &init_unit_test, count, const_cast<char**>(alternative) );
#else
return ::boost::unit_test::unit_test_main( &init_unit_test, argc, argv );
#endif
}
| lgpl-2.1 |
petosorus/javamon | src/model/Support.java | 446 | package javamon.model;
import javamon.model.Pokemon;
public class Support extends Ability{
Statistic statistic;
int force;
public Support(String name, int accuracy, Type type,
Pokemon source, Pokemon target,
Statistic statistic, int force){
super(name, accuracy, type, source, target);
this.statistic = statistic;
this.force = force;
}
@Override
public void effect(){
target.improveStat(statistic, force);
}
}
| lgpl-2.1 |
TeamupCom/tinymce | modules/katamari/src/test/ts/atomic/api/arr/ObjValuesTest.ts | 428 | import { Assert, UnitTest } from '@ephox/bedrock-client';
import * as Obj from 'ephox/katamari/api/Obj';
UnitTest.test('Obj.values', () => {
const check = (expValues, input) => {
const c = (expected, v) => {
v.sort();
Assert.eq('values', expected, v);
};
c(expValues, Obj.values(input));
};
check([], {});
check([ 'A' ], { a: 'A' });
check([ 'A', 'B', 'C' ], { a: 'A', c: 'C', b: 'B' });
});
| lgpl-2.1 |
mono/linux-packaging-monodevelop | src/core/MonoDevelop.Ide/MonoDevelop.Components.AutoTest.Operations/TextOperation.cs | 1937 | //
// TextOperation.cs
//
// Author:
// iain holmes <iain@xamarin.com>
//
// Copyright (c) 2015 Xamarin, Inc
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Reflection;
using System.Collections.Generic;
namespace MonoDevelop.Components.AutoTest.Operations
{
public class TextOperation : Operation
{
string Text;
bool Exact;
public TextOperation (string text, bool exact = true)
{
Text = text;
Exact = exact;
}
public override List<AppResult> Execute (List<AppResult> resultSet)
{
List<AppResult> newResultSet = new List<AppResult> ();
foreach (var result in resultSet) {
AppResult newResult = result.Text (Text, Exact);
if (newResult != null) {
newResultSet.Add (newResult);
}
}
return newResultSet;
}
public override string ToString ()
{
return string.Format ("Text (\"{0}\", {1})", Text, Exact);
}
}
}
| lgpl-2.1 |
kylinsoong/teiid-embedded-examples | restservice-as-a-datasource/src/main/java/org/teiid/example/TeiidEmbeddedRestWebServiceDataSource.java | 2733 | /*
* JBoss, Home of Professional Open Source.
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership. Some portions may be licensed
* to Red Hat, Inc. under one or more contributor license agreements.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*/
package org.teiid.example;
import static org.teiid.example.JDBCUtils.execute;
import java.sql.Connection;
import org.teiid.resource.adapter.ws.WSManagedConnectionFactory;
import org.teiid.runtime.EmbeddedConfiguration;
import org.teiid.runtime.EmbeddedServer;
import org.teiid.translator.ws.WSExecutionFactory;
@SuppressWarnings("nls")
public class TeiidEmbeddedRestWebServiceDataSource {
public static void main(String[] args) throws Exception {
EmbeddedServer server = new EmbeddedServer();
WSExecutionFactory factory = new WSExecutionFactory();
factory.start();
server.addTranslator("translator-rest", factory);
WSManagedConnectionFactory managedconnectionFactory = new WSManagedConnectionFactory();
server.addConnectionFactory("java:/CustomerRESTWebSvcSource", managedconnectionFactory.createConnectionFactory());
server.start(new EmbeddedConfiguration());
server.deployVDB(TeiidEmbeddedRestWebServiceDataSource.class.getClassLoader().getResourceAsStream("restwebservice-vdb.xml"));
Connection c = server.getDriver().connect("jdbc:teiid:restwebservice", null);
execute(c, "EXEC getCustomer('http://localhost:8080/customer/customerList')", false);
execute(c, "EXEC getAll('http://localhost:8080/customer/getAll')", false);
execute(c, "EXEC getOne('http://localhost:8080/customer/getByNumber/161')", false);
execute(c, "EXEC getOne('http://localhost:8080/customer/getByName/Technics%20Stores%20Inc.')", false);
execute(c, "EXEC getOne('http://localhost:8080/customer/getByCity/Burlingame')", false);
execute(c, "EXEC getOne('http://localhost:8080/customer/getByCountry/USA')", false);
execute(c, "SELECT * FROM CustomersView", true);
server.stop();
}
}
| lgpl-2.1 |
kobolabs/qt-everywhere-4.8.0 | examples/script/qstetrix/main.cpp | 4734 | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor
** the names of its contributors may be used to endorse or promote
** products derived from this software without specific prior written
** permission.
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
** $QT_END_LICENSE$
**
****************************************************************************/
#include "tetrixboard.h"
#include <QtGui>
#include <QtScript>
#include <QUiLoader>
#ifndef QT_NO_SCRIPTTOOLS
#include <QtScriptTools>
#endif
struct QtMetaObject : private QObject
{
public:
static const QMetaObject *get()
{ return &static_cast<QtMetaObject*>(0)->staticQtMetaObject; }
};
//! [0]
class TetrixUiLoader : public QUiLoader
{
public:
TetrixUiLoader(QObject *parent = 0)
: QUiLoader(parent)
{ }
virtual QWidget *createWidget(const QString &className, QWidget *parent = 0,
const QString &name = QString())
{
if (className == QLatin1String("TetrixBoard")) {
QWidget *board = new TetrixBoard(parent);
board->setObjectName(name);
return board;
}
return QUiLoader::createWidget(className, parent, name);
}
};
//! [0]
static QScriptValue evaluateFile(QScriptEngine &engine, const QString &fileName)
{
QFile file(fileName);
file.open(QIODevice::ReadOnly);
return engine.evaluate(file.readAll(), fileName);
}
int main(int argc, char *argv[])
{
Q_INIT_RESOURCE(tetrix);
//! [1]
QApplication app(argc, argv);
QScriptEngine engine;
QScriptValue Qt = engine.newQMetaObject(QtMetaObject::get());
Qt.setProperty("App", engine.newQObject(&app));
engine.globalObject().setProperty("Qt", Qt);
//! [1]
#if !defined(QT_NO_SCRIPTTOOLS)
QScriptEngineDebugger debugger;
debugger.attachTo(&engine);
QMainWindow *debugWindow = debugger.standardWindow();
debugWindow->resize(1024, 640);
#endif
//! [2]
evaluateFile(engine, ":/tetrixpiece.js");
evaluateFile(engine, ":/tetrixboard.js");
evaluateFile(engine, ":/tetrixwindow.js");
//! [2]
//! [3]
TetrixUiLoader loader;
QFile uiFile(":/tetrixwindow.ui");
uiFile.open(QIODevice::ReadOnly);
QWidget *ui = loader.load(&uiFile);
uiFile.close();
QScriptValue ctor = engine.evaluate("TetrixWindow");
QScriptValue scriptUi = engine.newQObject(ui, QScriptEngine::ScriptOwnership);
QScriptValue tetrix = ctor.construct(QScriptValueList() << scriptUi);
//! [3]
QPushButton *debugButton = ui->findChild<QPushButton*>("debugButton");
#if !defined(QT_NO_SCRIPTTOOLS)
QObject::connect(debugButton, SIGNAL(clicked()),
debugger.action(QScriptEngineDebugger::InterruptAction),
SIGNAL(triggered()));
QObject::connect(debugButton, SIGNAL(clicked()),
debugWindow, SLOT(show()));
#else
debugButton->hide();
#endif
//! [4]
ui->resize(550, 370);
ui->show();
qsrand(QTime(0,0,0).secsTo(QTime::currentTime()));
return app.exec();
//! [4]
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/toolkits/graph/interaction/InteractionHandler.java | 7134 | package soot.toolkits.graph.interaction;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2004 Jennifer Lhotak
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import soot.Body;
import soot.G;
import soot.PhaseOptions;
import soot.Singletons;
import soot.SootMethod;
import soot.Transform;
import soot.jimple.toolkits.annotation.callgraph.CallGraphGrapher;
import soot.options.Options;
import soot.toolkits.graph.DirectedGraph;
public class InteractionHandler {
private static final Logger logger = LoggerFactory.getLogger(InteractionHandler.class);
public InteractionHandler(Singletons.Global g) {
}
public static InteractionHandler v() {
return G.v().soot_toolkits_graph_interaction_InteractionHandler();
}
private ArrayList<Object> stopUnitList;
public ArrayList<Object> getStopUnitList() {
return stopUnitList;
}
public void addToStopUnitList(Object elem) {
if (stopUnitList == null) {
stopUnitList = new ArrayList<Object>();
}
stopUnitList.add(elem);
}
public void removeFromStopUnitList(Object elem) {
if (stopUnitList.contains(elem)) {
stopUnitList.remove(elem);
}
}
public void handleNewAnalysis(Transform t, Body b) {
// here save current phase name and only send if actual data flow analysis exists
if (PhaseOptions.getBoolean(PhaseOptions.v().getPhaseOptions(t.getPhaseName()), "enabled")) {
String name = t.getPhaseName() + " for method: " + b.getMethod().getName();
currentPhaseName(name);
currentPhaseEnabled(true);
doneCurrent(false);
} else {
currentPhaseEnabled(false);
setInteractThisAnalysis(false);
}
}
public void handleCfgEvent(DirectedGraph<?> g) {
if (currentPhaseEnabled()) {
logger.debug("Analyzing: " + currentPhaseName());
doInteraction(new InteractionEvent(IInteractionConstants.NEW_ANALYSIS, currentPhaseName()));
}
if (isInteractThisAnalysis()) {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_CFG, g));
}
}
public void handleStopAtNodeEvent(Object u) {
if (isInteractThisAnalysis()) {
doInteraction(new InteractionEvent(IInteractionConstants.STOP_AT_NODE, u));
}
}
public void handleBeforeAnalysisEvent(Object beforeFlow) {
if (isInteractThisAnalysis()) {
if (autoCon()) {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_BEFORE_ANALYSIS_INFO_AUTO, beforeFlow));
} else {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_BEFORE_ANALYSIS_INFO, beforeFlow));
}
}
}
public void handleAfterAnalysisEvent(Object afterFlow) {
if (isInteractThisAnalysis()) {
if (autoCon()) {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_AFTER_ANALYSIS_INFO_AUTO, afterFlow));
} else {
doInteraction(new InteractionEvent(IInteractionConstants.NEW_AFTER_ANALYSIS_INFO, afterFlow));
}
}
}
public void handleTransformDone(Transform t, Body b) {
doneCurrent(true);
if (isInteractThisAnalysis()) {
doInteraction(new InteractionEvent(IInteractionConstants.DONE, null));
}
}
public void handleCallGraphStart(Object info, CallGraphGrapher grapher) {
setGrapher(grapher);
doInteraction(new InteractionEvent(IInteractionConstants.CALL_GRAPH_START, info));
if (!isCgReset()) {
handleCallGraphNextMethod();
} else {
setCgReset(false);
handleReset();
}
}
public void handleCallGraphNextMethod() {
if (!cgDone()) {
getGrapher().setNextMethod(getNextMethod());
getGrapher().handleNextMethod();
}
}
private boolean cgReset = false;
public void setCgReset(boolean v) {
cgReset = v;
}
public boolean isCgReset() {
return cgReset;
}
public void handleReset() {
if (!cgDone()) {
getGrapher().reset();
}
}
public void handleCallGraphPart(Object info) {
doInteraction(new InteractionEvent(IInteractionConstants.CALL_GRAPH_PART, info));
if (!isCgReset()) {
handleCallGraphNextMethod();
} else {
setCgReset(false);
handleReset();
}
}
private CallGraphGrapher grapher;
private void setGrapher(CallGraphGrapher g) {
grapher = g;
}
private CallGraphGrapher getGrapher() {
return grapher;
}
private SootMethod nextMethod;
public void setNextMethod(SootMethod m) {
nextMethod = m;
}
private SootMethod getNextMethod() {
return nextMethod;
}
private synchronized void doInteraction(InteractionEvent event) {
getInteractionListener().setEvent(event);
getInteractionListener().handleEvent();
}
public synchronized void waitForContinue() {
try {
this.wait();
} catch (InterruptedException e) {
logger.debug("" + e.getMessage());
}
}
private boolean interactThisAnalysis;
public void setInteractThisAnalysis(boolean b) {
interactThisAnalysis = b;
}
public boolean isInteractThisAnalysis() {
return interactThisAnalysis;
}
private boolean interactionCon;
public synchronized void setInteractionCon() {
this.notify();
}
public boolean isInteractionCon() {
return interactionCon;
}
private IInteractionListener interactionListener;
public void setInteractionListener(IInteractionListener listener) {
interactionListener = listener;
}
public IInteractionListener getInteractionListener() {
return interactionListener;
}
private String currentPhaseName;
public void currentPhaseName(String name) {
currentPhaseName = name;
}
public String currentPhaseName() {
return currentPhaseName;
}
private boolean currentPhaseEnabled;
public void currentPhaseEnabled(boolean b) {
currentPhaseEnabled = b;
}
public boolean currentPhaseEnabled() {
return currentPhaseEnabled;
}
private boolean cgDone = false;
public void cgDone(boolean b) {
cgDone = b;
}
public boolean cgDone() {
return cgDone;
}
private boolean doneCurrent;
public void doneCurrent(boolean b) {
doneCurrent = b;
}
public boolean doneCurrent() {
return doneCurrent;
}
private boolean autoCon;
public void autoCon(boolean b) {
autoCon = b;
}
public boolean autoCon() {
return autoCon;
}
public void stopInteraction(boolean b) {
Options.v().set_interactive_mode(false);
}
}
| lgpl-2.1 |
walafc0/soclib | soclib/module/connectivity_component/vci_block_device/tlmdt/source/src/vci_block_device.cpp | 17283 | /* -*- c++ -*-
*
* SOCLIB_LGPL_HEADER_BEGIN
*
* This file is part of SoCLib, GNU LGPLv2.1.
*
* SoCLib is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation; version 2.1 of the License.
*
* SoCLib is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with SoCLib; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA
*
* SOCLIB_LGPL_HEADER_END
*
* Copyright (c) UPMC, Lip6, Asim
* Aline Vieira de Mello <aline.vieira-de-mello@lip6.fr>, 2010
* Alain Greiner <alain.greiner@lip6.fr>
*/
#include <stdint.h>
#include <iostream>
#include "register.h"
#include "../include/vci_block_device.h"
#include <fcntl.h>
#include "block_device.h"
//#define SOCLIB_MODULE_DEBUG 1
#define MAX_BURST_LENGTH 64
namespace soclib { namespace tlmdt {
namespace {
const char* SoclibBlockDeviceRegisters_str[] = {
"BLOCK_DEVICE_BUFFER",
"BLOCK_DEVICE_LBA",
"BLOCK_DEVICE_COUNT",
"BLOCK_DEVICE_OP",
"BLOCK_DEVICE_STATUS",
"BLOCK_DEVICE_IRQ_ENABLE",
"BLOCK_DEVICE_SIZE",
"BLOCK_DEVICE_BLOCK_SIZE"
};
const char* SoclibBlockDeviceOp_str[] = {
"BLOCK_DEVICE_NOOP",
"BLOCK_DEVICE_READ",
"BLOCK_DEVICE_WRITE",
};
const char* SoclibBlockDeviceStatus_str[] = {
"BLOCK_DEVICE_IDLE",
"BLOCK_DEVICE_BUSY",
"BLOCK_DEVICE_READ_SUCCESS",
"BLOCK_DEVICE_WRITE_SUCCESS",
"BLOCK_DEVICE_READ_ERROR",
"BLOCK_DEVICE_WRITE_ERROR",
"BLOCK_DEVICE_ERROR",
};
}
#define tmpl(t) template<typename vci_param> t VciBlockDevice<vci_param>
/////////////////////////
tmpl (void)::send_null()
{
m_pdes_local_time->reset_sync();
// send NULL message
m_null_time = m_pdes_local_time->get();
p_vci_initiator->nb_transport_fw(m_null_payload, m_null_phase, m_null_time);
// send IRQ
m_irq_time = m_pdes_local_time->get();
p_irq->nb_transport_fw(m_irq_payload, m_irq_phase, m_irq_time);
#ifdef SOCLIB_MODULE_DEBUG
std::cout << "[" <<name() << "] time = " << std::dec << m_null_time.value()
<< " NULL MESSAGE / IRQ value = " << (int)m_irq_value << std::endl;
#endif
}
////////////////////////////////////////////////////
tmpl (void)::send_vci_command(bool read_from_memory)
{
m_pdes_local_time->reset_sync();
// send VCI command
size_t length = m_transfer_size - m_transfer_offset;
if ( length > MAX_BURST_LENGTH) length = MAX_BURST_LENGTH;
if ( read_from_memory ) m_vci_extension.set_read();
else m_vci_extension.set_write();
m_vci_payload.set_data_ptr(m_vci_data_buf + m_transfer_offset);
m_vci_payload.set_address(m_buffer + m_transfer_offset);
m_vci_payload.set_data_length(length);
m_vci_payload.set_byte_enable_length(length);
m_vci_time = m_pdes_local_time->get();
p_vci_initiator->nb_transport_fw(m_vci_payload, m_vci_phase, m_vci_time);
// send IRQ
m_irq_time = m_pdes_local_time->get();
p_irq->nb_transport_fw(m_irq_payload, m_irq_phase, m_irq_time);
#ifdef SOCLIB_MODULE_DEBUG
std::cout << "[" <<name() << "] time = " << std::dec << m_vci_time.value();
if ( read_from_memory ) std::cout << " VCI READ at address ";
else std::cout << " VCI WRITE at address ";
std::cout << std::hex << m_buffer + m_transfer_offset;
std::cout << " / IRQ value = " << (int)m_irq_value << std::endl;
#endif
m_transfer_offset += length;
}
/////////////////////////////
tmpl(void)::ended(int status)
{
#ifdef SOCLIB_MODULE_DEBUG
std::cout
<< name()
<< " finished current operation ("
<< SoclibBlockDeviceOp_str[m_current_op]
<< ") with the status "
<< SoclibBlockDeviceStatus_str[status]
<< std::endl;
#endif
if ( m_irq_enabled ) m_irq_value = 0xFF;
m_current_op = m_op = BLOCK_DEVICE_NOOP;
m_status = status;
}
//////////////////////
tmpl(void)::next_req()
{
switch (m_current_op) {
case BLOCK_DEVICE_READ:
{
if ( m_count && m_transfer_offset == 0 )
{
if ( m_lba + m_count > m_device_size )
{
std::cerr << name() << " warning: trying to read beyond end of device" << std::endl;
ended(BLOCK_DEVICE_READ_ERROR);
break;
}
m_vci_data_buf = new uint8_t[m_transfer_size];
lseek(m_fd, m_lba*m_block_size, SEEK_SET);
int retval = ::read(m_fd, m_vci_data_buf, m_transfer_size);
if ( retval < 0 )
{
ended(BLOCK_DEVICE_READ_ERROR);
break;
}
}
// blocking command
bool read_from_memory = false;
send_vci_command(read_from_memory);
wait(m_rsp_received);
m_status = BLOCK_DEVICE_BUSY;
read_done();
break;
}
case BLOCK_DEVICE_WRITE:
{
if ( m_count && m_transfer_offset == 0 )
{
if ( m_lba + m_count > m_device_size )
{
std::cerr << name() << " warning: trying to write beyond end of device" << std::endl;
ended(BLOCK_DEVICE_WRITE_ERROR);
break;
}
m_vci_data_buf = new uint8_t[m_transfer_size];
lseek(m_fd, m_lba*m_block_size, SEEK_SET);
}
// blocking command
bool read_from_memory = true;
send_vci_command(read_from_memory);
wait(m_rsp_received);
m_status = BLOCK_DEVICE_BUSY;
write_finish();
break;
}
default:
ended(BLOCK_DEVICE_ERROR);
break;
}
}
///////////////////////////
tmpl(void)::write_finish( )
{
if ( ! m_vci_payload.is_response_error() && m_transfer_offset < m_transfer_size )
{
next_req();
return;
}
if ( ! m_vci_payload.is_response_error() && m_fd >= 0 &&
::write( m_fd, (char *)m_vci_data_buf, m_transfer_size ) > 0 ) ended(BLOCK_DEVICE_WRITE_SUCCESS);
else ended(BLOCK_DEVICE_WRITE_ERROR);
delete m_vci_data_buf;
}
///////////////////////
tmpl(void)::read_done()
{
if ( ! m_vci_payload.is_response_error() && m_transfer_offset < m_transfer_size )
{
next_req();
return;
}
if ( m_vci_payload.is_response_error() ) ended(BLOCK_DEVICE_READ_ERROR);
else ended(BLOCK_DEVICE_READ_SUCCESS);
delete m_vci_data_buf;
}
//////////////////////////////////////////////////////
// initiator thread
//////////////////////////////////////////////////////
tmpl (void)::execLoop ()
{
while(true)
{
m_pdes_local_time->add(UNIT_TIME);
if ( m_current_op == BLOCK_DEVICE_NOOP && m_op != BLOCK_DEVICE_NOOP )
{
if ( m_access_latency )
{
m_access_latency--;
}
else
{
#ifdef SOCLIB_MODULE_DEBUG
std::cout << name() << " launch an operation " << SoclibBlockDeviceOp_str[m_op] << std::endl;
#endif
m_current_op = m_op;
m_op = BLOCK_DEVICE_NOOP;
m_transfer_offset = 0;
m_transfer_size = m_count * m_block_size;
next_req();
}
}
// send a null message if required
if (m_pdes_local_time->need_sync())
{
send_null();
wait( m_rsp_received );
}
}
sc_core::sc_stop();
} // end execLoop()
///////////////////////////////////////////////////////////////////////////////
// Interface function used when receiving a response on the initiator port
///////////////////////////////////////////////////////////////////////////////
tmpl (tlm::tlm_sync_enum)::nb_transport_bw
( tlm::tlm_generic_payload &payload,
tlm::tlm_phase &phase,
sc_core::sc_time &time)
{
if(time > m_pdes_local_time->get()) m_pdes_local_time->set(time);
m_rsp_received.notify (sc_core::SC_ZERO_TIME);
return tlm::TLM_COMPLETED;
}
/////////////////////////////////////////////////////////////////////////////////////
// Interface function used when receiving a VCI command on the target port
/////////////////////////////////////////////////////////////////////////////////////
tmpl(tlm::tlm_sync_enum)::nb_transport_fw ( tlm::tlm_generic_payload &payload,
tlm::tlm_phase &phase,
sc_core::sc_time &time)
{
typename vci_param::addr_t address = payload.get_address();
int cell;
bool one_flit = (payload.get_data_length() == (unsigned int)vci_param::nbytes);
soclib_payload_extension* extension_pointer;
payload.get_extension(extension_pointer);
// No action and no response when receiving a null message
if(extension_pointer->is_null_message()) return tlm::TLM_COMPLETED;
// address and pcket length checking
if ( m_segment.contains(payload.get_address()) && one_flit )
{
cell = (int)((address - m_segment.baseAddress()) / vci_param::nbytes);
payload.set_response_status(tlm::TLM_OK_RESPONSE);
if (extension_pointer->get_command() == VCI_READ_COMMAND)
{
#ifdef SOCLIB_MODULE_DEBUG
std::cout << "[" << name() << "] time = " << std::dec << time.value()
<< " STATUS REQUEST " << SoclibBlockDeviceRegisters_str[cell] << std::endl;
#endif
if ( cell == BLOCK_DEVICE_SIZE ) utoa(m_device_size, payload.get_data_ptr(),0);
else if ( cell == BLOCK_DEVICE_BLOCK_SIZE ) utoa(m_block_size, payload.get_data_ptr(),0);
else if ( cell == BLOCK_DEVICE_STATUS )
{
utoa(m_status, payload.get_data_ptr(),0);
if (m_status != BLOCK_DEVICE_BUSY)
{
m_status = BLOCK_DEVICE_IDLE;
m_irq_value = 0x00;
}
}
else payload.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
} //end if READ
else if (extension_pointer->get_command() == VCI_WRITE_COMMAND)
{
#ifdef SOCLIB_MODULE_DEBUG
std::cout << "[" << name() << "] time = " << std::dec << time.value()
<< " CONFIG REQUEST to " << SoclibBlockDeviceRegisters_str[cell]
<< " with value = " << std::hex << atou(payload.get_data_ptr(),0) << std::endl;
#endif
if ( m_status != BLOCK_DEVICE_BUSY )
{
data_t data = atou(payload.get_data_ptr(),0);
if ( cell == BLOCK_DEVICE_BUFFER ) m_buffer = data;
else if ( cell == BLOCK_DEVICE_COUNT ) m_count = data;
else if ( cell == BLOCK_DEVICE_LBA ) m_lba = data;
else if ( cell == BLOCK_DEVICE_OP )
{
m_op = data;
m_access_latency = m_lfsr % (m_average_latency+1);
m_lfsr = (m_lfsr >> 1) ^ ((-(m_lfsr & 1)) & 0xd0000001);
}
else if ( cell == BLOCK_DEVICE_IRQ_ENABLE ) m_irq_enabled = (bool)data;
else payload.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
}
else
{
std::cerr << name()
<< " warning: receiving a new command while busy, ignored" << std::endl;
}
} // end if WRITE
else // illegal command
{
payload.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
}
}
else // illegal address
{
payload.set_response_status(tlm::TLM_GENERIC_ERROR_RESPONSE);
}
// update transaction phase and time
phase = tlm::BEGIN_RESP;
if ( time.value() < m_pdes_local_time->get().value() ) time = m_pdes_local_time->get();
else time = time + UNIT_TIME;
// send response
p_vci_target->nb_transport_bw(payload, phase, time);
return tlm::TLM_COMPLETED;
} // end nb_transport_fw
// Not implemented for this example but required by interface
tmpl(void)::b_transport
( tlm::tlm_generic_payload &payload, // payload
sc_core::sc_time &_time) //time
{
return;
}
// Not implemented for this example but required by interface
tmpl(bool)::get_direct_mem_ptr
( tlm::tlm_generic_payload &payload, // address + extensions
tlm::tlm_dmi &dmi_data) // DMI data
{
return false;
}
// Not implemented for this example but required by interface
tmpl(unsigned int):: transport_dbg
( tlm::tlm_generic_payload &payload) // debug payload
{
return false;
}
// Not implemented for this example but required by interface
tmpl(void)::invalidate_direct_mem_ptr
( sc_dt::uint64 start_range,
sc_dt::uint64 end_range) { }
/////////////////////////////////////////////////////////////////////////////////////
// Interface function executed when receiving a response to an IRQ transaction
/////////////////////////////////////////////////////////////////////////////////////
tmpl (tlm::tlm_sync_enum)::irq_nb_transport_bw
( tlm::tlm_generic_payload &payload, // payload
tlm::tlm_phase &phase, // phase
sc_core::sc_time &time) // time
{
return tlm::TLM_COMPLETED;
}
////////////////////////////
// constructor
////////////////////////////
tmpl(/**/)::VciBlockDevice(
sc_module_name name,
const soclib::common::MappingTable &mt,
const soclib::common::IntTab &srcid,
const soclib::common::IntTab &tgtid,
const std::string &filename,
const uint32_t block_size,
const uint32_t latency)
: sc_core::sc_module(name)
, m_block_size(block_size)
, m_average_latency(latency)
, m_srcid(mt.indexForId(srcid))
, m_segment(mt.getSegment(tgtid))
, p_vci_initiator("init")
, p_vci_target("tgt")
, p_irq("irq")
{
// bind vci initiator port
p_vci_initiator(*this);
// bind vci target port
p_vci_target(*this);
// register irq initiator port
p_irq.register_nb_transport_bw(this, &VciBlockDevice::irq_nb_transport_bw);
// PDES local time
m_pdes_local_time = new pdes_local_time(100*UNIT_TIME);
// create and initialize the be buffer for VCI transactions
m_vci_be_buf = new uint8_t[MAX_BURST_LENGTH];
for ( size_t i=0 ; i<MAX_BURST_LENGTH ; i++) m_vci_be_buf[i] = 0xFF;
// initialize payload, phase and extension for a VCI transaction
m_vci_payload.set_command(tlm::TLM_IGNORE_COMMAND);
m_vci_payload.set_byte_enable_ptr(m_vci_be_buf);
m_vci_payload.set_extension(&m_vci_extension);
m_vci_extension.set_src_id(m_srcid);
m_vci_extension.set_trd_id(0);
m_vci_extension.set_pkt_id(0);
m_vci_phase = tlm::BEGIN_REQ;
// initialize payload, phase and extension for a null message
m_null_payload.set_extension(&m_null_extension);
m_null_extension.set_null_message();
m_null_phase = tlm::BEGIN_REQ;
// initialize payload and phase for an irq message
m_irq_payload.set_data_ptr(&m_irq_value);
m_irq_phase = tlm::BEGIN_REQ;
// open file
m_fd = ::open(filename.c_str(), O_RDWR);
if ( m_fd < 0 )
{
std::cerr << "Unable to open block device image file " << filename << std::endl;
m_device_size = 0;
}
else
{
m_device_size = lseek(m_fd, 0, SEEK_END) / m_block_size;
if ( m_device_size > 0xFFFFFFFF)
{
std::cerr
<< "Warning: block device " << filename
<< " has more blocks than addressable with 32 bits" << std::endl;
m_device_size = 0xFFFFFFFF;
}
}
// initialise registers
m_irq_enabled = false;
m_irq_value = 0x00;
m_op = BLOCK_DEVICE_NOOP;
m_current_op = BLOCK_DEVICE_NOOP;
m_access_latency = 0;
m_status = BLOCK_DEVICE_IDLE;
m_lfsr = -1;
#ifdef SOCLIB_MODULE_DEBUG
std::cout
<< name
<< " = Opened "
<< filename
<< " which has "
<< m_device_size
<< " blocks of "
<< m_block_size
<< " bytes"
<< std::endl;
#endif
SC_THREAD(execLoop);
}
}}
// Local Variables:
// tab-width: 4
// c-basic-offset: 4
// c-file-offsets:((innamespace . 0)(inline-open . 0))
// indent-tabs-mode: nil
// End:
// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=4:softtabstop=4
| lgpl-2.1 |
kerenby/nabus | src/org/jitsi/impl/neomedia/codec/audio/silk/TablesOtherFLP.java | 616 | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package org.jitsi.impl.neomedia.codec.audio.silk;
/**
*
* @author Jing Dai
* @author Dingxin Xu
*
*/
public class TablesOtherFLP
{
static float[] SKP_Silk_HarmShapeFIR_FLP = { 16384.0f / 65536.0f, 32767.0f / 65536.0f, 16384.0f / 65536.0f };
float[][] SKP_Silk_Quantization_Offsets =
{
{ Define.OFFSET_VL_Q10 / 1024.0f, Define.OFFSET_VH_Q10 / 1024.0f },
{ Define.OFFSET_UVL_Q10 / 1024.0f, Define.OFFSET_UVH_Q10 / 1024.0f }
};
}
| lgpl-2.1 |
plast-lab/soot | src/main/java/soot/dava/toolkits/base/AST/ASTWalker.java | 4671 | package soot.dava.toolkits.base.AST;
/*-
* #%L
* Soot - a J*va Optimization Framework
* %%
* Copyright (C) 2003 Jerome Miecznikowski
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 2.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Lesser Public License for more details.
*
* You should have received a copy of the GNU General Lesser Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/lgpl-2.1.html>.
* #L%
*/
import soot.G;
import soot.Singletons;
import soot.Value;
import soot.jimple.ArrayRef;
import soot.jimple.BinopExpr;
import soot.jimple.CastExpr;
import soot.jimple.DefinitionStmt;
import soot.jimple.Expr;
import soot.jimple.InstanceFieldRef;
import soot.jimple.InstanceInvokeExpr;
import soot.jimple.InstanceOfExpr;
import soot.jimple.InvokeExpr;
import soot.jimple.InvokeStmt;
import soot.jimple.NewArrayExpr;
import soot.jimple.NewMultiArrayExpr;
import soot.jimple.Ref;
import soot.jimple.ReturnStmt;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.UnopExpr;
public class ASTWalker {
public ASTWalker(Singletons.Global g) {
}
public static ASTWalker v() {
return G.v().soot_dava_toolkits_base_AST_ASTWalker();
}
public void walk_stmt(ASTAnalysis a, Stmt s) {
if (a.getAnalysisDepth() < ASTAnalysis.ANALYSE_STMTS) {
return;
}
if (s instanceof DefinitionStmt) {
DefinitionStmt ds = (DefinitionStmt) s;
walk_value(a, ds.getRightOp());
walk_value(a, ds.getLeftOp());
a.analyseDefinitionStmt(ds);
} else if (s instanceof ReturnStmt) {
ReturnStmt rs = (ReturnStmt) s;
walk_value(a, rs.getOp());
a.analyseReturnStmt(rs);
} else if (s instanceof InvokeStmt) {
InvokeStmt is = (InvokeStmt) s;
walk_value(a, is.getInvokeExpr());
a.analyseInvokeStmt(is);
} else if (s instanceof ThrowStmt) {
ThrowStmt ts = (ThrowStmt) s;
walk_value(a, ts.getOp());
a.analyseThrowStmt(ts);
} else {
a.analyseStmt(s);
}
}
public void walk_value(ASTAnalysis a, Value v) {
if (a.getAnalysisDepth() < ASTAnalysis.ANALYSE_VALUES) {
return;
}
if (v instanceof Expr) {
Expr e = (Expr) v;
if (e instanceof BinopExpr) {
BinopExpr be = (BinopExpr) e;
walk_value(a, be.getOp1());
walk_value(a, be.getOp2());
a.analyseBinopExpr(be);
} else if (e instanceof UnopExpr) {
UnopExpr ue = (UnopExpr) e;
walk_value(a, ue.getOp());
a.analyseUnopExpr(ue);
} else if (e instanceof CastExpr) {
CastExpr ce = (CastExpr) e;
walk_value(a, ce.getOp());
a.analyseExpr(ce);
} else if (e instanceof NewArrayExpr) {
NewArrayExpr nae = (NewArrayExpr) e;
walk_value(a, nae.getSize());
a.analyseNewArrayExpr(nae);
} else if (e instanceof NewMultiArrayExpr) {
NewMultiArrayExpr nmae = (NewMultiArrayExpr) e;
for (int i = 0; i < nmae.getSizeCount(); i++) {
walk_value(a, nmae.getSize(i));
}
a.analyseNewMultiArrayExpr(nmae);
} else if (e instanceof InstanceOfExpr) {
InstanceOfExpr ioe = (InstanceOfExpr) e;
walk_value(a, ioe.getOp());
a.analyseInstanceOfExpr(ioe);
} else if (e instanceof InvokeExpr) {
InvokeExpr ie = (InvokeExpr) e;
for (int i = 0; i < ie.getArgCount(); i++) {
walk_value(a, ie.getArg(i));
}
if (ie instanceof InstanceInvokeExpr) {
InstanceInvokeExpr iie = (InstanceInvokeExpr) ie;
walk_value(a, iie.getBase());
a.analyseInstanceInvokeExpr(iie);
} else {
a.analyseInvokeExpr(ie);
}
} else {
a.analyseExpr(e);
}
} else if (v instanceof Ref) {
Ref r = (Ref) v;
if (r instanceof ArrayRef) {
ArrayRef ar = (ArrayRef) r;
walk_value(a, ar.getBase());
walk_value(a, ar.getIndex());
a.analyseArrayRef(ar);
} else if (r instanceof InstanceFieldRef) {
InstanceFieldRef ifr = (InstanceFieldRef) r;
walk_value(a, ifr.getBase());
a.analyseInstanceFieldRef(ifr);
} else {
a.analyseRef(r);
}
} else {
a.analyseValue(v);
}
}
}
| lgpl-2.1 |
dexman545/Technofirma-Mod | src/main/java/technofirma/core/CommonProxy.java | 13614 | package technofirma.core;
import net.minecraft.item.ItemStack;
import net.minecraftforge.common.MinecraftForge;
import com.bioxx.tfc.Items.ItemMeltedMetal;
import com.bioxx.tfc.api.Metal;
import com.bioxx.tfc.api.TFCItems;
import com.bioxx.tfc.api.Constant.Global;
import com.bioxx.tfc.api.Crafting.AnvilManager;
import com.bioxx.tfc.api.Crafting.AnvilRecipe;
import com.bioxx.tfc.api.Crafting.AnvilReq;
import com.bioxx.tfc.api.Crafting.PlanRecipe;
import com.bioxx.tfc.api.Enums.RuleEnum;
import technofirma.blocks.BlockTFOilLamp;
import technofirma.crafting.MagicAnvilManager;
import technofirma.crafting.MagicAnvilRecipe;
import technofirma.crafting.MagicPlanRecipe;
import technofirma.events.ThaumcraftTreeFell;
import technofirma.foci.ItemFocusProspecting;
import technofirma.handlers.GuiHandler;
import technofirma.items.ItemTFOilLamp;
import technofirma.items.ItemTechnofirmaAxe;
import technofirma.items.ItemTechnofirmaHoe;
import technofirma.items.ItemTechnofirmaIngot;
import technofirma.items.ItemTechnofirmaPickaxe;
import technofirma.items.ItemTechnofirmaShovel;
import technofirma.items.ItemTechnofirmaSword;
import technofirma.items.ItemTechnofirmaToolHead;
import technofirma.lamp.LampFluid;
import technofirma.tileentities.TEMagicAnvil;
import technofirma.tileentities.TETFIngotPile;
import technofirma.tileentities.TETFOilLamp;
import thaumcraft.api.ItemApi;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
import cpw.mods.fml.common.event.FMLInterModComms;
import cpw.mods.fml.common.network.NetworkRegistry;
import cpw.mods.fml.common.registry.GameRegistry;
public class CommonProxy
{
public void RegisterRenderers() { }
public void RegisterGuiHandler()
{
NetworkRegistry.INSTANCE.registerGuiHandler(TechnofirmaCore.instance, new GuiHandler());
}
public void SetupLampFuels()
{
LampFluid.CreateFluid("oliveoil", 1);
LampFluid.CreateFluid("oil", 2);
LampFluid.CreateFluid("fuel", 3);
}
public void SetupBlocks()
{
TechnofirmaCore.OilLamp = new BlockTFOilLamp().setHardness(1F).setBlockName("TFOilLamp");
}
public void RegisterBlocks()
{
GameRegistry.registerBlock(TechnofirmaCore.OilLamp, ItemTFOilLamp.class, "TFOilLamp");
}
public void RegisterTE()
{
GameRegistry.registerTileEntity(TETFOilLamp.class, "TF Oil Lamp");
}
public void SetupMagicItems()
{
// Setup magic ingots
TechnofirmaCore.ThaumicSteelIngot = new ItemTechnofirmaIngot().SetIconTexture("thaumcraft:thaumiumingot").setUnlocalizedName("Thaumic Steel Ingot");
// Setup Magic Melted Metal
TechnofirmaCore.ThaumicSteelUnshaped = new ItemMeltedMetal().setUnlocalizedName("Thaumic Steel Unshaped");
// Setup Magic Metal
TechnofirmaCore.ThaumicSteel = new Metal("Thaumic Steel", TechnofirmaCore.ThaumicSteelUnshaped, TechnofirmaCore.ThaumicSteelIngot);
// Setup magic tools
TechnofirmaCore.ThaumicSteelAxe = new ItemTechnofirmaAxe(TechnofirmaCore.ThaumicSteelMaterial, 250).SetIconTexture("thaumcraft:thaumiumaxe").setUnlocalizedName("Thaumic Steel Axe").setMaxDamage(TFCItems.steelUses + 250);
TechnofirmaCore.ThaumicSteelShovel = new ItemTechnofirmaShovel(TechnofirmaCore.ThaumicSteelMaterial).SetIconTexture("thaumcraft:thaumiumshovel").setUnlocalizedName("Thaumic Steel Shovel").setMaxDamage(TFCItems.steelUses + 250);
TechnofirmaCore.ThaumicSteelPickaxe = new ItemTechnofirmaPickaxe(TechnofirmaCore.ThaumicSteelMaterial).SetIconTexture("thaumcraft:thaumiumpick").setUnlocalizedName("Thaumic Steel Pickaxe").setMaxDamage(TFCItems.steelUses + 250);
TechnofirmaCore.ThaumicSteelHoe = new ItemTechnofirmaHoe(TechnofirmaCore.ThaumicSteelMaterial).SetIconTexture("thaumcraft:thaumiumhoe").setUnlocalizedName("Thaumic Steel Hoe").setMaxDamage(TFCItems.steelUses + 250);
TechnofirmaCore.ThaumicSteelSword = new ItemTechnofirmaSword(TechnofirmaCore.ThaumicSteelMaterial, 300).SetIconTexture("thaumcraft:thaumiumsword").setUnlocalizedName("Thaumic Steel Sword").setMaxDamage(TFCItems.steelUses + 250);
// Setup magic tool heads
TechnofirmaCore.ThaumicSteelAxeHead = new ItemTechnofirmaToolHead().SetIconTexture("technofirma:Thaumic Steel Axe Head").setUnlocalizedName("Thaumic Steel Axe Head");
TechnofirmaCore.ThaumicSteelShovelHead = new ItemTechnofirmaToolHead().SetIconTexture("technofirma:Thaumic Steel Shovel Head").setUnlocalizedName("Thaumic Steel Shovel Head");
TechnofirmaCore.ThaumicSteelPickaxeHead = new ItemTechnofirmaToolHead().SetIconTexture("technofirma:Thaumic Steel Pickaxe Head").setUnlocalizedName("Thaumic Steel Pickaxe Head");
TechnofirmaCore.ThaumicSteelHoeHead = new ItemTechnofirmaToolHead().SetIconTexture("technofirma:Thaumic Steel Hoe Head").setUnlocalizedName("Thaumic Steel Hoe Head");
TechnofirmaCore.ThaumicSteelSwordHead = new ItemTechnofirmaToolHead().SetIconTexture("technofirma:Thaumic Steel Sword Head").setUnlocalizedName("Thaumic Steel Sword Head");
// Create our items
TechnofirmaCore.ProspectingFocus = new ItemFocusProspecting().setUnlocalizedName("prospecting_focus");
}
public void RegisterRecipes()
{
GameRegistry.addRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelAxe, 1), new Object[] { "#", "%", Character.valueOf('#'), new ItemStack(TechnofirmaCore.ThaumicSteelAxeHead, 1), Character.valueOf('%'), new ItemStack(TFCItems.stick, 1)});
GameRegistry.addRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelShovel, 1), new Object[] { "#", "%", Character.valueOf('#'), new ItemStack(TechnofirmaCore.ThaumicSteelShovelHead, 1), Character.valueOf('%'), new ItemStack(TFCItems.stick, 1)});
GameRegistry.addRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelPickaxe, 1), new Object[] { "#", "%", Character.valueOf('#'), new ItemStack(TechnofirmaCore.ThaumicSteelPickaxeHead, 1), Character.valueOf('%'), new ItemStack(TFCItems.stick, 1)});
GameRegistry.addRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelHoe, 1), new Object[] { "#", "%", Character.valueOf('#'), new ItemStack(TechnofirmaCore.ThaumicSteelHoeHead, 1), Character.valueOf('%'), new ItemStack(TFCItems.stick, 1)});
GameRegistry.addRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelSword, 1), new Object[] { "#", "%", Character.valueOf('#'), new ItemStack(TechnofirmaCore.ThaumicSteelSwordHead, 1), Character.valueOf('%'), new ItemStack(TFCItems.stick, 1)});
GameRegistry.addShapelessRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelIngot, 1), new Object[] { ItemApi.getItem("itemResource", 2), new ItemStack(TFCItems.steelIngot, 1) });
GameRegistry.addRecipe(new ItemStack(TechnofirmaCore.ThaumicAnvil, 1), new Object[] { " ", " ", "###", Character.valueOf('#'), ItemApi.getBlock("blockCosmeticSolid", 4)});
}
public void RegisterEvents()
{
MinecraftForge.EVENT_BUS.register(new ThaumcraftTreeFell());
}
public void RegisterMagicTileEntities()
{
GameRegistry.registerTileEntity(TEMagicAnvil.class, "MagicAnvil");
GameRegistry.registerTileEntity(TETFIngotPile.class, "IngotPile");
}
public void RegisterWailaMessages()
{
// For our dark ore to show up properly in waila
if (TechnofirmaCore.FoundThaumcraft)
{
FMLInterModComms.sendMessage("Waila", "register", "technofirma.WAILA.WDarkOre.callbackRegister");
FMLInterModComms.sendMessage("Waila", "register", "technofirma.WAILA.WTFIngotPile.callbackRegister");
}
}
public void RegisterMagicItems()
{
// Register magic tools
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelAxe, "ThaumicSteelAxe");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelShovel, "ThaumicSteelShovel");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelPickaxe, "ThaumicSteelPickage");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelHoe, "ThaumicSteelHoe");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelSword, "ThaumicSteelSword");
// Register magic tool heads
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelAxeHead, "ThaumicSteelAxeHead");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelShovelHead, "ThaumicSteelShovelHead");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelPickaxeHead, "ThaumicSteelPickaxeHead");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelHoeHead, "ThaumicSteelHoeHead");
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelSwordHead, "ThaumicSteelSwordHead");
// Register magic ingots
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelIngot, "ThaumicSteelIngot");
// Register magic unshaped metals
GameRegistry.registerItem(TechnofirmaCore.ThaumicSteelUnshaped, "ThaumicSteelUnshaped");
// Register our magic foci
GameRegistry.registerItem(TechnofirmaCore.ProspectingFocus, "Prospecting Focus");
}
public void RegisterMagicToolsClasses()
{
TechnofirmaCore.ThaumicSteelAxe.setHarvestLevel("axe", 3);
TechnofirmaCore.ThaumicSteelShovel.setHarvestLevel("shovel", 3);
TechnofirmaCore.ThaumicSteelPickaxe.setHarvestLevel("pickaxe", 3);
}
public void RegisterAnvilPlans()
{
// Get the anvil manager
AnvilManager anvilmgr = AnvilManager.getInstance();
// Prospecting focus
anvilmgr.addPlan("pro_focus", new PlanRecipe(new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.DRAWNOTLAST, RuleEnum.BENDNOTLAST}));
// Iron Wand cap
anvilmgr.addPlan("iron_wand_cap", new PlanRecipe(new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.PUNCHSECONDFROMLAST, RuleEnum.BENDTHIRDFROMLAST}));
}
public void RegisterAnvilRecipes()
{
// Get the anvil manager
AnvilManager anvilmgr = AnvilManager.getInstance();
// Prospecting Focus
anvilmgr.addRecipe(new AnvilRecipe(new ItemStack(TFCItems.steelIngot2x), null, "pro_focus", 70, false, AnvilReq.STEEL.ordinal(), new ItemStack(TechnofirmaCore.ProspectingFocus, 1)).addRecipeSkill(Global.SKILL_TOOLSMITH));
// Iron Wand Cap
anvilmgr.addRecipe(new AnvilRecipe(new ItemStack(TFCItems.wroughtIronIngot), null, "iron_wand_cap", 70, false, AnvilReq.WROUGHTIRON.ordinal(), ItemApi.getItem("itemWandCap", 0)).addRecipeSkill(Global.SKILL_TOOLSMITH));
}
public void RegisterMagicAnvilPlans()
{
// Get the anvil manager
MagicAnvilManager anvilmgr = MagicAnvilManager.getInstance();
// Register our plans
AspectList alist = new AspectList();
alist.add(Aspect.ORDER, 2);
alist.add(Aspect.FIRE, 2);
alist.add(Aspect.AIR, 2);
anvilmgr.addPlan("copper_wand_cap", new MagicPlanRecipe("CAP_copper", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.PUNCHSECONDFROMLAST, RuleEnum.BENDTHIRDFROMLAST}));
alist = new AspectList();
alist.add(Aspect.ORDER, 4);
alist.add(Aspect.FIRE, 4);
alist.add(Aspect.AIR, 4);
anvilmgr.addPlan("silver_wand_cap", new MagicPlanRecipe("CAP_silver", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.PUNCHSECONDFROMLAST, RuleEnum.BENDTHIRDFROMLAST}));
alist = new AspectList();
alist.add(Aspect.ORDER, 3);
alist.add(Aspect.FIRE, 3);
alist.add(Aspect.AIR, 3);
anvilmgr.addPlan("gold_wand_cap", new MagicPlanRecipe("CAP_gold", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.PUNCHSECONDFROMLAST, RuleEnum.BENDTHIRDFROMLAST}));
alist = new AspectList();
anvilmgr.addPlan("thaumiumaxe", new MagicPlanRecipe("aspect.", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.HITSECONDFROMLAST, RuleEnum.UPSETTHIRDFROMLAST}));
anvilmgr.addPlan("thaumiumshovel", new MagicPlanRecipe("aspect.", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.HITNOTLAST, RuleEnum.ANY}));
anvilmgr.addPlan("thaumiumpickaxe", new MagicPlanRecipe("aspect.", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.BENDNOTLAST, RuleEnum.DRAWNOTLAST}));
anvilmgr.addPlan("thaumiumhoe", new MagicPlanRecipe("aspect.", alist, new RuleEnum[]{RuleEnum.PUNCHLAST, RuleEnum.HITNOTLAST, RuleEnum.BENDNOTLAST}));
anvilmgr.addPlan("thaumiumsword", new MagicPlanRecipe("aspect.", alist, new RuleEnum[]{RuleEnum.HITLAST, RuleEnum.BENDSECONDFROMLAST, RuleEnum.BENDTHIRDFROMLAST}));
}
public void RegisterMagicAnvilRecipes()
{
// Get the anvil manager
MagicAnvilManager anvilmgr = MagicAnvilManager.getInstance();
// Register our anvil recipes
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TFCItems.copperIngot), null, "copper_wand_cap", ItemApi.getItem("itemWandCap", 3)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TFCItems.silverIngot), null, "silver_wand_cap", ItemApi.getItem("itemWandCap", 5)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TFCItems.goldIngot), null, "gold_wand_cap", ItemApi.getItem("itemWandCap", 1)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelIngot), null, "thaumiumaxe", new ItemStack(TechnofirmaCore.ThaumicSteelAxeHead, 1)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelIngot), null, "thaumiumshovel", new ItemStack(TechnofirmaCore.ThaumicSteelShovelHead, 1)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelIngot), null, "thaumiumpickaxe", new ItemStack(TechnofirmaCore.ThaumicSteelPickaxeHead, 1)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelIngot), null, "thaumiumhoe", new ItemStack(TechnofirmaCore.ThaumicSteelHoeHead, 1)).addRecipeSkill(Global.SKILL_TOOLSMITH));
anvilmgr.addRecipe(new MagicAnvilRecipe(new ItemStack(TechnofirmaCore.ThaumicSteelIngot), null, "thaumiumsword", new ItemStack(TechnofirmaCore.ThaumicSteelSwordHead, 1)).addRecipeSkill(Global.SKILL_WEAPONSMITH));
}
}
| lgpl-2.1 |
optivo-org/fingbugs-1.3.9-optivo | src/java/edu/umd/cs/findbugs/classfile/impl/ZipInputStreamCodeBase.java | 6328 | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2006, University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.classfile.impl;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import edu.umd.cs.findbugs.classfile.ICodeBaseEntry;
import edu.umd.cs.findbugs.classfile.ICodeBaseIterator;
import edu.umd.cs.findbugs.classfile.ICodeBaseLocator;
import edu.umd.cs.findbugs.io.IO;
import edu.umd.cs.findbugs.util.Archive;
import edu.umd.cs.findbugs.util.MapCache;
/**
* Implementation of ICodeBase to read from a zip file or jar file.
*
* @author David Hovemeyer
*/
public class ZipInputStreamCodeBase extends AbstractScannableCodeBase {
final static boolean DEBUG = false;
final File file;
final MapCache<String, ZipInputStreamCodeBaseEntry> map
= new MapCache<String, ZipInputStreamCodeBaseEntry>(10000);
final HashSet<String> entries = new HashSet<String>();
/**
* Constructor.
*
* @param codeBaseLocator the codebase locator for this codebase
* @param file the File containing the zip file (may be a temp file
* if the codebase was copied from a nested zipfile in
* another codebase)
*/
public ZipInputStreamCodeBase(ICodeBaseLocator codeBaseLocator, File file) throws IOException {
super(codeBaseLocator);
this.file = file;
setLastModifiedTime(file.lastModified());
ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
try {
ZipEntry ze;
if (DEBUG) {
System.out.println("Reading zip input stream " + file);
}
while ((ze = zis.getNextEntry()) != null) {
String name = ze.getName();
if (!ze.isDirectory()
&& (name.equals("META-INF/MANIFEST.MF")
|| name.endsWith(".class")
|| Archive.isArchiveFileName(name)
)) {
entries.add(name);
if (name.equals("META-INF/MANIFEST.MF")) {
map.put(name, build(zis, ze));
}
}
zis.closeEntry();
}
} finally {
zis.close();
}
if (DEBUG) {
System.out.println("Done with zip input stream " + file);
}
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.ICodeBase#lookupResource(java.lang.String)
*/
public ICodeBaseEntry lookupResource(String resourceName) {
// Translate resource name, in case a resource name
// has been overridden and the resource is being accessed
// using the overridden name.
resourceName = translateResourceName(resourceName);
if (!entries.contains(resourceName)) {
return null;
}
try {
ZipInputStreamCodeBaseEntry z = map.get(resourceName);
if (z != null) {
return z;
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
try {
ZipEntry ze;
boolean found = false;
int countDown = 20;
while ((ze = zis.getNextEntry()) != null && countDown >= 0) {
if (ze.getName().equals(resourceName)) {
found = true;
}
if (found) {
countDown--;
if (map.containsKey(ze.getName())) {
continue;
}
z = build(zis, ze);
map.put(ze.getName(), z);
}
zis.closeEntry();
}
} finally {
zis.close();
}
z = map.get(resourceName);
if (z == null) {
throw new AssertionError("Could not find " + resourceName);
}
return z;
} catch (IOException e) {
return null;
}
}
ZipInputStreamCodeBaseEntry build(ZipInputStream zis, ZipEntry ze) throws IOException {
long sz = ze.getSize();
ByteArrayOutputStream out;
if (sz < 0 || sz > Integer.MAX_VALUE) {
out = new ByteArrayOutputStream();
} else {
out = new ByteArrayOutputStream((int) sz);
}
IO.copy(zis, out);
byte[] bytes = out.toByteArray();
setLastModifiedTime(ze.getTime());
return new ZipInputStreamCodeBaseEntry(this, ze, bytes);
}
class MyIterator implements ICodeBaseIterator {
ZipInputStream zis;
ZipEntry ze;
MyIterator() {
try {
zis = new ZipInputStream(new FileInputStream(file));
ze = zis.getNextEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void getNextEntry() throws IOException {
ze = zis.getNextEntry();
if (ze == null) {
zis.close();
}
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.ICodeBaseIterator#hasNext()
*/
public boolean hasNext() throws InterruptedException {
if (Thread.interrupted()) {
throw new InterruptedException();
}
return ze != null;
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.ICodeBaseIterator#next()
*/
public ICodeBaseEntry next() throws InterruptedException {
try {
if (Thread.interrupted()) {
throw new InterruptedException();
}
ZipInputStreamCodeBaseEntry z = build(zis, ze);
zis.closeEntry();
getNextEntry();
return z;
} catch (IOException e) {
throw new RuntimeException("Failure getting next entry in " + file, e);
}
}
}
public ICodeBaseIterator iterator() {
return new MyIterator();
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.ICodeBase#getPathName()
*/
public String getPathName() {
return file.getName();
}
/* (non-Javadoc)
* @see edu.umd.cs.findbugs.classfile.ICodeBase#close()
*/
public void close() {
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return file.getName();
}
}
| lgpl-2.1 |
raffy1982/spine-project | Spine_Android_serverApp/src/spine/SPINEManager.java | 21041 | /*****************************************************************
SPINE - Signal Processing In-Node Environment is a framework that
allows dynamic on node configuration for feature extraction and a
OtA protocol for the management for WSN
Copyright (C) 2007 Telecom Italia S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation,
version 2.1 of the License.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*****************************************************************/
/**
*
* This is the SPINE API implementation.
* It is responsible for converting high level application requests into SPINE protocol messages;
* it also handles lower level network activity generating higher level events.
*
* @author Raffaele Gravina
* @author Alessia Salmeri
*
* @version 1.3
*/
package spine;
import jade.util.Logger;
import java.io.InterruptedIOException;
import java.util.Hashtable;
import java.util.Vector;
import spine.datamodel.Address;
import spine.datamodel.Node;
import spine.datamodel.functions.SpineCodec;
import spine.datamodel.functions.SpineFunctionReq;
import spine.datamodel.functions.SpineObject;
import spine.datamodel.functions.SpineSetupFunction;
import spine.datamodel.functions.SpineSetupSensor;
import spine.datamodel.functions.SpineStart;
import spine.datamodel.serviceMessages.ServiceErrorMessage;
import spine.exceptions.MethodNotSupportedException;
import com.tilab.gal.LocalNodeAdapter;
import com.tilab.gal.WSNConnection;
@SuppressWarnings("rawtypes")
public class SPINEManager {
/** package scoped as they are used by EventDispatcher **/
static final byte DISC_COMPL_EVT_COD = 100;
static final String SPINEDATA_FUNCT_CLASSNAME_SUFFIX = "SpineData";
static final String SPINE_SERVICE_MESSAGE_CLASSNAME_SUFFIX = "Message";
static String URL_PREFIX = null;
static String SPINEDATACODEC_PACKAGE = null;
static String SPINE_SERVICE_MESSAGE_CODEC_PACKAGE = null;
WSNConnection connection;
Vector activeNodes = new Vector(); // <values:Node>
Hashtable htInstance = new Hashtable(); // Hash Table class instance
SpineCodec spineCodec = null;
boolean discoveryCompleted = false;
// private object to which SPINEMager delegates the event dispatching functionality
private EventDispatcher eventDispatcher = null;
private static Properties prop = Properties.getDefaultProperties();
private static final String DEF_PROP_MISSING_MSG =
"ERROR: unable to load 'defaults.properties' file.";
private final static long DISCOVERY_TIMEOUT = 2000;
private long discoveryTimeout = DISCOVERY_TIMEOUT;
private boolean started = false;
private LocalNodeAdapter nodeAdapter;
private static String MOTECOM = null;
private static String PLATFORM = null;
private static byte MY_GROUP_ID = 0;
private static String LOCALNODEADAPTER_CLASSNAME = null;
private static final String SPINEDATACODEC_PACKAGE_PREFIX = "spine.payload.codec.";
private static final String SPINE_SERVICE_MESSAGE_CODEC_PACKAGE_PREFIX = "spine.payload.codec.";
private static String MESSAGE_CLASSNAME = null;
private Node baseStation = null;
private static Logger l = Logger.getMyLogger(SPINEManager.class.getName());
/** package-scoped method to get a reference to baseStation **/
final Node getBaseStation() {
return baseStation;
}
/** package-scoped method to know if discovery is completed **/
final boolean isDiscoveryCompleted() {
return discoveryCompleted;
}
/** package-scoped method called by SPINEFactory.
* The caller must guarantee that moteCom and platform and are not null. **/
@SuppressWarnings("unchecked")
SPINEManager(String moteCom, String platform/*, int btNetworkSize*/) {
try {
MOTECOM = moteCom;
PLATFORM = platform;
MY_GROUP_ID = (byte)Short.parseShort(prop.getProperty(Properties.GROUP_ID_KEY), 16);
LOCALNODEADAPTER_CLASSNAME = prop.getProperty(PLATFORM + "_" + Properties.LOCALNODEADAPTER_CLASSNAME_KEY);
URL_PREFIX = prop.getProperty(PLATFORM + "_" + Properties.URL_PREFIX_KEY);
SPINEDATACODEC_PACKAGE = SPINEDATACODEC_PACKAGE_PREFIX +
prop.getProperty(PLATFORM + "_" + Properties.SPINEDATACODEC_PACKAGE_SUFFIX_KEY) + ".";
MESSAGE_CLASSNAME = prop.getProperty(PLATFORM + "_" + Properties.MESSAGE_CLASSNAME_KEY);
SPINE_SERVICE_MESSAGE_CODEC_PACKAGE = SPINE_SERVICE_MESSAGE_CODEC_PACKAGE_PREFIX +
prop.getProperty(PLATFORM + "_" + Properties.SPINEDATACODEC_PACKAGE_SUFFIX_KEY) + ".";
System.setProperty(Properties.LOCALNODEADAPTER_CLASSNAME_KEY, LOCALNODEADAPTER_CLASSNAME);
nodeAdapter = LocalNodeAdapter.getLocalNodeAdapter();
Vector params = new Vector();
params.addElement(MOTECOM);
nodeAdapter.init(params);
nodeAdapter.start();
connection = nodeAdapter.createAPSConnection();
baseStation = new Node(new Address(""+SPINEPacketsConstants.SPINE_BASE_STATION));
baseStation.setLogicalID(new Address(SPINEPacketsConstants.SPINE_BASE_STATION_LABEL));
eventDispatcher = new EventDispatcher(this);
eventDispatcher.start();
} catch (NumberFormatException e) {
exit(DEF_PROP_MISSING_MSG);
} catch (ClassNotFoundException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
} catch (InstantiationException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
} catch (IllegalAccessException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
}
}
/**
* Returns the EventDispatcher associated to the SPINEManager
*
* @return the EventDispatcher associated to the SPINEManager
*/
public EventDispatcher getEventDispatcher() {
return eventDispatcher;
}
/**
* Adds a SPINEListener to the manager instance
*
* @param listener the listener to register
*/
public void addListener(SPINEListener listener) {
eventDispatcher.addListener(listener);
}
/**
* Remove a SPINEListener from the manager instance
*
* @param listener the listener to deregister
*/
public void removeListener(SPINEListener listener) {
eventDispatcher.removeListener(listener);
}
/**
* Returns the list of the discovered nodes as a Vector of spine.datamodel.Node objects
*
* @return the discovered nodes
*
* @see spine.datamodel.Node
*/
public Vector getActiveNodes() {
return activeNodes;
}
/**
* Returns true if the manager has been asked to start the processing in the wsn; false otherwise
*
* @return true if the manager has been asked to start the processing in the wsn; false otherwise
*/
public boolean isStarted() {
return this.started;
}
/**
* Commands the SPINEManager to discovery the surrounding WSN nodes
* A default timeout of 2s, is used
*/
public void discoveryWsn() {
discoveryCompleted = false;
send(new Address(""+SPINEPacketsConstants.SPINE_BROADCAST), SPINEPacketsConstants.SERVICE_DISCOVERY, null);
if(this.discoveryTimeout > 0)
new DiscoveryTimer(this.discoveryTimeout).start();
}
/**
*
* Commands the SPINEManager to discovery the surrounding WSN nodes
* This method sets the timeout for the discovery procedure.
*
* A timeout <= 0 will disable the Discovery Timer;
* this way a 'discovery complete' event will never be signaled and at any time an
* announcing node is added to the active-nodes list and signaled to the SPINE listeners.
*
* @param discoveryTimeout the timeout for the discovery procedure
*/
public void discoveryWsn(long discoveryTimeout) {
discoveryCompleted = false;
this.discoveryTimeout = discoveryTimeout;
send(new Address(""+SPINEPacketsConstants.SPINE_BROADCAST), SPINEPacketsConstants.SERVICE_DISCOVERY, null);
if(this.discoveryTimeout > 0)
new DiscoveryTimer(this.discoveryTimeout).start();
}
/**
*
* Currently, it does nothing!
*
*/
public void bootUpWsn() {
}
/**
* Setups a specific sensor of the given node.
* Currently, a sensor is setup by providing a sampling time value and a time scale factor
*
* @param node the destination of the request
* @param setupSensor the object containing the setup parameters
*/
public void setup(Node node, SpineSetupSensor setupSensor) {
if (node == null)
throw new RuntimeException("Can't setup the sensor: node is null");
if (setupSensor == null)
throw new RuntimeException("Can't setup the sensor: setupSensor is null");
send(node.getPhysicalID(), SPINEPacketsConstants.SETUP_SENSOR, setupSensor);
}
/**
* Setups a specific function of the given node.
* The parameters involved are 'function dependent' and are specified by providing a proper
* SpineSetupFunction instantiation object
*
* @param node the destination of the request
* @param setupFunction the object containing the setup parameters
*/
public void setup(Node node, SpineSetupFunction setupFunction) {
if (node == null)
throw new RuntimeException("Can't setup the function: node is null");
if (setupFunction == null)
throw new RuntimeException("Can't setup the function: setupFunction is null");
send(node.getPhysicalID(), SPINEPacketsConstants.SETUP_FUNCTION, setupFunction);
}
/**
* Activates a function (or even only function sub-routines) on the given sensor.
* The content of the actual request is 'function dependent' and it's embedded into the
* 'SpineFunctionReq' instantiations.
*
* @param node the destination of the request
* @param functionReq the specific function activation request
*/
public void activate(Node node, SpineFunctionReq functionReq) {
if (node == null)
throw new RuntimeException("Can't activate the function: node is null");
if (functionReq == null)
throw new RuntimeException("Can't activate the function: functionReq is null");
// function activation requests are differentiated by the deactivation requests by setting the appropriate flag
functionReq.setActivationFlag(true);
send(node.getPhysicalID(), SPINEPacketsConstants.FUNCTION_REQ, functionReq);
}
/**
* Deactivates a function (or even only function sub-routines) on the given sensor.
* The content of the actual request is 'function dependent' and it's embedded into the
* 'SpineFunctionReq' instantiations.
*
* @param node the destination of the request
* @param functionReq the specific function deactivation request
*/
public void deactivate(Node node, SpineFunctionReq functionReq) {
if (node == null)
throw new RuntimeException("Can't deactivate the function: node is null");
if (functionReq == null)
throw new RuntimeException("Can't deactivate the function: functionReq is null");
// function activation requests are differentiated by the deactivation requests by setting the appropriate flag
functionReq.setActivationFlag(false);
send(node.getPhysicalID(), SPINEPacketsConstants.FUNCTION_REQ, functionReq);
}
/**
* Commands the given node to do a 'immediate one-shot' sampling on the given sensor.
* The method won't have any effects if the node is not provided with the given sensor.
*
* @param node the destination of the request
* @param sensorCode the sensor to be sampled
*
* @see spine.SPINESensorConstants
*/
public void getOneShotData(Node node, byte sensorCode) {
SpineSetupSensor sss = new SpineSetupSensor();
sss.setSensor(sensorCode);
sss.setTimeScale(SPINESensorConstants.NOW);
sss.setSamplingTime(0);
setup(node, sss);
}
/**
* Starts the WSN sensing and computing the previously requested functions.
* This is done thru a broadcast SPINE Synchr message.
* This simple start method will let the nodes use their default radio access scheme.
*
* @param radioAlwaysOn low-power radio mode control flag; set it 'true' to disable the radio low-power mode;
* 'false' to allow radio module turn off during 'idle' periods
*/
public void startWsn(boolean radioAlwaysOn) {
startWsn(radioAlwaysOn, false);
}
/**
* Starts the WSN sensing and computing the previously requested functions.
* This is done thru a broadcast SPINE Synchr message.
*
* @param radioAlwaysOn low-power radio mode control flag; set it 'true' to disable the radio low-power mode;
* 'false' to allow radio module turn off during 'idle' periods
*
* @param enableTDMA TDMA transmission scheme control flag; set it 'true' to enable the TDMA on the nodes;
* 'false' to keep using the default radio access scheme.
*/
public void startWsn(boolean radioAlwaysOn, boolean enableTDMA) {
SpineStart ss = new SpineStart();
ss.setActiveNodesCount(activeNodes.size());
ss.setRadioAlwaysOn(radioAlwaysOn);
ss.setEnableTDMA(enableTDMA);
send(new Address(""+SPINEPacketsConstants.SPINE_BROADCAST), SPINEPacketsConstants.START, ss);
started = true;
}
/**
* Commands a software 'on node local clock' synchronization of the whole WSN.
* This is done thru a broadcast SPINE Synchr message.
*/
public void syncWsn() {
send(new Address(""+SPINEPacketsConstants.SPINE_BROADCAST), SPINEPacketsConstants.SYNCR, null);
}
/**
* Commands a software reset of the whole WSN.
* This is done thru a broadcast SPINE Reset message.
*/
public void resetWsn() {
//send(SPINEPacketsConstants.SPINE_BROADCAST, SPINEPacketsConstants.RESET, null);
// broadcast reset is translated into multiple unicast reset as a workaround in the case node are
// communicating in radio low power mode.
for(int i = 0; i<activeNodes.size(); i++)
send(((Node)activeNodes.elementAt(i)).getPhysicalID(), SPINEPacketsConstants.RESET, null);
started = false;
}
/*
* Private utility method containing the actual message send code
*/
@SuppressWarnings("unchecked")
private void send(Address destination, byte pktType, SpineObject payload) {
try {
// dynamic class loading of the proper SpineCodec implementation
if (payload != null){
spineCodec = (SpineCodec)htInstance.get (payload.getClass().getSimpleName());
if (spineCodec==null){
Class p = Class.forName(SPINEDATACODEC_PACKAGE +
payload.getClass().getSimpleName());
spineCodec = (SpineCodec)p.newInstance();
htInstance.put (payload.getClass().getSimpleName(), spineCodec);
}
}
// dynamic class loading of the proper Message implementation
// String messageClassName = prop.getProperty(Properties.MESSAGE_CLASSNAME_KEY);
Class c = (Class)htInstance.get (MESSAGE_CLASSNAME);
if (c == null){
c = Class.forName(MESSAGE_CLASSNAME);
htInstance.put (MESSAGE_CLASSNAME, c);
}
com.tilab.gal.Message msg = (com.tilab.gal.Message)c.newInstance();
// construction of the message
msg.setDestinationURL(URL_PREFIX + destination.getAsInt());
msg.setClusterId(pktType); // the clusterId is treated as the 'packet type' field
msg.setProfileId(MY_GROUP_ID); // the profileId is treated as the 'group id' field
if (payload != null) {
try {
byte[] payloadArray = spineCodec.encode(payload);
short[] payloadShort = new short[payloadArray.length];
for (int i = 0; i<payloadShort.length; i++)
payloadShort[i] = payloadArray[i];
msg.setPayload(payloadShort);
}catch (MethodNotSupportedException e){
e.printStackTrace();
if (SPINEManager.getLogger().isLoggable(Logger.SEVERE))
SPINEManager.getLogger().log(Logger.SEVERE, e.getMessage());
}
}
// message sending
connection.send(msg);
} catch (InstantiationException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
} catch (IllegalAccessException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
} catch (ClassNotFoundException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
} catch (InterruptedIOException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
} catch (UnsupportedOperationException e) {
e.printStackTrace();
if (l.isLoggable(Logger.SEVERE))
l.log(Logger.SEVERE, e.getMessage());
}
}
/**
* Returns the already discovered Node corresponding to the given Address
*
* @param id the physical address of the Node to obtain
* @return the already discovered Node corresponding to the given Address
* or null if doesn't exist any Node with the given Address.
*/
public Node getNodeByPhysicalID(Address id) {
for (int i = 0; i<activeNodes.size(); i++) {
Node curr = (Node)activeNodes.elementAt(i);
if(curr.getPhysicalID().equals(id))
return curr;
}
return null;
}
/**
* Returns the already discovered Node corresponding to the given Address
*
* @param id the logical address of the Node to obtain
* @return the already discovered Node corresponding to the given Address
* or null if doesn't exist any Node with the given Address.
*/
public Node getNodeByLogicalID(Address id) {
for (int i = 0; i<activeNodes.size(); i++) {
Node curr = (Node)activeNodes.elementAt(i);
if(curr.getLogicalID().equals(id))
return curr;
}
return null;
}
/**
* Returns the MOTECOM property value specified in the given app.properties file
*
* @return the MOTECOM property value specified in the given app.properties file
* or the empty string if the MOTECOM property hasn't been specified
*/
public static String getMoteCom() {
return MOTECOM;
}
/**
* Returns the PLATFORM property value specified in the given app.properties file
*
* @return the PLATFORM property value specified in the given app.properties file
* or the empty string if the PLATFORM property hasn't been specified
*/
public static String getPlatform() {
return PLATFORM;
}
/**
* Returns the BT_NETWORK_SIZE property value specified in the given app.properties file.
* Note that this property is meaningful (and mandatory to be present in the app.properties file)
* if and only if the PLATFORM property is 'bt' (bluetooth).
*
* @return the BT_NETWORK_SIZE property value specified in the given app.properties file
* or the -1 if the BT_NETWORK_SIZE property hasn't been specified
*/
/*public static int getBTNetworkSize() {
return BT_NETWORK_SIZE;
}*/
/**
* Returns the Logger to be used by all the SPINE core classes
*
* @return the Logger to be used by all the SPINE core classes
*/
public static Logger getLogger() {
return l;
}
/**
* Returns the MY_GROUP_ID property value specified in the given app.properties file
*
* @return the MY_GROUP_ID property value specified in the dafaults.properties file
*/
public static byte getMyGroupID() {
return MY_GROUP_ID;
}
/*
* implementation of the discovery timer procedure can be simply seen as a
* Thread that, after a certain sleep interval, declares the discovery procedure completed
* (by setting a global boolean flag) and notifies the SPINEListeners of such event
*/
private class DiscoveryTimer extends Thread {
private long delay = 0;
private DiscoveryTimer(long delay) {
this.delay = delay;
}
public void run () {
if (!getPlatform().equalsIgnoreCase(SPINESupportedPlatforms.BLUETOOTH)) {
try {
discoveryCompleted = false;
sleep(delay);
} catch (InterruptedException e) {
}
// if no nodes has been discovered, it's the symptom of some radio connection problem;
// the SPINEManager notifies the SPINEListener of that situation by issuing an appropriate service message
if (activeNodes.size() == 0) {
ServiceErrorMessage serviceErrorMessage = new ServiceErrorMessage();
serviceErrorMessage.setNode(baseStation);
serviceErrorMessage.setMessageDetail(SPINEServiceMessageConstants.CONNECTION_FAIL);
eventDispatcher.notifyListeners(SPINEPacketsConstants.SVC_MSG, serviceErrorMessage);
}
discoveryCompleted = true;
eventDispatcher.notifyListeners(DISC_COMPL_EVT_COD, activeNodes);
}
}
}
private static void exit(String msg) {
if (l.isLoggable(Logger.SEVERE)) {
StringBuffer str = new StringBuffer();
str.append(msg);
str.append("\r\n");
str.append("Will exit now!");
l.log(Logger.SEVERE, str.toString());
}
System.exit(-1);
}
}
| lgpl-2.1 |
TedaLIEz/ParsingPlayer | parsingplayer/src/main/java/com/hustunique/parsingplayer/player/media/VideoRenderThread.java | 12447 | /*
* Copyright (c) 2017 UniqueStudio
*
*
* This file is part of ParsingPlayer.
*
* ParsingPlayer is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
*
* You should have received a copy of the GNU Lesser General Public
* License along with ParsingPlayer; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package com.hustunique.parsingplayer.player.media;
import android.graphics.Bitmap;
import android.graphics.SurfaceTexture;
import android.opengl.GLES20;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.support.annotation.WorkerThread;
import android.util.Log;
import com.hustunique.parsingplayer.util.LogUtil;
import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import static android.os.Process.THREAD_PRIORITY_BACKGROUND;
/**
* Created by JianGuo on 2/23/17.
* {@link HandlerThread} used for gles rendering
*/
class VideoRenderThread extends HandlerThread {
private Handler mWorker;
private WeakReference<SurfaceTexture> mNativeWindow;
private static final String TAG = "VideoRenderThread";
private static final int EGL_OPENGL_ES2_BIT = 0x4;
private static final int EGL_BACK_BUFFER = 0x3084;
private static final int EGL_CONTEXT_CLIENT_VERSION = 0x3098;
private static final int[] EGL_CONFIG_ATTRIBUTE_LIST = new int[] {
EGL10.EGL_RENDERABLE_TYPE, EGL_OPENGL_ES2_BIT,
EGL10.EGL_SURFACE_TYPE, EGL10.EGL_WINDOW_BIT,
EGL10.EGL_RED_SIZE, 8,
EGL10.EGL_GREEN_SIZE, 8,
EGL10.EGL_BLUE_SIZE, 8,
EGL10.EGL_ALPHA_SIZE, 8,
EGL10.EGL_DEPTH_SIZE, 0,
EGL10.EGL_STENCIL_SIZE, 0,
EGL10.EGL_NONE
};
private static final int[] EGL_SURFACE_ATTRIBUTE_LIST = new int[] {
EGL10.EGL_RENDER_BUFFER, EGL_BACK_BUFFER,
EGL10.EGL_NONE
};
private static final int[] EGL_CONTEXT_ATTRIBUTE_LIST = new int[] {
EGL_CONTEXT_CLIENT_VERSION, 2,
EGL10.EGL_NONE
};
private static final String VERTEX_SHADER = "" +
"attribute vec4 aPosition;\n" +
"attribute vec2 aTexCoord;\n" +
"\n" +
"varying vec2 vTexCoord;\n" +
"\n" +
"void main() {\n" +
" vTexCoord = aTexCoord;\n" +
" gl_Position = aPosition;\n" +
"}";
private static final String FRAGMENT_SHADER = "" +
"precision mediump float;\n" +
"uniform sampler2D sTexture;\n" +
"\n" +
"varying vec2 vTexCoord;\n" +
"\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTexCoord);\n" +
"}";
private static final String FRAGMENT_SHADER_OES = "" +
"#extension GL_OES_EGL_image_external : require\n" +
"precision mediump float;\n" +
"uniform samplerExternalOES sTexture;\n" +
"\n" +
"varying vec2 vTexCoord;\n" +
"\n" +
"void main() {\n" +
" gl_FragColor = texture2D(sTexture, vTexCoord);\n" +
"}";
private static final float[] VERTEX_COORDINATE = new float[] {
-1.0f, +1.0f, 0.0f,
+1.0f, +1.0f, 0.0f,
-1.0f, -1.0f, 0.0f,
+1.0f, -1.0f, 0.0f
};
private static final float[] TEXTURE_COORDINATE = new float[] {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f
};
private static ByteBuffer vertexByteBuffer;
private static ByteBuffer textureByteBuffer;
static {
vertexByteBuffer = ByteBuffer.allocateDirect(VERTEX_COORDINATE.length * 4);
vertexByteBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer().put(VERTEX_COORDINATE);
vertexByteBuffer.rewind();
textureByteBuffer = ByteBuffer.allocateDirect(TEXTURE_COORDINATE.length * 4);
textureByteBuffer.order(ByteOrder.nativeOrder()).asFloatBuffer().put(TEXTURE_COORDINATE);
textureByteBuffer.rewind();
}
private EGL10 egl10;
private EGLDisplay eglDisplay;
private EGLSurface eglSurface;
private EGLContext eglContext;
VideoRenderThread() {
this(TAG);
}
private VideoRenderThread(String name) {
this(name, THREAD_PRIORITY_BACKGROUND);
}
private VideoRenderThread(String name, int priority) {
super(name, priority);
}
@Override
protected void onLooperPrepared() {
super.onLooperPrepared();
setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread t, Throwable e) {
LogUtil.wtf(TAG, e);
t.interrupt();
}
});
}
@WorkerThread
private void initEGL() {
egl10 = (EGL10) EGLContext.getEGL();
eglDisplay = egl10.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
if (eglDisplay == EGL10.EGL_NO_DISPLAY) {
raiseEGLInitError();
}
int[] majorMinorVersions = new int[2];
if (!egl10.eglInitialize(eglDisplay, majorMinorVersions)) {
raiseEGLInitError();
}
EGLConfig[] eglConfigs = new EGLConfig[1];
int[] numOfConfigs = new int[1];
if (!egl10.eglChooseConfig(eglDisplay, EGL_CONFIG_ATTRIBUTE_LIST, eglConfigs, 1, numOfConfigs)) {
raiseEGLInitError();
}
LogUtil.v(TAG, "createWindowSurface by" + mNativeWindow.get());
eglSurface = egl10.eglCreateWindowSurface(eglDisplay, eglConfigs[0], mNativeWindow.get(), EGL_SURFACE_ATTRIBUTE_LIST);
if (eglSurface == EGL10.EGL_NO_SURFACE) {
raiseEGLInitError();
}
eglContext = egl10.eglCreateContext(eglDisplay, eglConfigs[0], EGL10.EGL_NO_CONTEXT, EGL_CONTEXT_ATTRIBUTE_LIST);
if (eglContext == EGL10.EGL_NO_CONTEXT) {
raiseEGLInitError();
}
if (!egl10.eglMakeCurrent(eglDisplay, eglSurface, eglSurface, eglContext)) {
raiseEGLInitError();
}
LogUtil.d(TAG, "initEGL");
}
private void raiseEGLInitError() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
throw new RuntimeException("EGL INIT ERROR " + egl10.eglGetError() + " " +
GLUtils.getEGLErrorString(egl10.eglGetError()));
}
}
private void checkGLESError(String where) {
int error = GLES20.glGetError();
if (error != GLES20.GL_NO_ERROR) {
LogUtil.e(TAG, "checkGLESError: " + GLU.gluErrorString(error));
throw new RuntimeException(where);
}
}
@WorkerThread
private void shutdownEGL() {
LogUtil.d(TAG, "shutdownEGL");
egl10.eglMakeCurrent(eglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
egl10.eglDestroyContext(eglDisplay, eglContext);
egl10.eglDestroySurface(eglDisplay, eglSurface);
egl10.eglTerminate(eglDisplay);
eglContext = EGL10.EGL_NO_CONTEXT;
eglSurface = EGL10.EGL_NO_SURFACE;
eglDisplay = EGL10.EGL_NO_DISPLAY;
}
void prepareHandler() {
mWorker = new Handler(getLooper(), new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
Bitmap bitmap = (Bitmap) msg.obj;
boolean recycled = msg.arg1 != 0;
LogUtil.w(TAG, "start rendering: {" + bitmap + ", size: " +
bitmap.getAllocationByteCount() + ", \n recycled: "
+ recycled + ", \n textureSurface: " + mNativeWindow.get() + "}");
initEGL();
performRenderPoster(bitmap, recycled);
shutdownEGL();
return true;
}
});
LogUtil.v(TAG, "Handler prepared!");
}
@WorkerThread
private void performRenderPoster(Bitmap bitmap, boolean recycled) {
int texture = createTexture(bitmap, recycled, GLES20.GL_TEXTURE_2D);
int program = GLES20.glCreateProgram();
if (program == 0) {
checkGLESError("create program");
}
int vertexShader = createShader(GLES20.GL_VERTEX_SHADER, VERTEX_SHADER);
int fragmentShader = createShader(GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER);
GLES20.glAttachShader(program, vertexShader);
checkGLESError("attach shader " + vertexShader);
GLES20.glAttachShader(program, fragmentShader);
checkGLESError("attach shader " + fragmentShader);
GLES20.glLinkProgram(program);
int[] linked = new int[1];
GLES20.glGetProgramiv(program, GLES20.GL_LINK_STATUS, linked, 0);
if (linked[0] == 0) {
checkGLESError("link program " + GLES20.glGetProgramInfoLog(program));
}
GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);
GLES20.glUseProgram(program);
checkGLESError("use program");
int positionIndex = GLES20.glGetAttribLocation(program, "aPosition");
int texcoordIndex = GLES20.glGetAttribLocation(program, "aTexCoord");
GLES20.glVertexAttribPointer(positionIndex, 3, GLES20.GL_FLOAT, false, 0, vertexByteBuffer);
GLES20.glVertexAttribPointer(texcoordIndex, 2, GLES20.GL_FLOAT, false, 0, textureByteBuffer);
GLES20.glEnableVertexAttribArray(positionIndex);
GLES20.glEnableVertexAttribArray(texcoordIndex);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, texture);
int tex = GLES20.glGetUniformLocation(program, "sTexture");
GLES20.glUniform1i(tex, 0);
GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);
egl10.eglSwapBuffers(eglDisplay, eglSurface);
Log.d(TAG, "performRenderPoster");
GLES20.glDisableVertexAttribArray(positionIndex);
GLES20.glDisableVertexAttribArray(texcoordIndex);
}
private int createTexture(Bitmap bitmap, boolean recycled, int target) {
int[] textures = new int[1];
GLES20.glGenTextures(1, textures, 0);
checkGLESError("gen texture");
GLES20.glBindTexture(target, textures[0]);
checkGLESError("bind texture");
GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
GLES20.glTexParameteri(target, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
GLUtils.texImage2D(target, 0, bitmap, 0);
if (recycled && !bitmap.isRecycled()) {
bitmap.recycle();
}
checkGLESError("tex image 2d");
return textures[0];
}
private int createShader(int shaderType, String shaderString) {
int shader = GLES20.glCreateShader(shaderType);
if (shader == 0) {
checkGLESError("create shader " + shaderType);
}
GLES20.glShaderSource(shader, shaderString);
GLES20.glCompileShader(shader);
int[] compiled = new int[1];
GLES20.glGetShaderiv(shader, GLES20.GL_COMPILE_STATUS, compiled, 0);
if (compiled[0] == 0) {
GLES20.glDeleteShader(shader);
checkGLESError("compile shader " + shaderType);
}
return shader;
}
void render(Bitmap bitmap, boolean recycled, SurfaceTexture surfaceTexture) {
mNativeWindow = new WeakReference<>(surfaceTexture);
Message msg = mWorker.obtainMessage();
msg.obj = bitmap;
msg.arg1 = recycled ? 1 : 0;
LogUtil.v(TAG, "send rending message : " + msg);
mWorker.sendMessage(msg);
}
}
| lgpl-2.1 |
FinnK/lems2hdl | src/main/java/ie/nuigalway/lems2hdl/VHDLUtils.java | 5589 | package ie.nuigalway.lems2hdl;
import ie.nuigalway.lems2hdl.VHDLConfiguration;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.lemsml.jlems.core.sim.ContentError;
import org.lemsml.jlems.core.type.ComponentType;
import org.lemsml.jlems.core.type.Lems;
public class VHDLUtils {
public static boolean isAlive( Process p ) {
try
{
p.exitValue();
return false;
} catch (IllegalThreadStateException e) {
return true;
}
}
public static void createAndPrintDependancyTree(Lems lems) throws ContentError
{
createAndPrintDependancyTree( lems, null);
}
public static void createAndPrintDependancyTree(Lems lems, String startWith) throws ContentError
{
createAndPrintDependancyTree( lems, startWith,0);
}
public static void createAndPrintDependancyTree(Lems lems, String startWith, int level) throws ContentError
{
List<ComponentType> containedComponents = new ArrayList<ComponentType>();
for (ComponentType entry : lems.getComponentTypes()) {
if ((startWith == null && entry.eXtends == null) )
{
containedComponents.add(entry);
}
else if (startWith != null && entry.eXtends != null && entry.eXtends.matches((lems.getComponentTypeByName(startWith).getName())))
{
containedComponents.add(entry);
}
}
for (ComponentType entry : containedComponents) {
StringBuilder spacesSB = new StringBuilder();
for (int i = 0; i < level; i++)
{
spacesSB.append(" > ");
}
System.out.println(spacesSB.toString() + entry.name + " : "); //entry.addDynamics();
createAndPrintDependancyTree( lems, entry.getName(), level + 1);
}
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileInputStream from = null;
FileOutputStream to = null;
try {
from = new FileInputStream(sourceFile);
to = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = from.read(buffer)) != -1)
to.write(buffer, 0, bytesRead); // write
}
finally {
if (from != null)
try {
from.close();
} catch (IOException e) {
;
}
if (to != null)
try {
to.close();
} catch (IOException e) {
;
}
}
}
public static byte[] getMD5ForFile(File file) throws NoSuchAlgorithmException, IOException
{
MessageDigest md = MessageDigest.getInstance("MD5");
try {
InputStream is = new FileInputStream(file.getAbsolutePath());
DigestInputStream dis = new DigestInputStream(is, md);
/* Read stream to EOF as normal... */
while (dis.read() != -1)
{}
}
catch (Exception e)
{
String error = e.getMessage();
}
byte[] digest = md.digest();
return digest;
}
public static byte[] getMD5ForString(String data) throws NoSuchAlgorithmException, IOException
{
MessageDigest md = MessageDigest.getInstance("MD5");
try {
InputStream is = new ByteArrayInputStream(data.getBytes(Charset.forName("UTF-8")));
DigestInputStream dis = new DigestInputStream(is, md);
/* Read stream to EOF as normal... */
while (dis.read() != -1)
{}
}
catch (Exception e)
{
String error = e.getMessage();
}
byte[] digest = md.digest();
return digest;
}
public static byte[] getMD5ForDir(String directory,final String fileExt) throws NoSuchAlgorithmException, IOException
{
MessageDigest md = MessageDigest.getInstance("MD5");
File dir = new File(directory);
File [] files = dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(fileExt);
}
});
for (File file : files) {
byte[] md5_file = getMD5ForFile(file);
md.update(md5_file);
}
return md.digest();
}
public static String lookForMatchingVHDLDirectory(VHDLConfiguration config, String thisDirectory) throws NoSuchAlgorithmException, IOException
{
byte[] md5_wanted = getMD5ForDir(thisDirectory,".vhdl");
File dir = new File(config.WORKDIR);
String[] directories = dir.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
for (int i = 0; i < directories.length; i++)
{
File dir1 = new File(directories[i]);
File dir2 = new File(thisDirectory);
if (dir1.equals(dir2))
continue;
byte[] md5_this = getMD5ForDir(config.WORKDIR + File.separator + directories[i] + File.separator + "Synth_output",".vhdl");
if (Arrays.equals(md5_this,md5_wanted))
{
File fileExisting = new File(config.WORKDIR + File.separator + directories[i] + File.separator + "Synth_output" +
File.separator + "dlm.bit");
if (fileExisting.exists())
{
return directories[i];
}
}
}
return null;
}
}
| lgpl-3.0 |
mWater/minimongo | test/v2/RemoteDb.ts | 4250 | // TODO: This file was created by bulk-decaffeinate.
// Sanity-check the conversion and remove this comment.
let RemoteDb
import _ from "lodash"
import $ from "jquery"
import { createUid } from "./utils"
export default RemoteDb = class RemoteDb {
// Url must have trailing /
constructor(url: any, client: any) {
this.url = url
this.client = client
this.collections = {}
}
addCollection(name: any) {
const collection = new Collection(name, this.url + name, this.client)
this[name] = collection
return (this.collections[name] = collection)
}
removeCollection(name: any) {
delete this[name]
return delete this.collections[name]
}
}
// Remote collection on server
class Collection {
constructor(name: any, url: any, client: any) {
this.name = name
this.url = url
this.client = client
}
// error is called with jqXHR
find(selector: any, options = {}) {
return {
fetch: (success: any, error: any) => {
// Create url
const params = {}
if (options.sort) {
params.sort = JSON.stringify(options.sort)
}
if (options.limit) {
params.limit = options.limit
}
if (options.fields) {
params.fields = JSON.stringify(options.fields)
}
if (this.client) {
params.client = this.client
}
params.selector = JSON.stringify(selector || {})
// Add timestamp for Android 2.3.6 bug with caching
if (navigator.userAgent.toLowerCase().indexOf("android 2.3") !== -1) {
params._ = new Date().getTime()
}
const req = $.getJSON(this.url, params)
req.done((data: any, textStatus: any, jqXHR: any) => success(data))
return req.fail(function (jqXHR: any, textStatus: any, errorThrown: any) {
if (error) {
return error(jqXHR)
}
})
}
}
}
// error is called with jqXHR
findOne(selector: any, options = {}, success: any, error: any) {
if (_.isFunction(options)) {
;[options, success, error] = [{}, options, success]
}
// Create url
const params = {}
if (options.sort) {
params.sort = JSON.stringify(options.sort)
}
params.limit = 1
if (this.client) {
params.client = this.client
}
params.selector = JSON.stringify(selector || {})
// Add timestamp for Android 2.3.6 bug with caching
if (navigator.userAgent.toLowerCase().indexOf("android 2.3") !== -1) {
params._ = new Date().getTime()
}
const req = $.getJSON(this.url, params)
req.done((data: any, textStatus: any, jqXHR: any) => success(data[0] || null))
return req.fail(function (jqXHR: any, textStatus: any, errorThrown: any) {
if (error) {
return error(jqXHR)
}
})
}
// error is called with jqXHR
upsert(doc: any, success: any, error: any) {
let url
if (!this.client) {
throw new Error("Client required to upsert")
}
if (!doc._id) {
doc._id = createUid()
}
// Add timestamp for Android 2.3.6 bug with caching
if (navigator.userAgent.toLowerCase().indexOf("android 2.3") !== -1) {
url = this.url + "?client=" + this.client + "&_=" + new Date().getTime()
} else {
url = this.url + "?client=" + this.client
}
const req = $.ajax(url, {
data: JSON.stringify(doc),
contentType: "application/json",
type: "POST"
})
req.done((data: any, textStatus: any, jqXHR: any) => success(data || null))
return req.fail(function (jqXHR: any, textStatus: any, errorThrown: any) {
if (error) {
return error(jqXHR)
}
})
}
// error is called with jqXHR
remove(id: any, success: any, error: any) {
if (!this.client) {
throw new Error("Client required to remove")
}
const req = $.ajax(this.url + "/" + id + "?client=" + this.client, { type: "DELETE" })
req.done((data: any, textStatus: any, jqXHR: any) => success())
return req.fail(function (jqXHR: any, textStatus: any, errorThrown: any) {
// 410 means already deleted
if (jqXHR.status === 410) {
return success()
} else if (error) {
return error(jqXHR)
}
})
}
}
| lgpl-3.0 |
sobiens/webcomponents | Sobiens.Web.Components/Scripts/Tutorials/SP/soby.news.d.ts | 107 | declare function soby_PopulateNews(): void;
declare function soby_PopulateSPNewsImages(itemID: any): void;
| lgpl-3.0 |
FDVSolutions/DynamicJasper | src/test/java/ar/com/fdvs/dj/test/groups/labels/GroupLabelTest4.java | 9125 | /*
* DynamicJasper: A library for creating reports dynamically by specifying
* columns, groups, styles, etc. at runtime. It also saves a lot of development
* time in many cases! (http://sourceforge.net/projects/dynamicjasper)
*
* Copyright (C) 2008 FDV Solutions (http://www.fdvsolutions.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
*
* License as published by the Free Software Foundation; either
*
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
*
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
*
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
*
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*
*/
package ar.com.fdvs.dj.test.groups.labels;
import java.awt.Color;
import java.util.Map;
import net.sf.jasperreports.view.JasperDesignViewer;
import net.sf.jasperreports.view.JasperViewer;
import ar.com.fdvs.dj.domain.AutoText;
import ar.com.fdvs.dj.domain.DJCalculation;
import ar.com.fdvs.dj.domain.DJGroupLabel;
import ar.com.fdvs.dj.domain.DynamicReport;
import ar.com.fdvs.dj.domain.ExpressionHelper;
import ar.com.fdvs.dj.domain.ImageBanner;
import ar.com.fdvs.dj.domain.StringExpression;
import ar.com.fdvs.dj.domain.Style;
import ar.com.fdvs.dj.domain.builders.ColumnBuilder;
import ar.com.fdvs.dj.domain.builders.DynamicReportBuilder;
import ar.com.fdvs.dj.domain.builders.GroupBuilder;
import ar.com.fdvs.dj.domain.builders.StyleBuilder;
import ar.com.fdvs.dj.domain.constants.Border;
import ar.com.fdvs.dj.domain.constants.Font;
import ar.com.fdvs.dj.domain.constants.GroupLayout;
import ar.com.fdvs.dj.domain.constants.HorizontalAlign;
import ar.com.fdvs.dj.domain.constants.LabelPosition;
import ar.com.fdvs.dj.domain.constants.Transparency;
import ar.com.fdvs.dj.domain.constants.VerticalAlign;
import ar.com.fdvs.dj.domain.entities.DJGroup;
import ar.com.fdvs.dj.domain.entities.columns.AbstractColumn;
import ar.com.fdvs.dj.domain.entities.columns.PropertyColumn;
import ar.com.fdvs.dj.test.BaseDjReportTest;
public class GroupLabelTest4 extends BaseDjReportTest {
public DynamicReport buildReport() throws Exception {
Style detailStyle = new Style();
Style headerStyle = new Style();
headerStyle.setFont(Font.ARIAL_MEDIUM_BOLD);
headerStyle.setBorderBottom(Border.PEN_1_POINT());
headerStyle.setBackgroundColor(Color.gray);
headerStyle.setTextColor(Color.white);
headerStyle.setHorizontalAlign(HorizontalAlign.CENTER);
headerStyle.setVerticalAlign(VerticalAlign.MIDDLE);
headerStyle.setTransparency(Transparency.OPAQUE);
Style headerVariables = new Style();
headerVariables.setFont(Font.ARIAL_MEDIUM_BOLD);
// headerVariables.setBorder(Border.THIN());
headerVariables.setHorizontalAlign(HorizontalAlign.RIGHT);
headerVariables.setVerticalAlign(VerticalAlign.TOP);
Style titleStyle = new Style();
titleStyle.setFont(new Font(18, Font._FONT_VERDANA, true));
Style importeStyle = new Style();
importeStyle.setHorizontalAlign(HorizontalAlign.RIGHT);
Style oddRowStyle = new Style();
oddRowStyle.setBorder(Border.NO_BORDER());
oddRowStyle.setBackgroundColor(Color.LIGHT_GRAY);
oddRowStyle.setTransparency(Transparency.OPAQUE);
DynamicReportBuilder drb = new DynamicReportBuilder();
Integer margin = 20;
drb
.setTitleStyle(titleStyle)
.setTitle("November " + getYear() +" sales report") //defines the title of the report
.setSubtitle("The items in this report correspond "
+"to the main products: DVDs, Books, Foods and Magazines")
.setDetailHeight(15).setLeftMargin(margin)
.setRightMargin(margin).setTopMargin(margin).setBottomMargin(margin)
.setPrintBackgroundOnOddRows(false)
.setGrandTotalLegend("Grand Total")
.setGrandTotalLegendStyle(headerVariables)
.setDefaultStyles(titleStyle, null, headerStyle, detailStyle)
.setPrintColumnNames(true)
.addImageBanner(System.getProperty("user.dir") +"/target/test-classes/images/logo_fdv_solutions_60.png", 100, 30, ImageBanner.Alignment.Right)
.setOddRowBackgroundStyle(oddRowStyle);
AbstractColumn columnState = ColumnBuilder.getNew()
.setColumnProperty("state", String.class.getName())
.setTitle("State").setWidth(new Integer(85))
//.setStyle(titleStyle).setHeaderStyle(titleStyle)
.build();
AbstractColumn columnBranch = ColumnBuilder.getNew()
.setColumnProperty("branch", String.class.getName())
.setTitle("Branch").setWidth(new Integer(85))
.setStyle(detailStyle).setHeaderStyle(headerStyle)
.build();
AbstractColumn columnaProductLine = ColumnBuilder.getNew()
.setColumnProperty("productLine", String.class.getName())
.setTitle("Product Line").setWidth(new Integer(85))
.setStyle(detailStyle).setHeaderStyle(headerStyle)
.build();
AbstractColumn columnaItem = ColumnBuilder.getNew()
.setColumnProperty("item", String.class.getName())
.setTitle("Item").setWidth(new Integer(85))
.setStyle(detailStyle).setHeaderStyle(headerStyle)
.build();
AbstractColumn columnCode = ColumnBuilder.getNew()
.setColumnProperty("id", Long.class.getName())
.setTitle("ID").setWidth(new Integer(40))
.setStyle(importeStyle).setHeaderStyle(headerStyle)
.build();
AbstractColumn columnaQuantity = ColumnBuilder.getNew()
.setColumnProperty("quantity", Long.class.getName())
.setTitle("Quantity").setWidth(new Integer(80))
.setStyle(importeStyle).setHeaderStyle(headerStyle)
.build();
AbstractColumn columnAmount = ColumnBuilder.getNew()
.setColumnProperty("amount", Float.class.getName())
.setTitle("Amount").setWidth(new Integer(90)).setPattern("$ 0.00")
.setStyle(importeStyle).setHeaderStyle(headerStyle)
.build();
GroupBuilder gb1 = new GroupBuilder("group_state");
Style glabelStyle = new StyleBuilder(false).setFont(Font.ARIAL_SMALL)
.setHorizontalAlign(HorizontalAlign.RIGHT).setBorderTop(Border.THIN())
.setStretchWithOverflow(false)
.build();
DJGroupLabel glabel1 = new DJGroupLabel(new StringExpression() {
public Object evaluate(Map fields, Map variables, Map parameters) {
return "Total amount";
}
},glabelStyle,LabelPosition.TOP);
DJGroupLabel glabel2 = new DJGroupLabel("Total quantity",glabelStyle,LabelPosition.TOP);
Style glabelStyle2 = new Style();
glabelStyle2.setHorizontalAlign(HorizontalAlign.CENTER);
glabelStyle2.setTextColor(Color.BLUE);
DJGroupLabel glabel3 = new DJGroupLabel(new StringExpression() {
public Object evaluate(Map fields, Map variables, Map parameters) {
return "group: \"" + variables.get("state_name") + "\", count: " + ExpressionHelper.getGroupCount("group_state", variables);
}
},glabelStyle2,LabelPosition.TOP);
// define the criteria column to group by (columnState)
DJGroup g1 = gb1.setCriteriaColumn((PropertyColumn) columnState)
.addVariable("state_name", columnState, DJCalculation.FIRST)
.addFooterVariable(columnAmount,DJCalculation.SUM,headerVariables, null, glabel1) // tell the group place a variable footer of the column "columnAmount" with the SUM of allvalues of the columnAmount in this group.
.addFooterVariable(columnaQuantity,DJCalculation.SUM,headerVariables, null, glabel2) // idem for the columnaQuantity column
.setGroupLayout(GroupLayout.VALUE_IN_HEADER) // tells the group how to be shown, there are manyposibilities, see the GroupLayout for more.
.setFooterLabel(glabel3)
.setFooterVariablesHeight(30)
.build();
GroupBuilder gb2 = new GroupBuilder(); // Create another group (using another column as criteria)
DJGroup g2 = gb2.setCriteriaColumn((PropertyColumn) columnBranch) // and we add the same operations for the columnAmount and
.addFooterVariable(columnAmount,DJCalculation.SUM) // columnaQuantity columns
.addFooterVariable(columnaQuantity, DJCalculation.SUM)
.build();
drb.addColumn(columnState);
drb.addColumn(columnBranch);
drb.addColumn(columnaProductLine);
// drb.addColumn(columnaItem);
// drb.addColumn(columnCode);
drb.addColumn(columnaQuantity);
drb.addColumn(columnAmount);
drb.addGlobalFooterVariable(columnAmount, DJCalculation.SUM, headerVariables, null);
drb.addGlobalFooterVariable(columnaQuantity, DJCalculation.SUM, headerVariables, null);
drb.addGroup(g1); // add group g1
// drb.addGroup(g2); // add group g2
drb.setUseFullPageWidth(true);
drb.addAutoText(AutoText.AUTOTEXT_PAGE_X_SLASH_Y, AutoText.POSITION_FOOTER, AutoText.ALIGNMENT_RIGHT);
DynamicReport dr = drb.build();
return dr;
}
public static void main(String[] args) throws Exception {
GroupLabelTest4 test = new GroupLabelTest4();
test.testReport();
test.exportToJRXML();
JasperViewer.viewReport(test.jp);
JasperDesignViewer.viewReportDesign(test.jr);
}
} | lgpl-3.0 |
univmobile/unm-backend | unm-backend-core/src/main/java/fr/univmobile/backend/core/LoginConversation.java | 121 | package fr.univmobile.backend.core;
public interface LoginConversation {
String getLoginToken();
String getKey();
}
| lgpl-3.0 |
flannelhead/espway | frontend/src/riot-loader.js | 164 | var riot = require('riot-compiler');
module.exports = function(source) {
this.cacheable();
return "import riot from 'riot';\n" + riot.compile(source);
};
| lgpl-3.0 |
PocketSoftMine/SoftMine | src/softmine/Block/Transparent.php | 838 | <?php
/*
*
* ____ _ _ __ __ _ __ __ ____
* | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
* | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
* | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
* |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* @author PocketMine Team
* @link http://www.pocketmine.net/
*
*
*/
namespace softmine\block;
abstract class Transparent extends Block{
public function isTransparent(){
return true;
}
} | lgpl-3.0 |
joerivandervelde/molgenis | molgenis-data-elasticsearch/src/main/java/org/molgenis/data/elasticsearch/request/QueryGenerator.java | 27202 | package org.molgenis.data.elasticsearch.request;
import static org.molgenis.data.elasticsearch.index.ElasticsearchIndexCreator.DEFAULT_ANALYZER;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.DisMaxQueryBuilder;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.FilterBuilders;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.molgenis.MolgenisFieldTypes.FieldTypeEnum;
import org.molgenis.data.AttributeMetaData;
import org.molgenis.data.Entity;
import org.molgenis.data.EntityMetaData;
import org.molgenis.data.MolgenisQueryException;
import org.molgenis.data.Query;
import org.molgenis.data.QueryRule;
import org.molgenis.data.QueryRule.Operator;
import org.molgenis.data.UnknownAttributeException;
import org.molgenis.data.elasticsearch.ElasticsearchService;
import org.molgenis.data.elasticsearch.index.MappingsBuilder;
import org.molgenis.util.MolgenisDateFormat;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
/**
* Creates Elasticsearch query from MOLGENIS query
*/
public class QueryGenerator implements QueryPartGenerator
{
public static final String ATTRIBUTE_SEPARATOR = ".";
@Override
public void generate(SearchRequestBuilder searchRequestBuilder, Query query, EntityMetaData entityMetaData)
{
List<QueryRule> queryRules = query.getRules();
if (queryRules == null || queryRules.isEmpty()) return;
QueryBuilder q = createQueryBuilder(queryRules, entityMetaData);
searchRequestBuilder.setQuery(q);
}
public QueryBuilder createQueryBuilder(List<QueryRule> queryRules, EntityMetaData entityMetaData)
{
QueryBuilder queryBuilder;
final int nrQueryRules = queryRules.size();
if (nrQueryRules == 1)
{
// simple query consisting of one query clause
queryBuilder = createQueryClause(queryRules.get(0), entityMetaData);
}
else
{
// boolean query consisting of combination of query clauses
Operator occur = null;
BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
for (int i = 0; i < nrQueryRules; i += 2)
{
QueryRule queryRule = queryRules.get(i);
// determine whether this query is a 'not' query
if (queryRule.getOperator() == Operator.NOT)
{
occur = Operator.NOT;
queryRule = queryRules.get(i + 1);
i += 1;
}
else if (i + 1 < nrQueryRules)
{
QueryRule occurQueryRule = queryRules.get(i + 1);
Operator occurOperator = occurQueryRule.getOperator();
if (occurOperator == null) throw new MolgenisQueryException("Missing expected occur operator");
switch (occurOperator)
{
case AND:
case OR:
if (occur != null && occurOperator != occur)
{
throw new MolgenisQueryException(
"Mixing query operators not allowed, use nested queries");
}
occur = occurOperator;
break;
// $CASES-OMITTED$
default:
throw new MolgenisQueryException(
"Expected query occur operator instead of [" + occurOperator + "]");
}
}
QueryBuilder queryPartBuilder = createQueryClause(queryRule, entityMetaData);
if (queryPartBuilder == null) continue; // skip SHOULD and DIS_MAX query rules
// add query part to query
switch (occur)
{
case AND:
boolQuery.must(queryPartBuilder);
break;
case OR:
boolQuery.should(queryPartBuilder).minimumNumberShouldMatch(1);
break;
case NOT:
boolQuery.mustNot(queryPartBuilder);
break;
// $CASES-OMITTED$
default:
throw new MolgenisQueryException("Unknown occurence operator [" + occur + "]");
}
}
queryBuilder = boolQuery;
}
return queryBuilder;
}
/**
* Create query clause for query rule
*
* @param queryRule
* @param entityMetaData
* @return query class or null for SHOULD and DIS_MAX query rules
*/
@SuppressWarnings("unchecked")
private QueryBuilder createQueryClause(QueryRule queryRule, EntityMetaData entityMetaData)
{
// create query rule
String queryField = queryRule.getField();
Operator queryOperator = queryRule.getOperator();
Object queryValue = queryRule.getValue();
QueryBuilder queryBuilder;
switch (queryOperator)
{
case AND:
case OR:
case NOT:
throw new MolgenisQueryException("Unexpected query operator [" + queryOperator + ']');
case SHOULD:
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
for (QueryRule subQuery : queryRule.getNestedRules())
{
boolQueryBuilder.should(createQueryClause(subQuery, entityMetaData));
}
queryBuilder = boolQueryBuilder;
break;
case DIS_MAX:
DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
for (QueryRule subQuery : queryRule.getNestedRules())
{
disMaxQueryBuilder.add(createQueryClause(subQuery, entityMetaData));
}
disMaxQueryBuilder.tieBreaker((float) 0.0);
if (queryRule.getValue() != null)
{
disMaxQueryBuilder.boost(Float.parseFloat(queryRule.getValue().toString()));
}
queryBuilder = disMaxQueryBuilder;
break;
case EQUALS:
{
// As a general rule, filters should be used instead of queries:
// - for binary yes/no searches
// - for queries on exact values
// Workaround for Elasticsearch Date to String conversion issue
if (queryValue instanceof Date)
{
String[] attributePath = parseAttributePath(queryField);
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
queryValue = getESDateQueryValue((Date) queryValue, attr);
}
FilterBuilder filterBuilder;
if (queryField.equals(ElasticsearchService.CRUD_TYPE_FIELD_NAME))
{
filterBuilder = FilterBuilders.termFilter(queryField, queryValue);
}
else
{
String[] attributePath = parseAttributePath(queryField);
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
// construct query part
if (queryValue != null)
{
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case BOOL:
case DATE:
case DATE_TIME:
case DECIMAL:
case INT:
case LONG:
{
filterBuilder = FilterBuilders.termFilter(queryField, queryValue);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
break;
}
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case SCRIPT:
case STRING:
case TEXT:
{
filterBuilder = FilterBuilders
.termFilter(queryField + '.' + MappingsBuilder.FIELD_NOT_ANALYZED, queryValue);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
break;
}
case CATEGORICAL:
case CATEGORICAL_MREF:
case XREF:
case MREF:
case FILE:
{
if (attributePath.length > 1) throw new UnsupportedOperationException(
"Can not filter on references deeper than 1.");
// support both entity as entity id as value
Object queryIdValue = queryValue instanceof Entity ? ((Entity) queryValue).getIdValue()
: queryValue;
AttributeMetaData refIdAttr = attr.getRefEntity().getIdAttribute();
String indexFieldName = getXRefEqualsInSearchFieldName(refIdAttr, queryField);
filterBuilder = FilterBuilders.nestedFilter(queryField,
FilterBuilders.termFilter(indexFieldName, queryIdValue));
break;
}
case COMPOUND:
throw new MolgenisQueryException(
"Illegal data type [" + dataType + "] for operator [" + queryOperator + "]");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
else
{
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case BOOL:
case DATE:
case DATE_TIME:
case DECIMAL:
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case INT:
case LONG:
case SCRIPT:
case STRING:
case TEXT:
filterBuilder = FilterBuilders.missingFilter(queryField).existence(true)
.nullValue(true);
break;
case CATEGORICAL:
case CATEGORICAL_MREF:
case FILE:
case MREF:
case XREF:
AttributeMetaData refIdAttr = attr.getRefEntity().getIdAttribute();
String indexFieldName = getXRefEqualsInSearchFieldName(refIdAttr, queryField);
// see https://github.com/elastic/elasticsearch/issues/3495
filterBuilder = FilterBuilders.notFilter(FilterBuilders.nestedFilter(queryField,
FilterBuilders.existsFilter(indexFieldName)));
break;
case COMPOUND:
throw new MolgenisQueryException(
"Illegal data type [" + dataType + "] for operator [" + queryOperator + "]");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
}
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case GREATER:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
validateNumericalQueryField(queryField, entityMetaData);
String[] attributePath = parseAttributePath(queryField);
// Workaround for Elasticsearch Date to String conversion issue
if (queryValue instanceof Date)
{
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
queryValue = getESDateQueryValue((Date) queryValue, attr);
}
FilterBuilder filterBuilder = FilterBuilders.rangeFilter(queryField).gt(queryValue);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case GREATER_EQUAL:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
validateNumericalQueryField(queryField, entityMetaData);
String[] attributePath = parseAttributePath(queryField);
// Workaround for Elasticsearch Date to String conversion issue
if (queryValue instanceof Date)
{
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
queryValue = getESDateQueryValue((Date) queryValue, attr);
}
FilterBuilder filterBuilder = FilterBuilders.rangeFilter(queryField).gte(queryValue);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case IN:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
if (!(queryValue instanceof Iterable<?>))
{
throw new MolgenisQueryException("Query value must be a Iterable instead of ["
+ queryValue.getClass().getSimpleName() + "]");
}
Iterable<?> iterable = (Iterable<?>) queryValue;
String[] attributePath = parseAttributePath(queryField);
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
FieldTypeEnum dataType = attr.getDataType().getEnumType();
FilterBuilder filterBuilder;
switch (dataType)
{
case BOOL:
case DATE:
case DATE_TIME:
case DECIMAL:
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case INT:
case LONG:
case SCRIPT:
case STRING:
case TEXT:
// note: inFilter expects array, not iterable
filterBuilder = FilterBuilders.inFilter(getFieldName(attr, queryField),
Iterables.toArray(iterable, Object.class));
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
break;
case CATEGORICAL:
case CATEGORICAL_MREF:
case MREF:
case XREF:
case FILE:
if (attributePath.length > 1)
throw new UnsupportedOperationException("Can not filter on references deeper than 1.");
// support both entity iterable as entity id iterable as value
Iterable<Object> idValues;
if (isEntityIterable(iterable))
{
idValues = Iterables.transform((Iterable<Entity>) iterable, new Function<Entity, Object>()
{
@Override
public Object apply(Entity entity)
{
return entity.getIdValue();
}
});
}
else
{
idValues = (Iterable<Object>) iterable;
}
// note: inFilter expects array, not iterable
filterBuilder = FilterBuilders.nestedFilter(queryField, FilterBuilders.inFilter(
getXRefEqualsInSearchFieldName(attr.getRefEntity().getIdAttribute(), queryField),
Iterables.toArray(idValues, Object.class)));
break;
case COMPOUND:
throw new MolgenisQueryException(
"Illegal data type [" + dataType + "] for operator [" + queryOperator + "]");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case LESS:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
validateNumericalQueryField(queryField, entityMetaData);
String[] attributePath = parseAttributePath(queryField);
// Workaround for Elasticsearch Date to String conversion issue
if (queryValue instanceof Date)
{
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
queryValue = getESDateQueryValue((Date) queryValue, attr);
}
FilterBuilder filterBuilder = FilterBuilders.rangeFilter(queryField).lt(queryValue);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case LESS_EQUAL:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
validateNumericalQueryField(queryField, entityMetaData);
String[] attributePath = parseAttributePath(queryField);
// Workaround for Elasticsearch Date to String conversion issue
if (queryValue instanceof Date)
{
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
queryValue = getESDateQueryValue((Date) queryValue, attr);
}
FilterBuilder filterBuilder = FilterBuilders.rangeFilter(queryField).lte(queryValue);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case RANGE:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
if (!(queryValue instanceof Iterable<?>))
{
throw new MolgenisQueryException("Query value must be a Iterable instead of ["
+ queryValue.getClass().getSimpleName() + "]");
}
Iterable<?> iterable = (Iterable<?>) queryValue;
validateNumericalQueryField(queryField, entityMetaData);
Iterator<?> iterator = iterable.iterator();
String[] attributePath = parseAttributePath(queryField);
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
Object queryValueFrom = iterator.next();
// Workaround for Elasticsearch Date to String conversion issue
if (queryValueFrom instanceof Date)
{
queryValueFrom = getESDateQueryValue((Date) queryValueFrom, attr);
}
Object queryValueTo = iterator.next();
// Workaround for Elasticsearch Date to String conversion issue
if (queryValueTo instanceof Date)
{
queryValueTo = getESDateQueryValue((Date) queryValueTo, attr);
}
FilterBuilder filterBuilder = FilterBuilders.rangeFilter(queryField).gte(queryValueFrom)
.lte(queryValueTo);
filterBuilder = nestedFilterBuilder(attributePath, filterBuilder);
queryBuilder = QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(), filterBuilder);
break;
}
case NESTED:
List<QueryRule> nestedQueryRules = queryRule.getNestedRules();
if (nestedQueryRules == null || nestedQueryRules.isEmpty())
{
throw new MolgenisQueryException("Missing nested rules for nested query");
}
queryBuilder = createQueryBuilder(nestedQueryRules, entityMetaData);
break;
case LIKE:
{
String[] attributePath = parseAttributePath(queryField);
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
// construct query part
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case BOOL:
case DATE:
case DATE_TIME:
case DECIMAL:
case COMPOUND:
case INT:
case LONG:
throw new MolgenisQueryException(
"Illegal data type [" + dataType + "] for operator [" + queryOperator + "]");
case CATEGORICAL:
case CATEGORICAL_MREF:
case MREF:
case XREF:
case FILE:
case SCRIPT: // due to size would result in large amount of ngrams
case TEXT: // due to size would result in large amount of ngrams
case HTML: // due to size would result in large amount of ngrams
throw new UnsupportedOperationException("Query with operator [" + queryOperator
+ "] and data type [" + dataType + "] not supported");
case EMAIL:
case ENUM:
case HYPERLINK:
case STRING:
queryBuilder = QueryBuilders
.matchQuery(queryField + '.' + MappingsBuilder.FIELD_NGRAM_ANALYZED, queryValue)
.analyzer(DEFAULT_ANALYZER);
queryBuilder = nestedQueryBuilder(attributePath, queryBuilder);
break;
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
break;
}
case SEARCH:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
// 1. attribute: search in attribute
// 2. no attribute: search in all
if (queryField == null)
{
queryBuilder = QueryBuilders.matchPhraseQuery("_all", queryValue).slop(10);
}
else
{
String[] attributePath = parseAttributePath(queryField);
AttributeMetaData attr = getAttribute(entityMetaData, attributePath);
// construct query part
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case BOOL:
throw new MolgenisQueryException(
"Cannot execute search query on [" + dataType + "] attribute");
case DATE:
case DATE_TIME:
case DECIMAL:
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case INT:
case LONG:
case SCRIPT:
case STRING:
case TEXT:
queryBuilder = QueryBuilders.matchQuery(queryField, queryValue);
queryBuilder = nestedQueryBuilder(attributePath, queryBuilder);
break;
case CATEGORICAL:
case CATEGORICAL_MREF:
case MREF:
case XREF:
case FILE:
if (attributePath.length > 1)
throw new UnsupportedOperationException("Can not filter on references deeper than 1.");
queryBuilder = QueryBuilders.nestedQuery(queryField,
QueryBuilders.matchQuery(queryField + '.' + "_all", queryValue));
break;
case COMPOUND:
throw new MolgenisQueryException(
"Illegal data type [" + dataType + "] for operator [" + queryOperator + "]");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
break;
}
case FUZZY_MATCH:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
if (queryField == null)
{
queryBuilder = QueryBuilders.matchQuery("_all", queryValue);
}
else
{
AttributeMetaData attr = entityMetaData.getAttribute(queryField);
if (attr == null) throw new UnknownAttributeException(queryField);
// construct query part
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case DATE:
case DATE_TIME:
case DECIMAL:
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case INT:
case LONG:
case SCRIPT:
case STRING:
case TEXT:
queryBuilder = QueryBuilders.queryStringQuery(queryField + ":(" + queryValue + ")");
break;
case MREF:
case XREF:
case CATEGORICAL:
case CATEGORICAL_MREF:
case FILE:
queryField = attr.getName() + "." + attr.getRefEntity().getLabelAttribute().getName();
queryBuilder = QueryBuilders
.nestedQuery(attr.getName(),
QueryBuilders.queryStringQuery(queryField + ":(" + queryValue + ")"))
.scoreMode("max");
break;
case BOOL:
case COMPOUND:
throw new MolgenisQueryException(
"Illegal data type [" + dataType + "] for operator [" + queryOperator + "]");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
break;
}
case FUZZY_MATCH_NGRAM:
{
if (queryValue == null) throw new MolgenisQueryException("Query value cannot be null");
if (queryField == null)
{
queryBuilder = QueryBuilders.matchQuery("_all", queryValue);
}
else
{
AttributeMetaData attr = entityMetaData.getAttribute(queryField);
if (attr == null) throw new UnknownAttributeException(queryField);
// construct query part
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case DATE:
case DATE_TIME:
case DECIMAL:
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case INT:
case LONG:
case SCRIPT:
case STRING:
case TEXT:
queryField = queryField + ".ngram";
queryBuilder = QueryBuilders.queryStringQuery(queryField + ":(" + queryValue + ")");
break;
case MREF:
case XREF:
queryField = attr.getName() + "." + attr.getRefEntity().getLabelAttribute().getName()
+ ".ngram";
queryBuilder = QueryBuilders
.nestedQuery(attr.getName(),
QueryBuilders.queryStringQuery(queryField + ":(" + queryValue + ")"))
.scoreMode("max");
break;
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
break;
}
default:
throw new MolgenisQueryException("Unknown query operator [" + queryOperator + "]");
}
return queryBuilder;
}
private String getFieldName(AttributeMetaData attr, String queryField)
{
FieldTypeEnum dataType = attr.getDataType().getEnumType();
switch (dataType)
{
case XREF:
case CATEGORICAL:
case CATEGORICAL_MREF:
case MREF:
case FILE:
return queryField;
case BOOL:
case DATE:
case DATE_TIME:
case DECIMAL:
case INT:
case LONG:
return queryField;
case EMAIL:
case ENUM:
case HTML:
case HYPERLINK:
case SCRIPT:
case STRING:
case TEXT:
return new StringBuilder(queryField).append('.').append(MappingsBuilder.FIELD_NOT_ANALYZED).toString();
case COMPOUND:
throw new MolgenisQueryException("Illegal data type [" + dataType + "] not supported");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
private String getXRefEqualsInSearchFieldName(AttributeMetaData refIdAttr, String queryField)
{
String indexFieldName = queryField + '.' + refIdAttr.getName();
return getFieldName(refIdAttr, indexFieldName);
}
private void validateNumericalQueryField(String queryField, EntityMetaData entityMetaData)
{
String[] attributePath = parseAttributePath(queryField);
FieldTypeEnum dataType = getAttribute(entityMetaData, attributePath).getDataType().getEnumType();
switch (dataType)
{
case DATE:
case DATE_TIME:
case DECIMAL:
case INT:
case LONG:
break;
case BOOL:
case CATEGORICAL:
case CATEGORICAL_MREF:
case COMPOUND:
case EMAIL:
case ENUM:
case FILE:
case HTML:
case HYPERLINK:
case MREF:
case SCRIPT:
case STRING:
case TEXT:
case XREF:
throw new MolgenisQueryException("Range query not allowed for type [" + dataType + "]");
default:
throw new RuntimeException("Unknown data type [" + dataType + "]");
}
}
private boolean isEntityIterable(Iterable<?> iterable)
{
Iterator<?> it = iterable.iterator();
boolean isEntity = it.hasNext() && (it.next() instanceof Entity);
return isEntity;
}
private String[] parseAttributePath(String queryField)
{
return queryField.split("\\" + ATTRIBUTE_SEPARATOR);
}
/**
* Wraps the filter in a nested filter when a query is done on a reference entity. Returns the original filter when
* it is applied to the current entity.
*/
private FilterBuilder nestedFilterBuilder(String[] attributePath, FilterBuilder filterBuilder)
{
if (attributePath.length == 1)
{
return filterBuilder;
}
else if (attributePath.length == 2)
{
return FilterBuilders.nestedFilter(attributePath[0], filterBuilder);
}
else
{
throw new UnsupportedOperationException("Can not filter on references deeper than 1.");
}
}
/**
* Wraps the query in a nested query when a query is done on a reference entity. Returns the original query when it
* is applied to the current entity.
*/
private QueryBuilder nestedQueryBuilder(String[] attributePath, QueryBuilder queryBuilder)
{
if (attributePath.length == 1)
{
return queryBuilder;
}
else if (attributePath.length == 2)
{
return QueryBuilders.nestedQuery(attributePath[0], queryBuilder);
}
else
{
throw new UnsupportedOperationException("Can not filter on references deeper than 1.");
}
}
/** Returns the target attribute. Looks in the reference entity when it is a nested query. */
private AttributeMetaData getAttribute(EntityMetaData entityMetaData, String[] attributePath)
{
if (attributePath.length > 2)
throw new UnsupportedOperationException("Can not filter on references deeper than 1.");
if (attributePath.length == 0) throw new MolgenisQueryException("Attribute path length is 0!");
if (attributePath.length == 1)
{
AttributeMetaData attr = entityMetaData.getAttribute(attributePath[0]);
if (attr == null) throw new UnknownAttributeException(attributePath[0]);
return attr;
}
else
{
AttributeMetaData attr = entityMetaData.getAttribute(attributePath[0]);
if (attr == null) throw new UnknownAttributeException(attributePath[0]);
attr = attr.getRefEntity().getAttribute(attributePath[1]);
if (attr == null) throw new UnknownAttributeException(attributePath[0] + "." + attributePath[1]);
return attr;
}
}
private String getESDateQueryValue(Date queryValue, AttributeMetaData attr)
{
if (attr.getDataType().getEnumType() == FieldTypeEnum.DATE_TIME)
{
return MolgenisDateFormat.getDateTimeFormat().format(queryValue);
}
return MolgenisDateFormat.getDateFormat().format(queryValue);
}
}
| lgpl-3.0 |
MagiciansArtificeTeam/Magicians-Artifice | src/main/java/magiciansartifice/main/magic/rituals/RitualWaterCreation.java | 3614 | package magiciansartifice.main.magic.rituals;
import magiciansartifice.api.BasicRitual;
import magiciansartifice.main.core.utils.registries.BlockRegistry;
import magiciansartifice.main.fluids.LiquidRegistry;
import net.minecraft.entity.effect.EntityLightningBolt;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.world.World;
import java.util.Random;
@SuppressWarnings("unused")
public class RitualWaterCreation extends BasicRitual {
public static Random itemRand = new Random();
public void startRitual(int x, int y, int z, World world, EntityPlayer player) {
super.startRitual(x, y, z, world, player);
}
public boolean areAllBlocksCorrect(int x, int y, int z, World world, EntityPlayer player) {
int x1 = x;
int y1 = y;
int z1 = z;
z -= 2;
for (int i = 0; i < 5; i++) {
if (world.getBlock(x - 2, y, z + i) == BlockRegistry.storage) {
if (!(world.getBlockMetadata(x - 2, y, z + i) == 0)) {
return false;
}
}
}
for (int i = 0; i < 5; i++) {
if (world.getBlock(x - 2, y, z + i) == BlockRegistry.storage) {
if (!(world.getBlockMetadata(x + 2, y, z + i) == 0)) {
return false;
}
}
}
x -= 2;
for (int i = 0; i < 5; i++) {
if (world.getBlock(x + i, y, z) == BlockRegistry.storage) {
if (!(world.getBlockMetadata(x + i, y, z) == 0)) {
return false;
}
}
}
for (int i = 0; i < 5; i++) {
if (world.getBlock(x + i, y, z + 4) == BlockRegistry.storage) {
if (!(world.getBlockMetadata(x + i, y, z) == 0)) {
return false;
}
}
}
x += 1;
for (int i = 0; i < 3; i++) {
if (!(world.getBlock(x + i, y, z + 3) == Blocks.water)) {
return false;
}
}
for (int i = 0; i < 3; i++) {
if (!(world.getBlock(x + i, y, z + 2) == Blocks.water || world.getBlock(x + i, y, z + 2) == BlockRegistry.ritualCornerStone)) {
return false;
}
}
for (int i = 0; i < 3; i++) {
if (!(world.getBlock(x + i, y, z + 1) == Blocks.water)) {
return false;
}
}
return true;
}
public void initEffect(int x, int y, int z, World world, EntityPlayer player) {
x -= 1;
z -= 1;
for (int i = 0; i < 3; i++) {
world.setBlockToAir(x + i, y, z);
world.spawnEntityInWorld(new EntityLightningBolt(world, (double) x + i, (double) y + 1, (double) z));
world.setBlock(x + i, y, z, LiquidRegistry.magicWaterBlock);
}
z += 1;
for (int i = 0; i < 3; i++) {
world.setBlockToAir(x + i, y, z);
world.spawnEntityInWorld(new EntityLightningBolt(world, (double) x + i, (double) y + 1, (double) z));
world.setBlock(x + i, y, z, LiquidRegistry.magicWaterBlock);
}
z += 1;
for (int i = 0; i < 3; i++) {
world.setBlockToAir(x + i, y, z);
world.spawnEntityInWorld(new EntityLightningBolt(world, (double) x + i, (double) y + 1, (double) z));
world.setBlock(x + i, y, z, LiquidRegistry.magicWaterBlock);
}
x += 1;
z -= 1;
world.setBlock(x, y, z, BlockRegistry.ritualCornerStone);
}
}
| lgpl-3.0 |
AngryLawyer/rust-apl | src/eval/test_divide.rs | 4305 | use eval::eval;
use eval::test_eval::{test_eval, test_eval_fail};
use eval::eval::Printable;
#[test]
fn test_eval_basic_division() {
test_eval(~"4÷2", |result| {
match result {
~eval::AplInteger(x) => {
assert_eq!(x, 2);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"5÷2", |result| {
match result {
~eval::AplFloat(x) => {
assert_eq!(x, 2.5);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"-4÷20", |result| {
match result {
~eval::AplFloat(x) => {
assert_eq!(x, -0.2);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"4.0÷2", |result| {
match result {
~eval::AplFloat(x) => {
assert_eq!(x, 2.0);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"4÷2J2", |result| {
match result {
~eval::AplComplex(c) => {
assert_eq!(c.re, 1.0);
assert_eq!(c.im, -1.0);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"4J5÷3J2", |result| {
match result {
~eval::AplComplex(c) => {
assert_approx_eq!(c.re, 1.69230769);
assert_approx_eq!(c.im, 0.538462);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"5J.2÷3J.2", |result| {
match result {
~eval::AplComplex(c) => {
assert_approx_eq!(c.re, 1.663717);
assert_approx_eq!(c.im, -0.0442478);
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
}
#[test]
fn test_eval_array_division() {
test_eval(~"4÷2 2", |result| {
match result {
~eval::AplArray(ref _order, ref _dims, ref array) => {
match (&array[0], &array[1]) {
(&~eval::AplInteger(2), &~eval::AplInteger(2)) => {
//Fine
},
_ => {
fail!(format!("Bad array division: got {}", result.to_string()))
}
}
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"4 4 ÷ 2", |result| {
match result {
~eval::AplArray(ref _order, ref _dims, ref array) => {
match (&array[0], &array[1]) {
(&~eval::AplInteger(2), &~eval::AplInteger(2)) => {
//Fine
},
_ => {
fail!(format!("Bad array division: got {}", result.to_string()))
}
}
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
test_eval(~"3 3÷2 1", |result| {
match result {
~eval::AplArray(ref _order, ref _dims, ref array) => {
match (&array[0], &array[1]) {
(&~eval::AplFloat(1.5), &~eval::AplInteger(3)) => {
//Fine
},
_ => {
fail!(format!("Bad array division: got {}", result.to_string()))
}
}
},
_ => {
fail!(format!("Didn't find a number - {}", result.to_typed_string()));
}
}
});
//TO- test length, depth
test_eval_fail(~"1 1 1 ÷ 1 1", |_result| {
//Cool beanz
});
}
| lgpl-3.0 |
kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/objects/macro/Gene_xref_necessary_type.cpp | 1813 | /* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Author: .......
*
* File Description:
* .......
*
* Remark:
* This code was originally generated by application DATATOOL
* using the following specifications:
* 'macro.asn'.
*/
// standard includes
#include <ncbi_pch.hpp>
// generated includes
#include <objects/macro/Gene_xref_necessary_type.hpp>
// generated classes
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
/* Original file checksum: lines: 52, chars: 1691, CRC32: 5fb8e70d */
| lgpl-3.0 |
mapsforge/vtm | vtm-desktop/src/org/oscim/awt/AwtCanvas.java | 7647 | /*
* Copyright 2010, 2011, 2012, 2013 mapsforge.org
* Copyright 2013 Hannes Janetzek
* Copyright 2016-2021 devemux86
* Copyright 2017 nebular
* Copyright 2017 Longri
*
* This file is part of the OpenScienceMap project (http://www.opensciencemap.org).
*
* This program is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.oscim.awt;
import org.oscim.backend.canvas.Bitmap;
import org.oscim.backend.canvas.Canvas;
import org.oscim.backend.canvas.Color;
import org.oscim.backend.canvas.Paint;
import java.awt.*;
import java.awt.font.TextLayout;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.DataBufferInt;
public class AwtCanvas implements Canvas {
private static final java.awt.Color TRANSPARENT = new java.awt.Color(0, 0, 0, 0);
private BufferedImage bitmap;
public Graphics2D canvas;
public AwtCanvas() {
}
public AwtCanvas(BufferedImage bitmap) {
this.bitmap = bitmap;
}
@Override
public void setBitmap(Bitmap bitmap) {
if (canvas != null)
canvas.dispose();
AwtBitmap awtBitmap = (AwtBitmap) bitmap;
this.bitmap = awtBitmap.bitmap;
canvas = awtBitmap.bitmap.createGraphics();
canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.CLEAR, 0));
canvas.fillRect(0, 0, bitmap.getWidth(), bitmap.getHeight());
canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
canvas.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
canvas.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
canvas.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);
}
private final AffineTransform tx = new AffineTransform();
@Override
public void drawText(String text, float x, float y, Paint paint) {
AwtPaint awtPaint = (AwtPaint) paint;
if (awtPaint.stroke == null) {
canvas.setColor(awtPaint.color);
canvas.setFont(awtPaint.font);
canvas.drawString(text, x, y);
} else {
canvas.setColor(awtPaint.color);
canvas.setStroke(awtPaint.stroke);
TextLayout tl = new TextLayout(text, awtPaint.font,
canvas.getFontRenderContext());
tx.setToIdentity();
tx.translate(x, y);
Shape s = tl.getOutline(tx);
canvas.draw(s);
canvas.setColor(awtPaint.color);
canvas.fill(s);
}
}
@Override
public void drawText(String text, float x, float y, Paint fill, Paint stroke) {
AwtPaint fillPaint = (AwtPaint) fill;
if (stroke == null) {
canvas.setColor(fillPaint.color);
canvas.setFont(fillPaint.font);
canvas.drawString(text, x, y);
} else {
AwtPaint strokePaint = (AwtPaint) stroke;
canvas.setColor(strokePaint.color);
canvas.setStroke(strokePaint.stroke);
TextLayout tl = new TextLayout(text, fillPaint.font,
canvas.getFontRenderContext());
tx.setToIdentity();
tx.translate(x, y);
Shape s = tl.getOutline(tx);
canvas.draw(s);
canvas.setColor(fillPaint.color);
canvas.fill(s);
}
}
@Override
public void drawBitmap(Bitmap bitmap, float x, float y) {
BufferedImage src = ((AwtBitmap) bitmap).bitmap;
// TODO Need better check
if (src.isAlphaPremultiplied()) {
int intX = (int) x;
int intY = (int) y;
int[] srcbuf = ((DataBufferInt) src.getRaster().getDataBuffer()).getData();
int[] dstbuf = ((DataBufferInt) this.bitmap.getRaster().getDataBuffer()).getData();
int width = intX + src.getWidth() > this.bitmap.getWidth() ? this.getWidth() - intX : src.getWidth();
int height = intY + src.getHeight() > this.bitmap.getHeight() ? this.getHeight() - intY : src.getHeight();
int dstoffs = intX + intY * this.bitmap.getWidth();
int srcoffs = 0;
for (int i = 0; i < height; i++, dstoffs += this.bitmap.getWidth(), srcoffs += width)
System.arraycopy(srcbuf, srcoffs, dstbuf, dstoffs, width);
} else
this.canvas.drawImage(src, (int) x, (int) y, null);
}
@Override
public void drawBitmapScaled(Bitmap bitmap) {
Image scaledImage = ((AwtBitmap) bitmap).bitmap.getScaledInstance(this.bitmap.getWidth(), this.bitmap.getHeight(), Image.SCALE_DEFAULT);
this.canvas.drawImage(scaledImage, 0, 0, this.bitmap.getWidth(), this.bitmap.getHeight(), null);
}
@Override
public void drawCircle(float x, float y, float radius, Paint paint) {
AwtPaint awtPaint = (AwtPaint) paint;
this.canvas.setColor(awtPaint.color);
if (awtPaint.stroke != null)
this.canvas.setStroke(awtPaint.stroke);
float doubleRadius = radius * 2;
Paint.Style style = paint.getStyle();
switch (style) {
case FILL:
this.canvas.fillOval((int) (x - radius), (int) (y - radius), (int) doubleRadius, (int) doubleRadius);
break;
case STROKE:
this.canvas.drawOval((int) (x - radius), (int) (y - radius), (int) doubleRadius, (int) doubleRadius);
break;
}
}
@Override
public void drawLine(float x1, float y1, float x2, float y2, Paint paint) {
AwtPaint awtPaint = (AwtPaint) paint;
this.canvas.setColor(awtPaint.color);
if (awtPaint.stroke != null)
this.canvas.setStroke(awtPaint.stroke);
this.canvas.drawLine((int) x1, (int) y1, (int) x2, (int) y2);
}
@Override
public void fillColor(int color) {
fillRectangle(0, 0, getWidth(), getHeight(), color);
}
@Override
public void fillRectangle(float x, float y, float width, float height, int color) {
java.awt.Color awtColor = color == Color.TRANSPARENT ? TRANSPARENT : new java.awt.Color(color, true);
Composite originalComposite = this.canvas.getComposite();
this.canvas.setComposite(AlphaComposite.getInstance(color == Color.TRANSPARENT ? AlphaComposite.CLEAR : AlphaComposite.SRC_OVER));
this.canvas.setColor(awtColor);
this.canvas.fillRect((int) x, (int) y, (int) width, (int) height);
this.canvas.setComposite(originalComposite);
}
@Override
public int getHeight() {
return this.bitmap != null ? this.bitmap.getHeight() : 0;
}
@Override
public int getWidth() {
return this.bitmap != null ? this.bitmap.getWidth() : 0;
}
}
| lgpl-3.0 |
it-guru/Sming | samples/TcpClient_NarodMon/app/application.cpp | 4306 | /* Пример отправки данных на narodmon.ru с помощью TCP-клиента.
* By JustACat http://esp8266.ru/forum/members/120/
* 23.04.2015
*/
#include <user_config.h>
#include <SmingCore/SmingCore.h>
// If you want, you can define WiFi settings globally in Eclipse Environment Variables
#ifndef WIFI_SSID
#define WIFI_SSID "PleaseEnterSSID" // Put you SSID and Password here
#define WIFI_PWD "PleaseEnterPass"
#endif
#define NARODM_HOST "narodmon.ru"
#define NARODM_PORT 8283
Timer procTimer; // Таймер для периодического вызова отправки данных
String mac; // Переменная для хранения mac-адреса
float t1 = -2.5; // Переменная, в которой у нас хранится температура с датчика
void nmOnCompleted(TcpClient& client, bool successful)
{
// debug msg
debugf("nmOnCompleted");
debugf("successful: %d", successful);
}
void nmOnReadyToSend(TcpClient& client, TcpConnectionEvent sourceEvent)
{
// debug msg
debugf("nmOnReadyToSend");
debugf("sourceEvent: %d", sourceEvent);
// в момент соединения осуществляем отправку
if(sourceEvent == eTCE_Connected) {
/* отправляем данные по датчикам (3 штуки)
* T1 = t1 (температура)
* H1 = 8 (влажность)
* P1 = 712.15 (давление)
*
* после отправки сразу закроем соединение: последний параметр = true
*/
client.sendString("#" + mac + "\n#T1#" + t1 + "\n#H1#8\n#P1#712.15\n##", true);
}
}
bool nmOnReceive(TcpClient& client, char* buf, int size)
{
// debug msg
debugf("nmOnReceive");
debugf("%s", buf);
return true;
}
// Создаем объект narodMon класса TcpClient
TcpClient narodMon(nmOnCompleted, nmOnReadyToSend, nmOnReceive);
// эта функция будет вызываться по таймеру
void sendData()
{
// считываем показания датчиков
// ...
// для отладки просто увеличиваем каждый раз значение переменной t1 на 1.39 градуса
t1 += 1.39;
// подключаемся к серверу narodmon
narodMon.connect(NARODM_HOST, NARODM_PORT);
}
// Когда удачно подключились к роутеру
void connectOk(String ssid, uint8_t ssid_len, uint8_t bssid[6], uint8_t channel)
{
// debug msg
debugf("I'm CONNECTED to WiFi");
// получаем MAC-адрес нашей ESP и помещаем в переменную mac
mac = WifiStation.getMAC();
// в верхний регистр
mac.toUpperCase();
// преобразуем из XXXXXXXXXXXX в XX-XX-XX-XX-XX-XX
for(int i = 2; i < mac.length(); i += 2)
mac = mac.substring(0, i) + "-" + mac.substring(i++);
debugf("mac: %s", mac.c_str());
}
void connectFail(String ssid, uint8_t ssid_len, uint8_t bssid[6], uint8_t reason)
{
// Если подключение к роутеру не удалось, выводим сообщение
debugf("I'm NOT CONNECTED!");
}
void gotIP(IPAddress ip, IPAddress netmask, IPAddress gateway)
{
// вызываем по таймеру функцию sendData
procTimer.initializeMs(6 * 60 * 1000, sendData).start(); // каждые 6 минут
// ну и заодно сразу после запуска вызываем, чтобы не ждать 6 минут первый раз
sendData();
}
void init()
{
// Настраиваем и включаем вывод в UART для дебага
Serial.begin(115200);
Serial.systemDebugOutput(true);
Serial.println("Hello friendly world! :)");
// Отключаем AP
WifiAccessPoint.enable(false);
// Настраиваем и включаем Station
WifiStation.config(WIFI_SSID, WIFI_PWD);
WifiStation.enable(true);
/* connectOk будет вызвана, когда (если) подключимся к роутеру
* connectFail будет вызвана, если подключиться не получится
* 30 - таймаут подключения (сек)
*/
WifiEvents.onStationConnect(connectOk);
WifiEvents.onStationDisconnect(connectFail);
WifiEvents.onStationGotIP(gotIP);
}
| lgpl-3.0 |
Invenietis/ck-certified | Plugins/Accessibility/Keyboard/ZoneCollection.cs | 9474 | #region LGPL License
/*----------------------------------------------------------------------------
* This file (Plugins\Accessibility\Keyboard\ZoneCollection.cs) is part of CiviKey.
*
* CiviKey is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* CiviKey is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License
* along with CiviKey. If not, see <http://www.gnu.org/licenses/>.
*
* Copyright © 2007-2012,
* Invenietis <http://www.invenietis.com>,
* In’Tech INFO <http://www.intechinfo.fr>,
* All rights reserved.
*-----------------------------------------------------------------------------*/
#endregion
using System;
using System.Collections;
using System.Diagnostics;
using System.Xml;
using System.Collections.Generic;
using CK.Core;
using CK.Keyboard.Model;
using CK.Storage;
using System.Linq;
namespace CK.Keyboard
{
class ZoneCollection : IZoneCollection, IEnumerable<Zone>, IStructuredSerializable
{
Keyboard _kb;
//Dictionary<string, Zone> _zones;
IList<Zone> _zonesl;
Zone _defaultZone;
public event EventHandler<ZoneEventArgs> ZoneCreated;
public event EventHandler<ZoneEventArgs> ZoneDestroyed;
public event EventHandler<ZoneEventArgs> ZoneRenamed;
public event EventHandler<ZoneEventArgs> ZoneMoved;
internal ZoneCollection( Keyboard kb )
{
_kb = kb;
_defaultZone = new Zone( this, String.Empty, 0 );
//_zones = new Dictionary<string, Zone>();
_zonesl = new List<Zone>();
//_zones.Add( _defaultZone.Name, _defaultZone );
_zonesl.Add( _defaultZone );
}
IKeyboardContext IZoneCollection.Context
{
get { return _kb.Context; }
}
internal KeyboardContext Context
{
get { return _kb.Context; }
}
IKeyboard IZoneCollection.Keyboard
{
get { return _kb; }
}
internal Keyboard Keyboard
{
get { return _kb; }
}
public bool Contains( object item )
{
IZone z = item as IZone;
return z != null && z.Keyboard == Keyboard;
}
public int Count
{
get { return _zonesl == null ? 1 : _zonesl.Count; }
}
IEnumerator<IZone> IEnumerable<IZone>.GetEnumerator()
{
Converter<Zone, IZone> conv = delegate( Zone l ) { return (IZone)l; };
//return Wrapper<IZone>.CreateEnumerator( _zones.Values, conv );
return Wrapper<IZone>.CreateEnumerator( _zonesl, conv );
}
IEnumerator IEnumerable.GetEnumerator()
{
return _zonesl.GetEnumerator();
//return _zones.Values.GetEnumerator();
}
public IEnumerator<Zone> GetEnumerator()
{
return _zonesl.GetEnumerator();
//return _zones.Values.GetEnumerator();
}
IZone IZoneCollection.this[string name]
{
get { return _zonesl.Where( z => z.Name == name ).FirstOrDefault(); }
//get { return this[name]; }
}
internal Zone this[string name]
{
get
{
return _zonesl.Where( z => z.Name == name ).FirstOrDefault();
//Zone l;
//_zones.TryGetValue( name, out l );
//return l;
}
}
IZone IZoneCollection.this[int index]
{
get { return _zonesl[index]; }
//get { return _zones.Values.ToReadOnlyList<IZone>()[index]; }
}
internal Zone this[int index]
{
get { return _zonesl[index]; }
//get { return _zones.Values.ToReadOnlyList<Zone>()[index]; }
}
IZone IZoneCollection.Default
{
get { return _defaultZone; }
}
internal Zone Default
{
get { return _defaultZone; }
}
IZone IZoneCollection.Create( string name )
{
return Create( name, -1 );
}
IZone IZoneCollection.Create( string name, int index )
{
return Create( name, index );
}
internal Zone Create( string name, int index )
{
name = name.Trim();
//If the zone's index has not been specified, it is added with the last index
//if( index == -1 ) index = _zones.Count;
if( index == -1 ) index = _zonesl.Count;
//Zone zone = new Zone( this, KeyboardContext.EnsureUnique( name, null, _zones.ContainsKey ), index );
Predicate<string> exists = new Predicate<string>( ( s ) => _zonesl.Any<Zone>( z => z.Name == s ) );
Zone zone = new Zone( this, KeyboardContext.EnsureUnique( name, null, exists ), index );
//_zones.Add( zone.Name, zone );
_zonesl.Add( zone );
if( ZoneCreated != null ) ZoneCreated( this, new ZoneEventArgs( zone ) );
Context.SetKeyboardContextDirty();
return zone;
}
internal void OnDestroy( Zone z )
{
Debug.Assert( z.Keyboard == Keyboard && z != Default, "It is not the default." );
//_zones.Remove( z.Name );
_zonesl.Remove( z );
foreach( Layout l in _kb.Layouts ) l.DestroyConfig( z, true );
if( ZoneDestroyed != null ) ZoneDestroyed( this, new ZoneEventArgs( z ) );
Context.SetKeyboardContextDirty();
}
internal void RenameZone( Zone z, ref string zoneName, string newName )
{
Debug.Assert( z.Keyboard == Keyboard && z.Name != newName, "It is not the default" );
string previous = zoneName;
Predicate<string> exists = new Predicate<string>( ( s ) => _zonesl.Any<Zone>( zone => zone.Name == s ) );
newName = KeyboardContext.EnsureUnique( newName, previous, exists ); // _zones.ContainsKey
if( newName != previous )
{
//_zones.Remove( z.Name );
_zonesl.Remove( z );
//_zones.Add( newName, z );
_zonesl.Add( z );
zoneName = newName;
if( ZoneRenamed != null ) ZoneRenamed( this, new ZoneRenamedEventArgs( z, previous ) );
Context.SetKeyboardContextDirty();
}
}
internal void OnMove( Zone zone, int i )
{
Debug.Assert( zone != null && zone.Keyboard == Keyboard, "This is one of our zones." );
if( i < 0 ) i = 0;
else if( i > _zonesl.Count ) i = _zonesl.Count;
int prevIndex = zone.Index;
if( i == prevIndex ) return;
Debug.Assert( _zonesl[prevIndex] == zone, "Indices are always synchronized." );
_zonesl.Insert( i, zone );
int min, max;
if( i > prevIndex )
{
min = prevIndex;
max = i;
Debug.Assert( _zonesl[prevIndex] == zone, "Remove the key" );
_zonesl.RemoveAt( prevIndex );
}
else
{
min = i;
max = prevIndex + 1;
Debug.Assert( _zonesl[max] == zone, "Remove the key" );
_zonesl.RemoveAt( max );
}
for( int iNew = min; iNew < max; ++iNew )
{
_zonesl[iNew].SetIndex( iNew );
}
ZoneEventArgs e = new ZoneEventArgs( zone );
if( ZoneMoved != null ) ZoneMoved( this, e );
Context.SetKeyboardContextDirty();
}
void IStructuredSerializable.ReadContent( IStructuredReader sr )
{
XmlReader r = sr.Xml;
// We are on the <Zones> tag, we move on to the content
r.Read();
int idx = 1; //index 0 is the default zone's index
while( r.IsStartElement( "Zone" ) )
{
// Gets normalized zone name.
string n = r.GetAttribute( "Name" );
if( n == null ) n = String.Empty;
else n = n.Trim();
Zone z;
// If empty name, it is the default zone.
if( n.Length == 0 ) z = _defaultZone;
else z = Create( n, idx++ );
sr.ReadInlineObjectStructured( z );
}
}
void IStructuredSerializable.WriteContent( IStructuredWriter sw )
{
XmlWriter w = sw.Xml;
foreach( Zone z in _zonesl )
{
sw.WriteInlineObjectStructuredElement( "Zone", z );
}
}
}
} | lgpl-3.0 |
kyungtaekLIM/PSI-BLASTexB | src/ncbi-blast-2.5.0+/c++/src/objects/remap/remap_client_.cpp | 4680 | /* $Id$
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* File Description:
* This code was generated by application DATATOOL
* using the following specifications:
* 'remap.asn'.
*
* ATTENTION:
* Don't edit or commit this file into CVS as this file will
* be overridden (by DATATOOL) without warning!
* ===========================================================================
*/
// standard includes
#include <ncbi_pch.hpp>
#include <serial/serialimpl.hpp>
// generated includes
#include <objects/remap/remap_client.hpp>
#include <objects/remap/Remap_result.hpp>
BEGIN_NCBI_SCOPE
BEGIN_objects_SCOPE // namespace ncbi::objects::
// generated classes
void CRemapClient_Base::Ask(const CRemapClient_Base::TRequestChoice& req, CRemapClient_Base::TReply& reply)
{
TRequest request;
request.Assign(*m_DefaultRequest);
request.SetRequest().Assign(req);
Ask(request, reply);
}
void CRemapClient_Base::Ask(const CRemapClient_Base::TRequestChoice& req, CRemapClient_Base::TReply& reply, CRemapClient_Base::TReplyChoice::E_Choice wanted)
{
TRequest request;
request.Assign(*m_DefaultRequest);
request.SetRequest().Assign(req);
Ask(request, reply, wanted);
}
void CRemapClient_Base::Ask(const CRemapClient_Base::TRequest& request, CRemapClient_Base::TReply& reply, CRemapClient_Base::TReplyChoice::E_Choice wanted)
{
Ask(request, reply);
TReplyChoice& rc = x_Choice(reply);
if (rc.Which() == wanted) {
return; // ok
} else if (rc.IsError()) {
CNcbiOstrstream oss;
oss << "CRemapClient: server error: " << rc.GetError();
NCBI_THROW(CException, eUnknown, CNcbiOstrstreamToString(oss));
} else {
rc.ThrowInvalidSelection(wanted);
}
}
CRef<CRemap_result> CRemapClient_Base::AskRemap(const CRemap_query& req, CRemapClient_Base::TReply* reply)
{
TRequestChoice request;
TReply reply0;
request.SetRemap(const_cast<CRemap_query&>(req));
if ( !reply ) {
reply = &reply0;
}
Ask(request, *reply, TReplyChoice::e_Remap);
return CRef<CRemap_result>(&x_Choice(*reply).SetRemap());
}
list< string > CRemapClient_Base::AskMaps_to_builds(const string& req, CRemapClient_Base::TReply* reply)
{
TRequestChoice request;
TReply reply0;
request.SetMaps_to_builds(const_cast<string&>(req));
if ( !reply ) {
reply = &reply0;
}
Ask(request, *reply, TReplyChoice::e_Maps_to_builds);
return x_Choice(*reply).GetMaps_to_builds();
}
list< string > CRemapClient_Base::AskMaps_from_builds(const string& req, CRemapClient_Base::TReply* reply)
{
TRequestChoice request;
TReply reply0;
request.SetMaps_from_builds(const_cast<string&>(req));
if ( !reply ) {
reply = &reply0;
}
Ask(request, *reply, TReplyChoice::e_Maps_from_builds);
return x_Choice(*reply).GetMaps_from_builds();
}
list< string > CRemapClient_Base::AskAll_builds(CRemapClient_Base::TReply* reply)
{
TRequestChoice request;
TReply reply0;
request.SetAll_builds();
if ( !reply ) {
reply = &reply0;
}
Ask(request, *reply, TReplyChoice::e_All_builds);
return x_Choice(*reply).GetAll_builds();
}
// constructor
CRemapClient_Base::CRemapClient_Base(void)
: Tparent("REMAP"), m_DefaultRequest(new TRequest)
{
}
// destructor
CRemapClient_Base::~CRemapClient_Base(void)
{
}
END_objects_SCOPE // namespace ncbi::objects::
END_NCBI_SCOPE
| lgpl-3.0 |
isartcanyameres/mqnaas | examples/api.router/src/main/java/org/mqnaas/examples/api/router/IInterface.java | 151 | package org.mqnaas.examples.api.router;
import org.mqnaas.core.api.IResource;
public interface IInterface extends IResource {
String getName();
}
| lgpl-3.0 |
steveevers/DataStructures | Graphs/IGraph.cs | 923 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SE.Graphs
{
public interface IGraph<T>
{
IList<T> Nodes { get; }
bool IsDirected { get; }
bool IsWeighted { get; }
bool IsConnected { get; }
bool IsComplete { get; }
bool IsAcyclic { get; }
bool EdgeExists(int from, int to);
bool EdgeExists(T from, T to);
float EdgeWeight(int from, int to);
float EdgeWeight(T from, T to);
void AddEdge(int from, int to, float weight = -1);
void AddEdge(T from, T to, float weight = -1);
void RemoveEdge(int from, int to);
void RemoveEdge(T from, T to);
void AddNode(T n);
void RemoveNode(int n);
void RemoveNode(T n);
IEnumerable<int> Neighbors(int n);
IEnumerable<int> Neighbors(T n);
}
}
| lgpl-3.0 |
leodmurillo/sonar | sonar-plugin-api/src/test/java/org/sonar/api/test/SimpleProjectFileSystem.java | 3603 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2011 SonarSource
* mailto:contact AT sonarsource DOT com
*
* Sonar is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* Sonar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with Sonar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02
*/
package org.sonar.api.test;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.CharEncoding;
import org.apache.commons.lang.NotImplementedException;
import org.sonar.api.resources.InputFile;
import org.sonar.api.resources.Language;
import org.sonar.api.resources.ProjectFileSystem;
import org.sonar.api.resources.Resource;
import org.sonar.api.utils.SonarException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.List;
public class SimpleProjectFileSystem implements ProjectFileSystem {
private File basedir;
public SimpleProjectFileSystem(File basedir) {
this.basedir = basedir;
}
public Charset getSourceCharset() {
return Charset.defaultCharset();
}
private File createDir(String path) {
try {
File dir = new File(basedir, path);
FileUtils.forceMkdir(dir);
return dir;
} catch (IOException e) {
throw new SonarException(e);
}
}
public File getBasedir() {
return basedir;
}
public File getBuildDir() {
return createDir("target");
}
public File getBuildOutputDir() {
return createDir("target/classes");
}
public List<File> getSourceDirs() {
return Arrays.asList(createDir("src/main"));
}
public ProjectFileSystem addSourceDir(File dir) {
throw new NotImplementedException();
}
public List<File> getTestDirs() {
return Arrays.asList(createDir("src/test"));
}
public ProjectFileSystem addTestDir(File dir) {
throw new NotImplementedException();
}
public File getReportOutputDir() {
return createDir("target/site");
}
public File getSonarWorkingDirectory() {
return createDir("target/sonar");
}
public File resolvePath(String path) {
return null;
}
public List<File> getSourceFiles(Language... langs) {
return null;
}
public List<File> getJavaSourceFiles() {
return null;
}
public boolean hasJavaSourceFiles() {
return false;
}
public List<File> getTestFiles(Language... langs) {
return null;
}
public boolean hasTestFiles(Language lang) {
return false;
}
public File writeToWorkingDirectory(String content, String filename) throws IOException {
File file = new File(getSonarWorkingDirectory(), filename);
FileUtils.writeStringToFile(file, content, CharEncoding.UTF_8);
return file;
}
public File getFileFromBuildDirectory(String filename) {
return null;
}
public Resource toResource(File file) {
return null;
}
/**
* @since 2.6
*/
public List<InputFile> mainFiles(String... lang) {
return null;
}
/**
* @since 2.6
*/
public List<InputFile> testFiles(String... lang) {
return null;
}
}
| lgpl-3.0 |
hcasse/elfy | src/elf/ui/CheckBox.java | 856 | /*
* ElfCore library
* Copyright (c) 2014 - Hugues Cassé <hugues.casse@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package elf.ui;
/**
* A simple check box.
* @author casse
*
*/
public interface CheckBox extends Field {
}
| lgpl-3.0 |
openstreetview/android | eventbus/src/main/java/org/greenrobot/eventbus/util/ErrorDialogManager.java | 11156 | /*
* Copyright (C) 2012-2016 Markus Junginger, greenrobot (http://greenrobot.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.greenrobot.eventbus.util;
import org.greenrobot.eventbus.EventBus;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
/**
* Central class for app that want to use event based error dialogs.<br/>
* <br/>
* How to use:
* <ol>
* <li>Set the {@link #factory} to configure dialogs for your app, typically in {@link Application#onCreate()}</li>
* <li>Use one of {@link #attachTo(Activity)}, {@link #attachTo(Activity, boolean)} or
* {@link #attachTo(Activity, boolean, Bundle)} in your Activity, typically in onCreate.</li>
* </ol>
* <p>
* For more complex mappings, you can supply your own {@link ErrorDialogFragmentFactory}.
* @author Markus
*/
public class ErrorDialogManager {
public static final String KEY_TITLE = "de.greenrobot.eventbus.errordialog.title";
public static final String KEY_MESSAGE = "de.greenrobot.eventbus.errordialog.message";
public static final String KEY_FINISH_AFTER_DIALOG = "de.greenrobot.eventbus.errordialog.finish_after_dialog";
public static final String KEY_ICON_ID = "de.greenrobot.eventbus.errordialog.icon_id";
public static final String KEY_EVENT_TYPE_ON_CLOSE = "de.greenrobot.eventbus.errordialog.event_type_on_close";
protected static final String TAG_ERROR_DIALOG = "de.greenrobot.eventbus.error_dialog";
protected static final String TAG_ERROR_DIALOG_MANAGER = "de.greenrobot.eventbus.error_dialog_manager";
/**
* Must be set by the application.
*/
public static ErrorDialogFragmentFactory<?> factory;
/**
* Scope is limited to the activity's class.
*/
public static void attachTo(Activity activity) {
attachTo(activity, false, null);
}
/**
* Scope is limited to the activity's class.
*/
public static void attachTo(Activity activity, boolean finishAfterDialog) {
attachTo(activity, finishAfterDialog, null);
}
/**
* Scope is limited to the activity's class.
*/
public static void attachTo(Activity activity, boolean finishAfterDialog, Bundle argumentsForErrorDialog) {
Object executionScope = activity.getClass();
attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog);
}
public static void attachTo(Activity activity, Object executionScope, boolean finishAfterDialog, Bundle argumentsForErrorDialog) {
if (factory == null) {
throw new RuntimeException("You must set the static factory field to configure error dialogs for your app.");
}
if (isSupportActivity(activity)) {
SupportManagerFragment.attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog);
} else {
HoneycombManagerFragment.attachTo(activity, executionScope, finishAfterDialog, argumentsForErrorDialog);
}
}
private static boolean isSupportActivity(Activity activity) {
boolean isSupport = false;
for (Class<?> c = activity.getClass().getSuperclass(); ; c = c.getSuperclass()) {
if (c == null) {
throw new RuntimeException("Illegal activity type: " + activity.getClass());
}
String name = c.getName();
if (name.equals("android.support.v4.app.FragmentActivity")) {
isSupport = true;
break;
} else if (name.startsWith("com.actionbarsherlock.app") &&
(name.endsWith(".SherlockActivity") || name.endsWith(".SherlockListActivity") || name.endsWith(".SherlockPreferenceActivity"))) {
throw new RuntimeException("Please use SherlockFragmentActivity. Illegal activity: " + name);
} else if (name.equals("android.app.Activity")) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
throw new RuntimeException(
"Illegal activity without fragment support. Either use Android 3.0+ or android.support.v4.app.FragmentActivity.");
}
break;
}
}
return isSupport;
}
protected static void checkLogException(ThrowableFailureEvent event) {
if (factory.config.logExceptions) {
String tag = factory.config.tagForLoggingExceptions;
if (tag == null) {
tag = EventBus.TAG;
}
Log.i(tag, "Error dialog manager received exception", event.throwable);
}
}
private static boolean isInExecutionScope(Object executionScope, ThrowableFailureEvent event) {
if (event != null) {
Object eventExecutionScope = event.getExecutionScope();
if (eventExecutionScope != null && !eventExecutionScope.equals(executionScope)) {
// Event not in our scope, do nothing
return false;
}
}
return true;
}
public static class SupportManagerFragment extends Fragment {
protected boolean finishAfterDialog;
protected Bundle argumentsForErrorDialog;
private EventBus eventBus;
private boolean skipRegisterOnNextResume;
private Object executionScope;
public static void attachTo(Activity activity, Object executionScope, boolean finishAfterDialog, Bundle argumentsForErrorDialog) {
FragmentManager fm = ((FragmentActivity) activity).getSupportFragmentManager();
SupportManagerFragment fragment = (SupportManagerFragment) fm.findFragmentByTag(TAG_ERROR_DIALOG_MANAGER);
if (fragment == null) {
fragment = new SupportManagerFragment();
fm.beginTransaction().add(fragment, TAG_ERROR_DIALOG_MANAGER).commit();
fm.executePendingTransactions();
}
fragment.finishAfterDialog = finishAfterDialog;
fragment.argumentsForErrorDialog = argumentsForErrorDialog;
fragment.executionScope = executionScope;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
eventBus = ErrorDialogManager.factory.config.getEventBus();
eventBus.register(this);
skipRegisterOnNextResume = true;
}
@Override
public void onResume() {
super.onResume();
if (skipRegisterOnNextResume) {
// registered in onCreate, skip registration in this run
skipRegisterOnNextResume = false;
} else {
eventBus = ErrorDialogManager.factory.config.getEventBus();
eventBus.register(this);
}
}
@Override
public void onPause() {
eventBus.unregister(this);
super.onPause();
}
public void onEventMainThread(ThrowableFailureEvent event) {
if (!isInExecutionScope(executionScope, event)) {
return;
}
checkLogException(event);
// Execute pending commits before finding to avoid multiple error fragments being shown
FragmentManager fm = getFragmentManager();
fm.executePendingTransactions();
DialogFragment existingFragment = (DialogFragment) fm.findFragmentByTag(TAG_ERROR_DIALOG);
if (existingFragment != null) {
// Just show the latest error
existingFragment.dismiss();
}
android.support.v4.app.DialogFragment errorFragment =
(android.support.v4.app.DialogFragment) factory.prepareErrorFragment(event, finishAfterDialog, argumentsForErrorDialog);
if (errorFragment != null) {
errorFragment.show(fm, TAG_ERROR_DIALOG);
}
}
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static class HoneycombManagerFragment extends android.app.Fragment {
protected boolean finishAfterDialog;
protected Bundle argumentsForErrorDialog;
private EventBus eventBus;
private Object executionScope;
public static void attachTo(Activity activity, Object executionScope, boolean finishAfterDialog, Bundle argumentsForErrorDialog) {
android.app.FragmentManager fm = activity.getFragmentManager();
HoneycombManagerFragment fragment = (HoneycombManagerFragment) fm.findFragmentByTag(TAG_ERROR_DIALOG_MANAGER);
if (fragment == null) {
fragment = new HoneycombManagerFragment();
fm.beginTransaction().add(fragment, TAG_ERROR_DIALOG_MANAGER).commit();
fm.executePendingTransactions();
}
fragment.finishAfterDialog = finishAfterDialog;
fragment.argumentsForErrorDialog = argumentsForErrorDialog;
fragment.executionScope = executionScope;
}
@Override
public void onResume() {
super.onResume();
eventBus = ErrorDialogManager.factory.config.getEventBus();
eventBus.register(this);
}
@Override
public void onPause() {
eventBus.unregister(this);
super.onPause();
}
public void onEventMainThread(ThrowableFailureEvent event) {
if (!isInExecutionScope(executionScope, event)) {
return;
}
checkLogException(event);
// Execute pending commits before finding to avoid multiple error fragments being shown
android.app.FragmentManager fm = getFragmentManager();
fm.executePendingTransactions();
android.app.DialogFragment existingFragment = (android.app.DialogFragment) fm.findFragmentByTag(TAG_ERROR_DIALOG);
if (existingFragment != null) {
// Just show the latest error
existingFragment.dismiss();
}
android.app.DialogFragment errorFragment =
(android.app.DialogFragment) factory.prepareErrorFragment(event, finishAfterDialog, argumentsForErrorDialog);
if (errorFragment != null) {
errorFragment.show(fm, TAG_ERROR_DIALOG);
}
}
}
}
| lgpl-3.0 |
AriseID/ariseid-core | les/randselect.go | 5371 | // Copyright 2017 Ethereum, AriseID Authors
// This file is part of the AriseID library.
//
// The AriseID library is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// The AriseID library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with the AriseID library. If not, see <http://www.gnu.org/licenses/>.
// Package les implements the Light AriseID Subprotocol.
package les
import (
"math/rand"
)
// wrsItem interface should be implemented by any entries that are to be selected from
// a weightedRandomSelect set. Note that recalculating monotonously decreasing item
// weights on-demand (without constantly calling update) is allowed
type wrsItem interface {
Weight() int64
}
// weightedRandomSelect is capable of weighted random selection from a set of items
type weightedRandomSelect struct {
root *wrsNode
idx map[wrsItem]int
}
// newWeightedRandomSelect returns a new weightedRandomSelect structure
func newWeightedRandomSelect() *weightedRandomSelect {
return &weightedRandomSelect{root: &wrsNode{maxItems: wrsBranches}, idx: make(map[wrsItem]int)}
}
// update updates an item's weight, adds it if it was non-existent or removes it if
// the new weight is zero. Note that explicitly updating decreasing weights is not necessary.
func (w *weightedRandomSelect) update(item wrsItem) {
w.setWeight(item, item.Weight())
}
// remove removes an item from the set
func (w *weightedRandomSelect) remove(item wrsItem) {
w.setWeight(item, 0)
}
// setWeight sets an item's weight to a specific value (removes it if zero)
func (w *weightedRandomSelect) setWeight(item wrsItem, weight int64) {
idx, ok := w.idx[item]
if ok {
w.root.setWeight(idx, weight)
if weight == 0 {
delete(w.idx, item)
}
} else {
if weight != 0 {
if w.root.itemCnt == w.root.maxItems {
// add a new level
newRoot := &wrsNode{sumWeight: w.root.sumWeight, itemCnt: w.root.itemCnt, level: w.root.level + 1, maxItems: w.root.maxItems * wrsBranches}
newRoot.items[0] = w.root
newRoot.weights[0] = w.root.sumWeight
w.root = newRoot
}
w.idx[item] = w.root.insert(item, weight)
}
}
}
// choose randomly selects an item from the set, with a chance proportional to its
// current weight. If the weight of the chosen element has been decreased since the
// last stored value, returns it with a newWeight/oldWeight chance, otherwise just
// updates its weight and selects another one
func (w *weightedRandomSelect) choose() wrsItem {
for {
if w.root.sumWeight == 0 {
return nil
}
val := rand.Int63n(w.root.sumWeight)
choice, lastWeight := w.root.choose(val)
weight := choice.Weight()
if weight != lastWeight {
w.setWeight(choice, weight)
}
if weight >= lastWeight || rand.Int63n(lastWeight) < weight {
return choice
}
}
}
const wrsBranches = 8 // max number of branches in the wrsNode tree
// wrsNode is a node of a tree structure that can store wrsItems or further wrsNodes.
type wrsNode struct {
items [wrsBranches]interface{}
weights [wrsBranches]int64
sumWeight int64
level, itemCnt, maxItems int
}
// insert recursively inserts a new item to the tree and returns the item index
func (n *wrsNode) insert(item wrsItem, weight int64) int {
branch := 0
for n.items[branch] != nil && (n.level == 0 || n.items[branch].(*wrsNode).itemCnt == n.items[branch].(*wrsNode).maxItems) {
branch++
if branch == wrsBranches {
panic(nil)
}
}
n.itemCnt++
n.sumWeight += weight
n.weights[branch] += weight
if n.level == 0 {
n.items[branch] = item
return branch
} else {
var subNode *wrsNode
if n.items[branch] == nil {
subNode = &wrsNode{maxItems: n.maxItems / wrsBranches, level: n.level - 1}
n.items[branch] = subNode
} else {
subNode = n.items[branch].(*wrsNode)
}
subIdx := subNode.insert(item, weight)
return subNode.maxItems*branch + subIdx
}
}
// setWeight updates the weight of a certain item (which should exist) and returns
// the change of the last weight value stored in the tree
func (n *wrsNode) setWeight(idx int, weight int64) int64 {
if n.level == 0 {
oldWeight := n.weights[idx]
n.weights[idx] = weight
diff := weight - oldWeight
n.sumWeight += diff
if weight == 0 {
n.items[idx] = nil
n.itemCnt--
}
return diff
}
branchItems := n.maxItems / wrsBranches
branch := idx / branchItems
diff := n.items[branch].(*wrsNode).setWeight(idx-branch*branchItems, weight)
n.weights[branch] += diff
n.sumWeight += diff
if weight == 0 {
n.itemCnt--
}
return diff
}
// choose recursively selects an item from the tree and returns it along with its weight
func (n *wrsNode) choose(val int64) (wrsItem, int64) {
for i, w := range n.weights {
if val < w {
if n.level == 0 {
return n.items[i].(wrsItem), n.weights[i]
} else {
return n.items[i].(*wrsNode).choose(val)
}
} else {
val -= w
}
}
panic(nil)
}
| lgpl-3.0 |
Rugiewit/ducky | Assets/Guilherme/Scripts/AttackRequest.cs | 482 | using UnityEngine;
public delegate void AttackDelegate(GameObject player);
public class AttackRequest
{
private AttackDelegate attackDelegate;
private int attackPower;
public AttackRequest (AttackDelegate attackDelegate, int attackPower)
{
this.attackDelegate = attackDelegate;
this.attackPower = attackPower;
}
public int getAttackPower()
{
return attackPower;
}
public void executeDelegate(GameObject playerObject)
{
attackDelegate(playerObject);
}
}
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-server/src/test/java/org/sonar/server/component/index/ComponentIndexLoginTest.java | 2408 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.component.index;
import org.junit.Test;
import org.sonar.db.component.ComponentDto;
import org.sonar.db.user.GroupDto;
import org.sonar.db.user.UserDto;
import static org.sonar.db.user.GroupTesting.newGroupDto;
import static org.sonar.db.user.UserTesting.newUserDto;
public class ComponentIndexLoginTest extends ComponentIndexTest {
@Test
public void should_filter_unauthorized_results() {
indexer.index(newProject("sonarqube", "Quality Product"));
// do not give any permissions to that project
assertNoSearchResults("sonarqube");
assertNoSearchResults("Quality Product");
}
@Test
public void should_find_project_for_which_the_user_has_direct_permission() {
UserDto user = newUserDto();
userSession.logIn(user);
ComponentDto project = newProject("sonarqube", "Quality Product");
indexer.index(project);
assertNoSearchResults("sonarqube");
// give the user explicit access
authorizationIndexerTester.allowOnlyUser(project, user);
assertSearchResults("sonarqube", project);
}
@Test
public void should_find_project_for_which_the_user_has_indirect_permission_through_group() {
GroupDto group = newGroupDto();
userSession.logIn().setGroups(group);
ComponentDto project = newProject("sonarqube", "Quality Product");
indexer.index(project);
assertNoSearchResults("sonarqube");
// give the user implicit access (though group)
authorizationIndexerTester.allowOnlyGroup(project, group);
assertSearchResults("sonarqube", project);
}
}
| lgpl-3.0 |
scodynelson/JCL | jcl-core/src/main/java/jcl/lang/ReadtableStruct.java | 6788 | package jcl.lang;
import jcl.lang.internal.readtable.ReadtableStructImpl;
import jcl.lang.statics.CommonLispSymbols;
/**
* The {@link ReadtableStruct} is the object representation of a Lisp 'readtable' type.
*/
public interface ReadtableStruct extends LispStruct {
/**
* Creates a new dispatching table for the provided {@code codePoint}, designating the {@link SyntaxType} as
* terminating if the provided {@code nonTerminatingP} is false.
*
* @param dispatchTable
* the dispatching table {@link FunctionStruct} to use
* @param codePoint
* the key for the new dispatching table
* @param nonTerminatingP
* true if the character should be non-terminating; false otherwise
*
* @return the value of {@code nonTerminatingP}
*/
boolean makeDispatchMacroCharacter(final FunctionStruct dispatchTable, final int codePoint, final boolean nonTerminatingP);
default BooleanStruct makeDispatchMacroCharacter(final FunctionStruct dispatchTable,
final CharacterStruct character,
final BooleanStruct nonTerminatingP) {
makeDispatchMacroCharacter(dispatchTable, character.toUnicodeCodePoint(), nonTerminatingP.toJavaPBoolean());
return TStruct.INSTANCE;
}
/**
* Sets the {@link FunctionStruct} for the provided {@code codePoint} to the provided {@code
* readerMacroFunction}, designating the {@link SyntaxType} as terminating if the provided {@code nonTerminatingP}
* is false.
*
* @param codePoint
* the key for the {@link FunctionStruct} to set
* @param readerMacroFunction
* the new {@link FunctionStruct}
* @param nonTerminatingP
* true if the character should be non-terminating; false otherwise
*/
void setMacroCharacter(final int codePoint, final FunctionStruct readerMacroFunction, final boolean nonTerminatingP);
default LispStruct setMacroCharacter(final CharacterStruct character, final FunctionStruct newFunction,
final BooleanStruct nonTerminatingP) {
setMacroCharacter(character.toUnicodeCodePoint(), newFunction, nonTerminatingP.toJavaPBoolean());
return TStruct.INSTANCE;
}
/**
* Getter for readtable {@link ReadtableCase} property.
*
* @return readtable {@link ReadtableCase} property
*/
ReadtableCase getReadtableCase();
default SymbolStruct readtableCase() {
final ReadtableCase readtableCase = getReadtableCase();
switch (readtableCase) {
case UPCASE:
return CommonLispSymbols.UPCASE_KEYWORD;
case DOWNCASE:
return CommonLispSymbols.DOWNCASE_KEYWORD;
case PRESERVE:
return CommonLispSymbols.PRESERVE_KEYWORD;
case INVERT:
return CommonLispSymbols.INVERT_KEYWORD;
}
return NILStruct.INSTANCE;
}
/**
* Setter for readtable {@link ReadtableCase} property.
*
* @param readtableCase
* new readtable {@link ReadtableCase} property value
*/
void setReadtableCase(final ReadtableCase readtableCase);
default SymbolStruct setReadtableCase(final SymbolStruct mode) {
if (CommonLispSymbols.UPCASE_KEYWORD.eq(mode)) {
setReadtableCase(ReadtableCase.UPCASE);
} else if (CommonLispSymbols.DOWNCASE_KEYWORD.eq(mode)) {
setReadtableCase(ReadtableCase.DOWNCASE);
} else if (CommonLispSymbols.PRESERVE_KEYWORD.eq(mode)) {
setReadtableCase(ReadtableCase.PRESERVE);
} else if (CommonLispSymbols.INVERT_KEYWORD.eq(mode)) {
setReadtableCase(ReadtableCase.INVERT);
}
return mode;
}
/**
* Retrieves the {@link FunctionStruct} for the provided {@code codePoint}.
*
* @param codePoint
* the key for the {@link FunctionStruct}
*
* @return the {@link FunctionStruct} for the provided {@code codePoint}
*/
FunctionStruct getMacroCharacter(final int codePoint);
default FunctionStruct getMacroCharacter(final CharacterStruct character) {
return getMacroCharacter(character.toUnicodeCodePoint());
}
/**
* Gets the {@link FunctionStruct} for the provided {@code subCodePoint} within the provided {@code
* dispatchCodePoint}'s dispatching table.
*
* @param dispatchCodePoint
* the key for the dispatching table to search for the {@link FunctionStruct}
* @param subCodePoint
* the key for the {@link FunctionStruct}
*
* @return the {@link FunctionStruct} for the provided {@code subCodePoint}
*/
FunctionStruct getDispatchMacroCharacter(final int dispatchCodePoint, final int subCodePoint);
default FunctionStruct getDispatchMacroCharacter(final CharacterStruct dispatchChar, final CharacterStruct subChar) {
return getDispatchMacroCharacter(dispatchChar.toUnicodeCodePoint(), subChar.toUnicodeCodePoint());
}
/**
* Sets the {@link FunctionStruct} for the provided {@code subCodePoint} to the provided {@code
* readerMacroFunction} within the provided {@code dispatchCodePoint}'s dispatching table.
*
* @param dispatchCodePoint
* the key for the dispatching table to set the {@link FunctionStruct}
* @param subCodePoint
* the key for the {@link FunctionStruct} to set
* @param readerMacroFunction
* the new {@link FunctionStruct}
*/
void setDispatchMacroCharacter(final int dispatchCodePoint, final int subCodePoint, final FunctionStruct readerMacroFunction);
default LispStruct setDispatchMacroCharacter(final CharacterStruct dispatchChar, final CharacterStruct subChar,
final FunctionStruct newFunction) {
setDispatchMacroCharacter(dispatchChar.toUnicodeCodePoint(), subChar.toUnicodeCodePoint(), newFunction);
return TStruct.INSTANCE;
}
/**
* Gets the {@link AttributeType} for the provided {@code codePoint} value.
*
* @param codePoint
* the codePoint for the {@link AttributeType} to retrieve
* @param readBase
* the read-base valued used to retrieve the appropriate {@link AttributeType}
*
* @return the {@link AttributeType} for the provided {@code codePoint} value
*/
AttributeType getAttributeType(final int codePoint, final IntegerStruct readBase);
/**
* Gets the {@link SyntaxType} for the provided {@code codePoint} value.
*
* @param codePoint
* the codePoint for the {@link SyntaxType} to retrieve
*
* @return the {@link SyntaxType} for the provided {@code codePoint} value
*/
SyntaxType getSyntaxType(final int codePoint);
default ReadtableStruct copyReadtable(final LispStruct toReadtable) {
if (toReadtable instanceof ReadtableStruct) {
// TODO: This isn't correct. We can't fully copy the Readtable objects right now.
final ReadtableStruct toReadtableCast = (ReadtableStruct) toReadtable;
return new ReadtableStructImpl(toReadtableCast.getReadtableCase());
} else {
return new ReadtableStructImpl();
}
}
static ReadtableStruct toReadtable() {
return new ReadtableStructImpl();
}
}
| lgpl-3.0 |
ari-zah/gaiasandbox | core/src/gaiasky/scenegraph/component/OrbitComponent.java | 3888 | /*
* This file is part of Gaia Sky, which is released under the Mozilla Public License 2.0.
* See the file LICENSE.md in the project root for full license details.
*/
package gaiasky.scenegraph.component;
import gaiasky.util.Constants;
import gaiasky.util.Nature;
import gaiasky.util.coord.AstroUtils;
import gaiasky.util.math.MathUtilsd;
import gaiasky.util.math.Vector3d;
import java.time.Instant;
public class OrbitComponent {
/** Source file **/
public String source;
/** Orbital period in days **/
public double period;
/** Base epoch **/
public double epoch;
/** Semi major axis of the ellipse, a in Km.**/
public double semimajoraxis;
/** Eccentricity of the ellipse. **/
public double e;
/** Inclination, angle between the reference plane (ecliptic) and the orbital plane. **/
public double i;
/** Longitude of the ascending node in degrees. **/
public double ascendingnode;
/** Argument of perihelion in degrees. **/
public double argofpericenter;
/** Mean anomaly at epoch, in degrees. **/
public double meananomaly;
/** G*M of central body (gravitational constant). Defaults to the Sun's **/
public double mu = 1.32712440041e20;
public OrbitComponent() {
}
public void setSource(String source) {
this.source = source;
}
public void setPeriod(Double period) {
this.period = period;
}
public void setEpoch(Double epoch) {
this.epoch = epoch;
}
public void setSemimajoraxis(Double semimajoraxis) {
this.semimajoraxis = semimajoraxis;
}
public void setEccentricity(Double e) {
this.e = e;
}
public void setInclination(Double i) {
this.i = i;
}
public void setAscendingnode(Double ascendingnode) {
this.ascendingnode = ascendingnode;
}
public void setArgofpericenter(Double argofpericenter) {
this.argofpericenter = argofpericenter;
}
public void setMeananomaly(Double meanAnomaly) {
this.meananomaly = meanAnomaly;
}
public void setMu(Double mu) {
this.mu = mu;
}
public void loadDataPoint(Vector3d out, Instant t){
double a = semimajoraxis * 1000d; // km to m
double M0 = meananomaly * MathUtilsd.degRad;
double omega_lan = ascendingnode * MathUtilsd.degRad;
double omega_ap = argofpericenter * MathUtilsd.degRad;
double ic = i * MathUtilsd.degRad;
double tjd = AstroUtils.getJulianDate(t);
// 1
double deltat = (tjd - epoch) * Nature.D_TO_S;
double M = M0 + deltat * Math.sqrt(mu / Math.pow(a, 3d));
// 2
double E = M;
for (int j = 0; j < 2; j++) {
E = E - ((E - e * Math.sin(E) - M) / (1 - e * Math.cos(E)));
}
double E_t = E;
// 3
double nu_t = 2d * Math.atan2(Math.sqrt(1d + e) * Math.sin(E_t / 2d), Math.sqrt(1d - e) * Math.cos(E_t / 2d));
// 4
double rc_t = a * (1d - e * Math.cos(E_t));
// 5
double ox = rc_t * Math.cos(nu_t);
double oy = rc_t * Math.sin(nu_t);
// 6
double sinomega = Math.sin(omega_ap);
double cosomega = Math.cos(omega_ap);
double sinOMEGA = Math.sin(omega_lan);
double cosOMEGA = Math.cos(omega_lan);
double cosi = Math.cos(ic);
double sini = Math.sin(ic);
double x = ox * (cosomega * cosOMEGA - sinomega * cosi * sinOMEGA) - oy * (sinomega * cosOMEGA + cosomega * cosi * sinOMEGA);
double y = ox * (cosomega * sinOMEGA + sinomega * cosi * cosOMEGA) + oy * (cosomega * cosi * cosOMEGA - sinomega * sinOMEGA);
double z = ox * (sinomega * sini) + oy * (cosomega * sini);
// 7
x *= Constants.M_TO_U;
y *= Constants.M_TO_U;
z *= Constants.M_TO_U;
out.set(y, z, x);
}
}
| lgpl-3.0 |
pauloremoli/terrama2 | webapp/public/javascripts/angular/schema-form-plugin/mask-warn/directives/terrama2-mask-field.js | 2437 | define([], function(){
/**
* It defines TerraMA2 mask field of schema form addon
*
* @example
* <terrama2-mask-field class="MyClass"></terrama2-analysis-helpers>
*
* @returns {angular.IDirective}
*/
function terrama2MaskField(i18n) {
return {
restrict: 'E',
require: 'ngModel',
scope: false,
template:
'<input ng-if="!form.fieldAddonLeft && !form.fieldAddonRight" ng-show="form.key" type="{{form.type}}" step="any" sf-changed="form" placeholder="{{form.placeholder}}" class="form-control {{form.fieldHtmlClass}}" id="{{form.key.slice(-1)[0]}}" ng-model-options="form.ngModelOptions" ng-model="modelValue" ng-disabled="form.readonly" schema-validate="form" name="{{form.key.slice(-1)[0]}}" aria-describedby="{{form.key.slice(-1)[0] + \'Status\'}}" ng-blur="updateModel(modelValue)">' +
'<span style="top: 25px; margin-right: 20px !important" ng-if="form.feedback !== false" class="form-control-feedback" ng-class="evalInScope(form.feedback) || {\'glyphicon\': true, \'glyphicon-ok\': hasSuccess(), \'glyphicon-remove\': hasError() }" aria-hidden="true"></span>'+
'<span ng-if="hasError() || hasSuccess()" id="{{form.key.slice(-1)[0] + \'Status\'}}" class="sr-only">{{ hasSuccess() ? \'(success)\' : \'(error)\' }}</span>'+
'<span class="warn-message" ng-if="showWarnMessage" ng-bind="i18n.__(\'Files can be overwritten\')"></span>'
,
link: function (scope, element, attrs, ngModel) {
scope.i18n = i18n;
scope.modelValue = ngModel.$viewValue;
scope.showWarnMessage = false;
scope.updateModel = function (modelValue) {
ngModel.$setViewValue(modelValue);
if (!modelValue) {
scope.showWarnMessage = false;
return;
}
scope.showWarnMessage = true;
// checking if value has some pattern characters
if (scope.form.maskPattern){
scope.form.maskPattern.forEach(function(mPattern){
if (modelValue.indexOf(mPattern) != -1){
scope.showWarnMessage = false;
return;
}
});
}
// if value is valid and have to show warn message, show message
scope.showWarnMessage = scope.showWarnMessage && ngModel.$valid;
};
},
};
}
terrama2MaskField.$inject = ['i18n'];
return terrama2MaskField;
});
| lgpl-3.0 |
Victorious3/NovaCore | minecraft/1.8/src/main/java/nova/core/wrapper/mc18/wrapper/block/forward/BlockPosition.java | 953 | package nova.core.wrapper.mc18.wrapper.block.forward;
import net.minecraft.world.World;
/**
* @author Stan Hebben
*/
public final class BlockPosition {
private final World world;
private final int x;
private final int y;
private final int z;
public BlockPosition(World world, int x, int y, int z) {
this.world = world;
this.x = x;
this.y = y;
this.z = z;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BlockPosition that = (BlockPosition) o;
if (x != that.x) {
return false;
}
if (y != that.y) {
return false;
}
if (z != that.z) {
return false;
}
if (!world.equals(that.world)) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = world.hashCode();
result = 31 * result + x;
result = 31 * result + y;
result = 31 * result + z;
return result;
}
}
| lgpl-3.0 |
Godin/sonar | server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/view/TriggerViewRefreshDelegate.java | 1291 | /*
* SonarQube
* Copyright (C) 2009-2019 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.ce.task.projectanalysis.view;
import java.util.OptionalInt;
import org.sonar.server.project.Project;
public interface TriggerViewRefreshDelegate {
/**
* Triggers the refresh of portfolios and applications
* associated to the project.
*
* @return the number of portfolios and applications being refreshed,
* or {@link OptionalInt#empty()} if not applicable.
*/
OptionalInt triggerFrom(Project project);
}
| lgpl-3.0 |
SINGROUP/pycp2k | pycp2k/classes/_each314.py | 1114 | from pycp2k.inputsection import InputSection
class _each314(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Metadynamics = None
self.Geo_opt = None
self.Rot_opt = None
self.Cell_opt = None
self.Band = None
self.Ep_lin_solver = None
self.Spline_find_coeffs = None
self.Replica_eval = None
self.Bsse = None
self.Shell_opt = None
self.Tddft_scf = None
self._name = "EACH"
self._keywords = {'Bsse': 'BSSE', 'Cell_opt': 'CELL_OPT', 'Just_energy': 'JUST_ENERGY', 'Band': 'BAND', 'Xas_scf': 'XAS_SCF', 'Rot_opt': 'ROT_OPT', 'Replica_eval': 'REPLICA_EVAL', 'Tddft_scf': 'TDDFT_SCF', 'Shell_opt': 'SHELL_OPT', 'Md': 'MD', 'Pint': 'PINT', 'Metadynamics': 'METADYNAMICS', 'Geo_opt': 'GEO_OPT', 'Spline_find_coeffs': 'SPLINE_FIND_COEFFS', 'Powell_opt': 'POWELL_OPT', 'Qs_scf': 'QS_SCF', 'Ep_lin_solver': 'EP_LIN_SOLVER'}
| lgpl-3.0 |
DavidS/MailSystem.NET | Class Library/ActiveUp.Net.Groupware/vCard.LabelCollection.cs | 1421 | // Copyright 2001-2010 - Active Up SPRLU (http://www.agilecomponents.com)
//
// This file is part of MailSystem.NET.
// MailSystem.NET is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// MailSystem.NET is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License
// along with SharpMap; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
namespace ActiveUp.Net.Groupware.vCard
{
/// <summary>
/// Contains one or more Label object(s).
/// </summary>
#if !PocketPC
[System.Serializable]
#endif
public class LabelCollection : System.Collections.CollectionBase
{
public LabelCollection()
{
}
public void Add(ActiveUp.Net.Groupware.vCard.Label number)
{
this.List.Add(number);
}
public ActiveUp.Net.Groupware.vCard.Label this[int index]
{
get
{
return (ActiveUp.Net.Groupware.vCard.Label)this.List[index];
}
}
}
}
| lgpl-3.0 |
SINGROUP/pycp2k | pycp2k/classes/_program_run_info9.py | 679 | from pycp2k.inputsection import InputSection
from ._each44 import _each44
class _program_run_info9(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Section_parameters = None
self.Add_last = None
self.Common_iteration_levels = None
self.Filename = None
self.Log_print_key = None
self.EACH = _each44()
self._name = "PROGRAM_RUN_INFO"
self._keywords = {'Log_print_key': 'LOG_PRINT_KEY', 'Filename': 'FILENAME', 'Add_last': 'ADD_LAST', 'Common_iteration_levels': 'COMMON_ITERATION_LEVELS'}
self._subsections = {'EACH': 'EACH'}
self._attributes = ['Section_parameters']
| lgpl-3.0 |
cryptobuks/forknote | src/transfers/SynchronizationState.cpp | 3586 | // Copyright (c) 2012-2015, The CryptoNote developers, The Bytecoin developers
//
// This file is part of Bytecoin.
//
// Bytecoin is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Bytecoin is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with Bytecoin. If not, see <http://www.gnu.org/licenses/>.
#include "SynchronizationState.h"
#include "serialization/BinaryInputStreamSerializer.h"
#include "serialization/BinaryOutputStreamSerializer.h"
#include "cryptonote_core/cryptonote_serialization.h"
namespace CryptoNote {
SynchronizationState::ShortHistory SynchronizationState::getShortHistory(size_t localHeight) const {
ShortHistory history;
size_t i = 0;
size_t current_multiplier = 1;
size_t sz = std::min(m_blockchain.size(), localHeight + 1);
if (!sz)
return history;
size_t current_back_offset = 1;
bool genesis_included = false;
while (current_back_offset < sz) {
history.push_back(m_blockchain[sz - current_back_offset]);
if (sz - current_back_offset == 0)
genesis_included = true;
if (i < 10) {
++current_back_offset;
} else {
current_back_offset += current_multiplier *= 2;
}
++i;
}
if (!genesis_included)
history.push_back(m_blockchain[0]);
return history;
}
SynchronizationState::CheckResult SynchronizationState::checkInterval(const BlockchainInterval& interval) const {
assert(interval.startHeight <= m_blockchain.size());
CheckResult result = { false, 0, false, 0 };
size_t intervalEnd = interval.startHeight + interval.blocks.size();
size_t iterationEnd = std::min(m_blockchain.size(), intervalEnd);
if (iterationEnd == 1)
iterationEnd = 0;
for (size_t i = interval.startHeight; i < iterationEnd; ++i) {
if (m_blockchain[i] != interval.blocks[i - interval.startHeight]) {
result.detachRequired = true;
result.detachHeight = i;
break;
}
}
if (result.detachRequired) {
result.hasNewBlocks = true;
result.newBlockHeight = result.detachHeight;
return result;
}
if (intervalEnd > m_blockchain.size()) {
result.hasNewBlocks = true;
result.newBlockHeight = m_blockchain.size();
}
return result;
}
void SynchronizationState::detach(uint64_t height) {
assert(height < m_blockchain.size());
m_blockchain.resize(height);
}
void SynchronizationState::addBlocks(const crypto::hash* blockHashes, uint64_t height, size_t count) {
assert(blockHashes);
auto size = m_blockchain.size();
assert( size == height);
m_blockchain.insert(m_blockchain.end(), blockHashes, blockHashes + count);
}
uint64_t SynchronizationState::getHeight() const {
return m_blockchain.size();
}
void SynchronizationState::save(std::ostream& os) {
CryptoNote::BinaryOutputStreamSerializer s(os);
serialize(s, "state");
}
void SynchronizationState::load(std::istream& in) {
CryptoNote::BinaryInputStreamSerializer s(in);
serialize(s, "state");
}
CryptoNote::ISerializer& SynchronizationState::serialize(CryptoNote::ISerializer& s, const std::string& name) {
s.beginObject(name);
s(m_blockchain, "blockchain");
s.endObject();
return s;
}
}
| lgpl-3.0 |
46bit/jeepers | src/gp/tree/mod.rs | 6285 | mod gen;
pub use self::gen::*;
use rand::Rng;
use std::fmt::{self, Debug};
use std::ops::{Deref, DerefMut};
use std::collections::VecDeque;
/// Trait to be implemented by Genetic Programs trees.
pub trait Tree
where Self: Sized + Debug + Clone
{
/// Type of input when evaluating the tree.
type Environment;
/// The type the tree will evaluate to.
type Action;
/// Generate a new tree within the bounds specified by TreeGen.
fn tree<R: Rng>(tg: &mut TreeGen<R>) -> BoxTree<Self> {
Self::child(tg, 0)
}
/// Generate a random new node to go into a tree.
fn child<R: Rng>(tg: &mut TreeGen<R>, current_depth: usize) -> BoxTree<Self> {
if tg.have_reached_a_leaf(current_depth) {
Self::leaf(tg, current_depth)
} else {
Self::branch(tg, current_depth)
}
}
/// Generate a branch node (a node with at least one Tree child).
fn branch<R: Rng>(tg: &mut TreeGen<R>, current_depth: usize) -> BoxTree<Self>;
/// Generate a leaf node (a node without any Tree children).
fn leaf<R: Rng>(tg: &mut TreeGen<R>, current_depth: usize) -> BoxTree<Self>;
/// Count `Self` children of this node.
fn count_children(&mut self) -> usize;
/// Get children of this node.
fn children(&self) -> Vec<&BoxTree<Self>>;
/// Get mutable children of this node.
fn children_mut(&mut self) -> Vec<&mut BoxTree<Self>>;
/// Get indexed child of this node. Number children from 0; suggested to go left-to-right.
//fn get_mut_child(&mut self, index: usize) -> Option<&mut BoxTree<Self>>;
/// Used to evaluate the root node of a tree.
fn evaluate(&self, env: &Self::Environment) -> Self::Action;
}
/// `Box` Wrapper for implementations of Tree.
#[derive(Clone, PartialEq, Eq)]
pub struct BoxTree<T>(Box<T>) where T: Tree;
impl<T> BoxTree<T>
where T: Tree
{
/// Extract the internal `Tree`.
pub fn inner(self) -> T {
*self.0
}
/// Count the number of nodes below this node in the tree.
pub fn count_nodes(&mut self) -> usize {
self.fold(0, |count, _, _, _| count + 1)
}
/// Get a clone of a particular value.
pub fn get(&mut self, target_index: usize) -> Option<T> {
let mut node = None;
self.map_while(|current, index, _| if index == target_index {
node = Some(current.clone());
false
} else {
true
});
node
}
/// Traverse the tree with the ability to mutate nodes in-place.
///
/// The callback receives a mutable pointer to the current node, the 0-based current iteration
/// count, and the 0-based current depth in the tree.
pub fn map<F>(&mut self, mut f: F)
where F: FnMut(&mut T, usize, usize)
{
// @TOOD: Benchmark if this optimises out.
self.map_while(|p, i, d| {
f(p, i, d);
true
})
}
/// Traverse the tree until the function returns `false`.
///
/// The callback receives a mutable pointer to the current node, the 0-based current iteration
/// count, and the 0-based current depth in the tree.
///
/// The callback returns a `bool`. If `false` the loop terminates.
pub fn map_while<F>(&mut self, mut f: F)
where F: FnMut(&mut T, usize, usize) -> bool
{
let mut stack: VecDeque<(&mut Self, usize)> = VecDeque::new();
stack.push_back((self, 0));
let mut i = 0;
while let Some((node, depth)) = stack.pop_back() {
if !f(node, i, depth) {
break;
}
let mut children = node.children_mut();
children.reverse();
for child in children {
stack.push_back((child, depth + 1));
}
i += 1;
}
}
/// Traverse the tree building up a return value, with the ability to mutate nodes in-place.
///
/// The callback receives the value being built up, a mutable pointer to the current node, the
/// 0-based current iteration count, and the 0-based current depth in the tree.
pub fn fold<F, V>(&mut self, value: V, mut f: F) -> V
where F: FnMut(V, &mut T, usize, usize) -> V
{
// @TOOD: Benchmark if this optimises out.
self.fold_while(value, |v, p, i, d| (true, f(v, p, i, d)))
}
/// Traverse the tree building up a return value, with the ability to mutate nodes in-place.
///
/// The callback receives the value being built up, a mutable pointer to the current node, the
/// 0-based current iteration count, and the 0-based current depth in the tree.
///
/// The callback returns a pair of `(bool, fold_value)`. If `false` the loop terminates.
pub fn fold_while<F, V>(&mut self, mut value: V, mut f: F) -> V
where F: FnMut(V, &mut T, usize, usize) -> (bool, V)
{
let mut stack: VecDeque<(&mut Self, usize)> = VecDeque::new();
stack.push_back((self, 0));
let mut i = 0;
while let Some((node, depth)) = stack.pop_back() {
value = match f(value, node, i, depth) {
(true, value) => value,
(false, value) => return value,
};
let mut children = node.children_mut();
children.reverse();
for child in children {
stack.push_back((child, depth + 1));
}
i += 1;
}
value
}
}
/// Make `BoxTree` invisible in `Debug` output. At the cost of a little invisibility this
/// makes `Tree`s far more readable.
impl<T> Debug for BoxTree<T>
where T: Tree
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}
impl<T> fmt::Display for BoxTree<T>
where T: Tree + fmt::Display
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl<T> Deref for BoxTree<T>
where T: Tree
{
type Target = T;
fn deref(&self) -> &T {
&self.0
}
}
impl<T> DerefMut for BoxTree<T>
where T: Tree
{
fn deref_mut(&mut self) -> &mut T {
&mut self.0
}
}
impl<T> From<T> for BoxTree<T>
where T: Tree
{
fn from(tree: T) -> BoxTree<T> {
BoxTree(Box::new(tree))
}
}
| lgpl-3.0 |
wfxiang08/zeromq4-x | src/atomic_counter.hpp | 6362 | /*
Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file
This file is part of 0MQ.
0MQ is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
0MQ is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef __ZMQ_ATOMIC_COUNTER_HPP_INCLUDED__
#define __ZMQ_ATOMIC_COUNTER_HPP_INCLUDED__
#include "stdint.hpp"
#include "platform.hpp"
#if defined ZMQ_FORCE_MUTEXES
#define ZMQ_ATOMIC_COUNTER_MUTEX
#elif (defined __i386__ || defined __x86_64__) && defined __GNUC__
#define ZMQ_ATOMIC_COUNTER_X86
#elif defined __ARM_ARCH_7A__ && defined __GNUC__
#define ZMQ_ATOMIC_COUNTER_ARM
#elif defined ZMQ_HAVE_WINDOWS
#define ZMQ_ATOMIC_COUNTER_WINDOWS
#elif (defined ZMQ_HAVE_SOLARIS || defined ZMQ_HAVE_NETBSD)
#define ZMQ_ATOMIC_COUNTER_ATOMIC_H
#elif defined __tile__
#define ZMQ_ATOMIC_COUNTER_TILE
#else
#define ZMQ_ATOMIC_COUNTER_MUTEX
#endif
#if defined ZMQ_ATOMIC_COUNTER_MUTEX
#include "mutex.hpp"
#elif defined ZMQ_ATOMIC_COUNTER_WINDOWS
#include "windows.hpp"
#elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
#include <atomic.h>
#elif defined ZMQ_ATOMIC_COUNTER_TILE
#include <arch/atomic.h>
#endif
namespace zmq {
// This class represents an integer that can be incremented/decremented
// in atomic fashion.
class atomic_counter_t {
public:
typedef uint32_t integer_t;
inline atomic_counter_t(integer_t value_ = 0) :
value(value_) {
}
inline ~atomic_counter_t() {
}
// Set counter value (not thread-safe).
inline void set(integer_t value_) {
value = value_;
}
// Atomic addition. Returns the old value.
inline integer_t add(integer_t increment_) {
integer_t old_value;
#if defined ZMQ_ATOMIC_COUNTER_WINDOWS
old_value = InterlockedExchangeAdd ((LONG*) &value, increment_);
#elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
integer_t new_value = atomic_add_32_nv (&value, increment_);
old_value = new_value - increment_;
#elif defined ZMQ_ATOMIC_COUNTER_TILE
old_value = arch_atomic_add (&value, increment_);
#elif defined ZMQ_ATOMIC_COUNTER_X86
__asm__ volatile (
"lock; xadd %0, %1 \n\t"
: "=r" (old_value), "=m" (value)
: "0" (increment_), "m" (value)
: "cc", "memory");
#elif defined ZMQ_ATOMIC_COUNTER_ARM
integer_t flag, tmp;
__asm__ volatile (
" dmb sy\n\t"
"1: ldrex %0, [%5]\n\t"
" add %2, %0, %4\n\t"
" strex %1, %2, [%5]\n\t"
" teq %1, #0\n\t"
" bne 1b\n\t"
" dmb sy\n\t"
: "=&r"(old_value), "=&r"(flag), "=&r"(tmp), "+Qo"(value)
: "Ir"(increment_), "r"(&value)
: "cc");
#elif defined ZMQ_ATOMIC_COUNTER_MUTEX
sync.lock ();
old_value = value;
value += increment_;
sync.unlock ();
#else
#error atomic_counter is not implemented for this platform
#endif
return old_value;
}
// Atomic subtraction. Returns false if the counter drops to zero.
inline bool sub(integer_t decrement) {
#if defined ZMQ_ATOMIC_COUNTER_WINDOWS
LONG delta = - ((LONG) decrement);
integer_t old = InterlockedExchangeAdd ((LONG*) &value, delta);
return old - decrement != 0;
#elif defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
int32_t delta = - ((int32_t) decrement);
integer_t nv = atomic_add_32_nv (&value, delta);
return nv != 0;
#elif defined ZMQ_ATOMIC_COUNTER_TILE
int32_t delta = - ((int32_t) decrement);
integer_t nv = arch_atomic_add (&value, delta);
return nv != 0;
#elif defined ZMQ_ATOMIC_COUNTER_X86
integer_t oldval = -decrement;
volatile integer_t *val = &value;
__asm__ volatile ("lock; xaddl %0,%1"
: "=r" (oldval), "=m" (*val)
: "0" (oldval), "m" (*val)
: "cc", "memory");
return oldval != decrement;
#elif defined ZMQ_ATOMIC_COUNTER_ARM
integer_t old_value, flag, tmp;
__asm__ volatile (
" dmb sy\n\t"
"1: ldrex %0, [%5]\n\t"
" sub %2, %0, %4\n\t"
" strex %1, %2, [%5]\n\t"
" teq %1, #0\n\t"
" bne 1b\n\t"
" dmb sy\n\t"
: "=&r"(old_value), "=&r"(flag), "=&r"(tmp), "+Qo"(value)
: "Ir"(decrement), "r"(&value)
: "cc");
return old_value - decrement != 0;
#elif defined ZMQ_ATOMIC_COUNTER_MUTEX
sync.lock ();
value -= decrement;
bool result = value ? true : false;
sync.unlock ();
return result;
#else
#error atomic_counter is not implemented for this platform
#endif
}
inline integer_t get() {
return value;
}
private:
volatile integer_t value;
#if defined ZMQ_ATOMIC_COUNTER_MUTEX
mutex_t sync;
#endif
atomic_counter_t(const atomic_counter_t &);
const atomic_counter_t &operator=(const atomic_counter_t &);
};
}
// Remove macros local to this file.
#if defined ZMQ_ATOMIC_COUNTER_WINDOWS
#undef ZMQ_ATOMIC_COUNTER_WINDOWS
#endif
#if defined ZMQ_ATOMIC_COUNTER_ATOMIC_H
#undef ZMQ_ATOMIC_COUNTER_ATOMIC_H
#endif
#if defined ZMQ_ATOMIC_COUNTER_X86
#undef ZMQ_ATOMIC_COUNTER_X86
#endif
#if defined ZMQ_ATOMIC_COUNTER_ARM
#undef ZMQ_ATOMIC_COUNTER_ARM
#endif
#if defined ZMQ_ATOMIC_COUNTER_MUTEX
#undef ZMQ_ATOMIC_COUNTER_MUTEX
#endif
#endif
| lgpl-3.0 |
TheRosettaFoundation/solas-protobuf | generated/js/emails/PasswordResetEmail.js | 327 | var _root=dcodeIO.ProtoBuf.newBuilder().create([{"name":"PasswordResetEmail","fields":[{"rule":"required","type":"EmailMessage.Type","name":"email_type","id":1,"options":{"default":"PasswordResetEmail"}},{"rule":"required","type":"int32","name":"user_id","id":2,"options":{}}],"enums":[],"messages":[],"options":{}}]).build();
| lgpl-3.0 |
amjames/psi4 | psi4/src/psi4/libpsio/volseek.cc | 2216 | /*
* @BEGIN LICENSE
*
* Psi4: an open-source quantum chemistry software package
*
* Copyright (c) 2007-2018 The Psi4 Developers.
*
* The copyrights for code used from other parties are included in
* the corresponding files.
*
* This file is part of Psi4.
*
* Psi4 is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, version 3.
*
* Psi4 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along
* with Psi4; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* @END LICENSE
*/
/*!
\file
\ingroup PSIO
*/
#include <unistd.h>
#include "psi4/libpsio/psio.h"
#include "psi4/psi4-dec.h"
/* This is strictly used to avoid overflow errors on lseek() calls */
#define PSIO_BIGNUM 10000
namespace psi {
/*!
** PSIO_VOLSEEK()
**
** \ingroup PSIO
*/
int psio_volseek(psio_vol *vol, size_t page, size_t offset, size_t numvols) {
int stream, errcod;
size_t bignum, total_offset;
bignum = PSIO_BIGNUM*numvols;
stream = vol->stream;
/* Set file pointer to beginning of file */
errcod = lseek(stream, (size_t) 0, SEEK_SET);
if (errcod == -1)
return (errcod);
/* lseek() through large chunks of the file to avoid offset overflows */
for (; page > bignum; page -= bignum) {
total_offset = PSIO_BIGNUM * PSIO_PAGELEN;
errcod = lseek(stream, total_offset, SEEK_CUR);
if (errcod == -1)
return (errcod);
}
/* Now compute the final offset including the page-relative term */
total_offset = (size_t) page/numvols; /* This should truncate */
total_offset *= PSIO_PAGELEN;
total_offset += offset; /* Add the page-relative term */
errcod = lseek(stream, total_offset, SEEK_CUR);
if (errcod == -1)
return (errcod);
return (0);
}
}
| lgpl-3.0 |
Builders-SonarSource/sonarqube-bis | server/sonar-web/src/main/js/components/ui/Avatar.js | 2211 | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { connect } from 'react-redux';
import md5 from 'blueimp-md5';
import classNames from 'classnames';
import { getSettingValue } from '../../store/rootReducer';
class Avatar extends React.Component {
static propTypes = {
enableGravatar: React.PropTypes.bool.isRequired,
gravatarServerUrl: React.PropTypes.string.isRequired,
email: React.PropTypes.string,
size: React.PropTypes.number.isRequired,
className: React.PropTypes.string
};
render () {
if (!this.props.enableGravatar) {
return null;
}
const emailHash = md5.md5((this.props.email || '').toLowerCase()).trim();
const url = this.props.gravatarServerUrl
.replace('{EMAIL_MD5}', emailHash)
.replace('{SIZE}', this.props.size * 2);
const className = classNames(this.props.className, 'rounded');
return (
<img className={className}
src={url}
width={this.props.size}
height={this.props.size}
alt={this.props.email}/>
);
}
}
const mapStateToProps = state => ({
enableGravatar: (getSettingValue(state, 'sonar.lf.enableGravatar') || {}).value === 'true',
gravatarServerUrl: (getSettingValue(state, 'sonar.lf.gravatarServerUrl') || {}).value
});
export default connect(mapStateToProps)(Avatar);
export const unconnectedAvatar = Avatar;
| lgpl-3.0 |
moinejf/abc2svg | Scc1t2/70.js | 4340 | // abc2svg sound font
abcsf2[70] = '\
UklGRjwMAABzZmJrTElTVGYAAABJTkZPaWZpbAQAAAACAAEAaXNuZwgAAABFTVU4MDAwAElOQU0O\
AAAAU2NjMXQyIGJhc29vbgBJU0ZUKAAAAGxpYkluc3RQYXRjaCB2MS4wLjA6bGliSW5zdFBhdGNo\
IDEuMC4wAABMSVNUSgkAAHNkdGFzbXBsPgkAAAAA2QD1AJwAAgE0AWsCBwIXAfz/cv9nAYAB2wKo\
A4oD9wLdA6YBywCR/8D/0v6s/9D/6P5DADcBxQC5ADP/Uv87/in//f+OAAYDWgXPBhsH0QenBioF\
TQPRAIL+hf0L/U/9hP0T/5T/BACwAGIAfv+R/43+sP0E/fz8gPzK/Pf8ePwh/IT7Hvvw+nT7qvtD\
/Jf8ef3A/Sz+Y/7Q/rX+0f5U/tH9Gf3g/JX8n/wS/LX7ZftW+4X7Rfvm+/v7a/wG/QH91PzV/KP8\
tvyK/On7M/v/+r/6GPqb+VH5vfgf+Jf3SPYu9hz2qvY594j3rPg3+qr7jf2Y/kv/fwAuAQ8BDgHQ\
/9L+Qv6F/WP9Q/wE/E38sPzJ/Z3+f/4L//L/wAAmAlsD0wPZBYoG2wflB7kHfQclB54HpwcjB0kH\
WgY+BpcFUQWEBKADcQP+AeYBUQHaARICpQFsAfv/Q/7P/df7+fqn+gX7L/tq/dT9wv5G/z7/Vv+j\
/xv/k/4M/gr+G//fAD8C9gK0Al4C2AJoAXUCdAE6AlQDEwVuB7QKXwz6DlQPkQ/9D0APQw67DjEN\
lgzhDNELXwuWCmgJTgh4B4UF4wMJAgoBXACD/3/+rf5c/oX/3f7d/2kATAOKA6UDxQH9AJsBrQAu\
/6z9xvvG/PX9yf6WANoC5gR4Bz4JxQneC4oL1gt9CxQKZAneCI8H4QYdB1sGPAaJBb4DAQPkATkB\
nAD//iP98vsy+sT4SfiP9vf1EvZV9Crz5fHy8LvxKvL28lTzB/Qh9UT3LvjY+HH6//kk+6j7m/vr\
/Nb8BP7t/bH9D/1n/KH7t/kN+Rv3vvWX9UD0uvSN9Pb0cvUa9uv1RPfZ9+33BfjV9l31HfXQ883y\
e/F679vune4O7+3vtu+68JLy2fPO9dn2m/fP+a/7lP1h/vz+mf/+APgBDgMeA44CaQOtBFcG5QiP\
CqoM2Q9dEusUkxZCF5UXRBfUFmQWthRAEzERxQ54DHgJQwb1AhMA8PwO+oP3EfV483nyivI88pLy\
tPL88gH0V/Wr9p/31fgT+o76pvpK+mH4sPYy9ATx0ewJ6dfki+C83Inartlw3SPk3+1h+BgGWBUg\
JTo2/kL+S3JQ808YTPlCFjjEKhEd1BHQB/cA9PsE+1v8qgEDCBEKSQmKBJsEOgXjAcf+TvcK8wLy\
1fHh8vDwM/ER74vtuOsq6ZnmP+g87QPzj/jZ/s0D4wlfD1QVaxdkGZQbCh36Hy8l1CjiK5Au3S4m\
Lj8t5StiKHIkMiA0G64WZBMJDwgLSwamAeT7BPdx8iru9+oG6QPny+Tr4gThueBr48PmJusq8Az1\
NPqg/mYCcAPBAVf82fWS7ffl4d2H1s3Rqc3VzGjNb9C71ljdxuet8aP8DgdyD0YXgBywH50gER5j\
F4cOpwOL93jrS98D1G7J9cHUvG27pL0+w6zL/NVH4RPszvYzAeEJHhGfFbIY1Rm/Gh4awBfyFBkS\
Cw8wC4UHeQOMAGT/7v2j/MD7q/uf/az/qwIdBXEINAzxD04SKxT6FD4VhxT8EooPigxfCQIGhwIz\
/rT5IvUB8QbtFep257zmyubw6PnrC/Hw9cL7UwEsBkoKoQ22D6ERABIPEhMQhQ1SCa0D3vuJ8hnn\
h9oFzVLArrV+sLexgrqEyhXiBP8oH3c/A1yocCJ8J3yxbxRa9DsvHJP/hemB3g/eherc+loQsR9E\
KCYwsi/5MFYjoxiDDM7+kPqD9bHyYfF78SPxgvOA+WP7LwKKBSMKEAnoA3n/1/RP7avpjeij66P0\
4P1hCekVDh7qIuYkiyXrIhAh2iB8H+MechzHGXwV5hNiEsERXBNDF7wbKyObK/Qx5zbmN8A05Sw0\
IowVCwkU/uD0+e3E6MnnHumS7PnxPPfe+pb74/hU8YXnb9oayjq5lKZVlxONkojliqqToqIatYjL\
YuFZ9oQK1RyHLGM3oT9KQe491zedLAEenA3A+tHnata1x0m7QbN9roitCLKxuQfFJNIy38vsjPg7\
AnwJLA69EFES4RJMEk4SzRIPExgTGRL6ENUOjgv0B9YDpQBk/2T/7v2j/MD7q/uf/az/qwIdBXEI\
NAzxD04SKxT6FD4VhxT8EooPigxfCQIGhwIz/rT5IvUB8QbtFep257zmAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAKgBZwEtA4ECZwFlAQr/nP4E/t37GPxy/CL7Qft/+4j7L/0h\
/h//VQC5ABwCTgNsBGYFpwYfCO8HEAh8B5kFXAWCBMwCjAH8/3X+W/3G+5L5Svhc91f2UPfe94X3\
6Pc6+fT5MfyPAe0FiArVC/kJAQnYBNIC7AJoAEb+rfwb+7b4GfXi8wX07PXD+hL/+wK2BeYHAAt8\
DP0MPQ6hDvYNPQ0qCzoIUgUqAmz/7/vG98Dzeu9q69HpsOix6HLsR/Lp/q0P8xn6IHwgkRadEC4K\
VgPcAV77uPaO9QXt9uS04BTeH+Ev6UDwIPUG/JEDwwwUFmUZHhxnHYUa4Bm5FysSeg7nC2MJHwbK\
AKT7zfaT8o/ufusc6hXr5uwi6yXlk94F2g/dHu8xC5YnP0ChR3M8XikjE/0Ff/4T9DjtheMW2SXa\
69fd1U/ah96B7AX7iQV4FG0d1CQgK44oDyPcIPge4xs+GMkSsg0nCiMHNgGl9/7tY+Un3XrWr9L5\
0+7WNtgV2vLeXPGuFfw/xGHRa01UnC1xD+IA7wJ4/+Hu2dsIwwuwYqbGob+q/8JY6YkQnCfEMDI1\
3jtFQO87qjF6Jf0aJBNHC+QBivkX9o35nP4i/677qPQG7M7oB+1U9S/+wP6+8NrU0rEDoPu7+vxg\
SBx7J3wwU9kgAQMuAHf+4e7h7tnbCMMLsGKmxqG/qv/CWOmJEJwnxDAyNd47RUDvO6oxeiX9GiQT\
RwvkAYr5F/aN+Zz+Iv+u+6j0BuzO6AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
TElTVHACAABwZHRhcGhkckwAAABCYXNzb29uAAAAAAAAAAAAAAAAAEYAAAAAAAAAAAAAAAAAAAAA\
AEVPUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAcGJhZwgAAAAAAAAAAQAAAHBt\
b2QKAAAAAAAAAAAAAAAAAHBnZW4IAAAAKQAAAAAAAABpbnN0LAAAAEJhc3Nvb24AAAAAAAAAAAAA\
AAAAAABFT0kAAAAAAAAAAAAAAAAAAAAAAAMAaWJhZxAAAAAAAAAAEQABACIAAgAzAAMAaW1vZCgA\
AAACAQgAAAACDQAAAgEIAAAAAg0AAAIBCAAAAAINAAAAAAAAAAAAAAAAaWdlbtAAAAArAAAyBgAD\
AA0AAQAQAAAAFQCf+xYArv0XAJ/7GACu/R0A6AMkAIoKJQAWACYAI+MwADoAMwAAADQAAAA2AAEA\
NQAAACsAM0QGAAMADQABABAAAAAVAJ/7FgCu/RcAn/sYAK79HQDoAyQAigolABYAJgAj4zAAHgAz\
AAAANAAAADYAAQA1AAEAKwBFYQYAAwANAAEAEAAAABUAn/sWAK79FwCf+xgArv0dAOgDJACKCiUA\
FgAmACPjMAAiADMAAAA0AAAANgABADUAAQAAAAAAc2hkcooAAABCQVNTTjQ0AAAAAAAAAAAAAAAA\
AAAAAAAlAwAAMQIAAAUDAAAiVgAALP0AAAEAQkFTU042OQAAAAAAAAAAAAAAAABTAwAAcQQAACAE\
AABRBAAAIlYAAEXZAAABAEVPUwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\
AAAAAAA=\
'
| lgpl-3.0 |
anlambert/tulip | thirdparty/OGDF/src/ogdf/layered/FastSimpleHierarchyLayout.cpp | 15927 | /** \file
* \brief Implementation of the FastSimpleHierarchyLayout
* (third phase of sugiyama)
*
* \author Till Schäfer, Carsten Gutwenger
*
* \par License:
* This file is part of the Open Graph Drawing Framework (OGDF).
*
* \par
* Copyright (C)<br>
* See README.md in the OGDF root directory for details.
*
* \par
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* Version 2 or 3 as published by the Free Software Foundation;
* see the file LICENSE.txt included in the packaging of this file
* for details.
*
* \par
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* \par
* You should have received a copy of the GNU General Public
* License along with this program; if not, see
* http://www.gnu.org/copyleft/gpl.html
*/
#include <ogdf/layered/FastSimpleHierarchyLayout.h>
namespace ogdf {
FastSimpleHierarchyLayout::FastSimpleHierarchyLayout()
{
m_minXSep = LayoutStandards::defaultNodeSeparation();
m_ySep = 1.5 * LayoutStandards::defaultNodeSeparation();
m_balanced = true;
m_downward = true;
m_leftToRight = true;
}
FastSimpleHierarchyLayout::FastSimpleHierarchyLayout(const FastSimpleHierarchyLayout &fshl)
{
m_minXSep = fshl.m_minXSep;
m_ySep = fshl.m_ySep;
m_balanced = fshl.m_balanced;
m_downward = fshl.m_downward;
m_leftToRight = fshl.m_leftToRight;
}
FastSimpleHierarchyLayout &FastSimpleHierarchyLayout::operator=(const FastSimpleHierarchyLayout &fshl)
{
m_minXSep = fshl.m_minXSep;
m_ySep = fshl.m_ySep;
m_balanced = fshl.m_balanced;
m_downward = fshl.m_downward;
m_leftToRight = fshl.m_leftToRight;
return *this;
}
void FastSimpleHierarchyLayout::doCall(const HierarchyLevelsBase &levels, GraphAttributes &AGC)
{
const Hierarchy &H = levels.hierarchy();
const GraphCopy &GC = H;
if (GC.numberOfNodes() == 0) {
return;
}
NodeArray<node> align(GC);
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
for(int i = 0; i <= levels.high(); ++i) {
std::cout << "level " << i << ": ";
const LevelBase &level = levels[i];
for(int j = 0; j <= level.high(); ++j)
std::cout << level[j] << " ";
std::cout << std::endl;
}
#endif
if (m_balanced) {
// the x positions; x = -infinity <=> x is undefined
NodeArray<double> x[4];
NodeArray<double> blockWidth[4];
NodeArray<node> root[4];
double width[4];
double min[4];
double max[4];
int minWidthLayout = 0;
// initializing
for (int i = 0; i < 4; i++) {
min[i] = std::numeric_limits<double>::max();
max[i] = std::numeric_limits<double>::lowest();
}
// calc the layout for down/up and leftToRight/rightToLeft
for (int downward = 0; downward <= 1; downward++) {
NodeArray<NodeArray<bool> > type1Conflicts(GC);
markType1Conflicts(levels, downward == 0, type1Conflicts);
for (int leftToRight = 0; leftToRight <= 1; leftToRight++) {
int k = 2 * downward + leftToRight;
root[k].init(GC);
verticalAlignment(levels, root[k], align, type1Conflicts, downward == 0, leftToRight == 0);
computeBlockWidths(GC, AGC, root[k], blockWidth[k]);
horizontalCompactation(align, levels, root[k], blockWidth[k], x[k], leftToRight == 0, downward == 0);
}
}
/*
* - calc min/max x coordinate for each layout
* - calc x-width for each layout
* - find the layout with the minimal width
*/
for (int i = 0; i < 4; i++) {
for(node v : GC.nodes) {
double bw = 0.5 * blockWidth[i][root[i][v]];
double xp = x[i][v] - bw;
if (min[i] > xp) {
min[i] = xp;
}
xp = x[i][v] + bw;
if (max[i] < xp) {
max[i] = xp;
}
}
width[i] = max[i] - min[i];
if (width[minWidthLayout] > width[i]) {
minWidthLayout = i;
}
}
/*
* shift the layout so that they align with the minimum width layout
* - leftToRight: align minimum coordinate
* - rightToLeft: align maximum coordinate
*/
double shift[4];
for (int i = 0; i < 4; i++) {
if (i % 2 == 0) {
// for leftToRight layouts
shift[i] = min[minWidthLayout] - min[i];
} else {
// for rightToLeft layouts
shift[i] = max[minWidthLayout] - max[i];
}
}
/*
* shift the layouts and use the
* median average coordinate for each node
*/
Array<double> sorting(4);
for(node v : GC.nodes) {
for (int i = 0; i < 4; i++) {
sorting[i] = x[i][v] + shift[i];
}
sorting.quicksort();
AGC.x(v) = 0.5 * (sorting[1] + sorting[2]);
}
} else {
NodeArray<double> x;
NodeArray<NodeArray<bool> > type1Conflicts(GC);
markType1Conflicts(levels, m_downward, type1Conflicts);
NodeArray<double> blockWidth; // the width of each block (max width of node in block)
NodeArray<node> root(GC);
verticalAlignment(levels, root, align, type1Conflicts, m_downward, m_leftToRight);
computeBlockWidths(GC, AGC, root, blockWidth);
horizontalCompactation(align, levels, root, blockWidth, x, m_leftToRight, m_downward);
for(node v : GC.nodes) {
AGC.x(v) = x[v];
}
}
// compute y-coordinates
const int k = levels.size();
// compute height of each layer
Array<double> height(0,k-1,0.0);
for(int i = 0; i < k; ++i) {
const LevelBase &level = levels[i];
for(int j = 0; j < level.size(); ++j) {
double h = getHeight(AGC, levels, level[j]);
if(h > height[i])
height[i] = h;
}
}
// assign y-coordinates
double yPos = 0.5 * height[0];
for(int i = 0; ; ++i)
{
const LevelBase &level = levels[i];
for(int j = 0; j < level.size(); ++j)
AGC.y(level[j]) = yPos;
if(i == k-1)
break;
yPos += m_ySep + 0.5 * (height[i] + height[i+1]);
}
}
void FastSimpleHierarchyLayout::markType1Conflicts(const HierarchyLevelsBase &levels, const bool downward, NodeArray<NodeArray<bool> > &type1Conflicts)
{
const GraphCopy& GC = levels.hierarchy();
for(node v : GC.nodes) {
type1Conflicts[v].init(GC,false);
}
if (levels.size() >= 4) {
int upper, lower; // iteration bounds
int k1; // node position boundaries of closest inner segments
HierarchyLevelsBase::TraversingDir relupward; // upward relativ to the direction from downward
if (downward) {
lower = 1;
upper = levels.high() - 2;
relupward = HierarchyLevelsBase::TraversingDir::downward;
}
else {
lower = levels.high() - 1;
upper = 2;
relupward = HierarchyLevelsBase::TraversingDir::upward;
}
/*
* iterate level[2..h-2] in the given direction
*
* availible levels: 1 to h
*/
for (int i = lower; (downward && i <= upper) || (!downward && i >= upper); i = downward ? i + 1 : i - 1)
{
int k0 = 0;
int firstIndex = 0; // index of first node on layer
const LevelBase ¤tLevel = levels[i];
const LevelBase &nextLevel = downward ? levels[i+1] : levels[i-1];
// for all nodes on next level
for (int l1 = 0; l1 <= nextLevel.high(); l1++) {
const node virtualTwin = virtualTwinNode(levels, nextLevel[l1], relupward);
if (l1 == nextLevel.high() || virtualTwin != nullptr) {
k1 = currentLevel.high();
if (virtualTwin != nullptr) {
k1 = levels.pos(virtualTwin);
}
for (; firstIndex <= l1; firstIndex++) {
const Array<node> &upperNeighbours = levels.adjNodes(nextLevel[l1], relupward);
for (auto currentNeighbour : upperNeighbours) {
/*
* XXX: < 0 in first iteration is still ok for indizes starting
* with 0 because no index can be smaller than 0
*/
if (levels.pos(currentNeighbour) < k0 || levels.pos(currentNeighbour) > k1) {
type1Conflicts[nextLevel[l1]][currentNeighbour] = true;
}
}
}
k0 = k1;
}
}
}
}
}
void FastSimpleHierarchyLayout::verticalAlignment(
const HierarchyLevelsBase &levels,
NodeArray<node> &root,
NodeArray<node> &align,
const NodeArray<NodeArray<bool> > &type1Conflicts,
bool downward,
const bool leftToRight)
{
const GraphCopy& GC = levels.hierarchy();
HierarchyLevelsBase::TraversingDir relupward; // upward relativ to the direction from downward
relupward = downward ? HierarchyLevelsBase::TraversingDir::downward : HierarchyLevelsBase::TraversingDir::upward;
// initialize root and align
for(node v : GC.nodes) {
root[v] = v;
align[v] = v;
}
// for all Level
for (int i = downward ? 0 : levels.high();
(downward && i <= levels.high()) || (!downward && i >= 0);
i = downward ? i + 1 : i - 1)
{
const LevelBase ¤tLevel = levels[i];
int r = leftToRight ? -1 : std::numeric_limits<int>::max();
// for all nodes on Level i (with direction leftToRight)
for (int j = leftToRight ? 0 : currentLevel.high();
(leftToRight && j <= currentLevel.high()) || (!leftToRight && j >= 0);
leftToRight ? j++ : j--)
{
node v = currentLevel[j];
// the first median
int median = (int)floor((levels.adjNodes(v, relupward).size() + 1) / 2.0);
int medianCount = (levels.adjNodes(v, relupward).size() % 2 == 1) ? 1 : 2;
if (levels.adjNodes(v, relupward).size() == 0) {
medianCount = 0;
}
// for all median neighbours in direction of H
for (int count = 0; count < medianCount; count++) {
node u = levels.adjNodes(v, relupward)[median + count - 1];
if (align[v] == v
// if segment (u,v) not marked by type1 conflicts AND ...
&& !type1Conflicts[v][u]
&& ((leftToRight && r < levels.pos(u))
|| (!leftToRight && r > levels.pos(u)))) {
align[u] = v;
root[v] = root[u];
align[v] = root[v];
r = levels.pos(u);
}
}
}
}
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
for(node v : GC.nodes) {
std::cout
<< "node: " << GC.original(v) << "/" << v
<< ", root: " << GC.original(root[v]) << "/" << root[v]
<< ", alignment: " << GC.original(align[v]) << "/" << align[v] << std::endl;
}
#endif
}
void FastSimpleHierarchyLayout::computeBlockWidths(
const GraphCopy &GC,
const GraphAttributes &GCA,
NodeArray<node> &root,
NodeArray<double> &blockWidth)
{
blockWidth.init(GC, 0.0);
for(node v : GC.nodes) {
if (!GC.isDummy(v)) {
Math::updateMax(blockWidth[root[v]], GCA.width(v));
}
}
}
void FastSimpleHierarchyLayout::horizontalCompactation(
const NodeArray<node> &align,
const HierarchyLevelsBase &levels,
const NodeArray<node> &root,
const NodeArray<double> &blockWidth,
NodeArray<double> &x,
const bool leftToRight, bool downward)
{
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "-------- Horizontal Compactation --------" << std::endl;
#endif
const GraphCopy& GC = levels.hierarchy();
NodeArray<node> sink(GC);
NodeArray<double> shift(GC, std::numeric_limits<double>::max());
x.init(GC, std::numeric_limits<double>::lowest());
for(node v : GC.nodes) {
sink[v] = v;
}
// calculate class relative coordinates for all roots
for (int i = downward ? 0 : levels.high();
(downward && i <= levels.high()) || (!downward && i >= 0);
i = downward ? i + 1 : i - 1)
{
const LevelBase ¤tLevel = levels[i];
for (int j = leftToRight ? 0 : currentLevel.high();
(leftToRight && j <= currentLevel.high()) || (!leftToRight && j >= 0);
leftToRight ? j++ : j--)
{
node v = currentLevel[j];
if (root[v] == v) {
placeBlock(v, sink, shift, x, align, levels, blockWidth, root, leftToRight);
}
}
}
double d = 0;
for (int i = downward ? 0 : levels.high();
(downward && i <= levels.high()) || (!downward && i >= 0);
i = downward ? i + 1 : i - 1)
{
const LevelBase ¤tLevel = levels[i];
node v = currentLevel[leftToRight ? 0 : currentLevel.high()];
if(v == sink[root[v]]) {
double oldShift = shift[v];
if(oldShift < std::numeric_limits<double>::max()) {
shift[v] += d;
d += oldShift;
} else
shift[v] = 0;
}
}
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "------- Sinks ----------" << std::endl;
#endif
// apply root coordinates for all aligned nodes
// (place block did this only for the roots)
for(node v : GC.nodes) {
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
if (sink[root[v]] == v) {
std::cout << "Topmost Root von Senke!: " << GC.original(v) << std::endl;
std::cout << "-> Shift: " << shift[v] << std::endl;
std::cout << "-> x: " << x[v] << std::endl;
}
#endif
x[v] = x[root[v]];
}
// apply shift for each class
for(node v : GC.nodes) {
x[v] += shift[sink[root[v]]];
}
}
void FastSimpleHierarchyLayout::placeBlock(
node v,
NodeArray<node> &sink,
NodeArray<double> &shift,
NodeArray<double> &x,
const NodeArray<node> &align,
const HierarchyLevelsBase &levels,
const NodeArray<double> &blockWidth,
const NodeArray<node> &root,
const bool leftToRight)
{
const Hierarchy &H = levels.hierarchy();
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
const GraphCopy& GC = H;
#endif
if (x[v] == std::numeric_limits<double>::lowest()) {
x[v] = 0;
node w = v;
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "---placeblock: " << GC.original(v) << " ---" << std::endl;
#endif
do {
// if not first node on layer
if ((leftToRight && levels.pos(w) > 0) || (!leftToRight && levels.pos(w) < levels[H.rank(w)].high())) {
node u = root[pred(w, levels, leftToRight)];
placeBlock(u, sink, shift, x, align, levels, blockWidth, root, leftToRight);
if (sink[v] == v) {
sink[v] = sink[u];
}
if (sink[v] != sink[u]) {
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "old shift " << GC.original(sink[u]) << ": " << shift[sink[u]] << "<>" << x[v] - x[u] - m_minXSep << std::endl;
#endif
if (leftToRight) {
shift[sink[u]] = min<double>(shift[sink[u]], x[v] - x[u] - m_minXSep - 0.5 * (blockWidth[u] + blockWidth[v]));
} else {
shift[sink[u]] = max<double>(shift[sink[u]], x[v] - x[u] + m_minXSep + 0.5 * (blockWidth[u] + blockWidth[v]));
}
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "-> new shift: " << shift[sink[u]] << std::endl;
#endif
}
else {
if (leftToRight) {
x[v] = max<double>(x[v], x[u] + m_minXSep + 0.5 * (blockWidth[u] + blockWidth[v]));
} else {
x[v] = min<double>(x[v], x[u] - m_minXSep - 0.5 * (blockWidth[u] + blockWidth[v]));
}
}
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "placing w: " << GC.original(w) << "; predecessor: " << GC.original(pred(w, levels, leftToRight)) <<
"; root(w)=v: " << GC.original(v) << "; root(pred(u)): " << GC.original(u) <<
"; sink(v): " << GC.original(sink[v]) << "; sink(u): " << GC.original(sink[u]) << std::endl;
std::cout << "x(v): " << x[v] << std::endl;
} else {
std::cout << "not placing w: " << GC.original(w) << " because at beginning of layer" << std::endl;
#endif
}
w = align[w];
} while (w != v);
#ifdef OGDF_FAST_SIMPLE_HIERARCHY_LAYOUT_LOGGING
std::cout << "---END placeblock: " << GC.original(v) << " ---" << std::endl;
#endif
}
}
node FastSimpleHierarchyLayout::virtualTwinNode(const HierarchyLevelsBase &levels, const node v, const HierarchyLevelsBase::TraversingDir dir) const
{
const Hierarchy &H = levels.hierarchy();
if (!H.isLongEdgeDummy(v) || levels.adjNodes(v, dir).size() == 0) {
return nullptr;
}
if (levels.adjNodes(v, dir).size() > 1) {
// since v is a dummy there sould be only one upper neighbour
throw AlgorithmFailureException("FastSimpleHierarchyLayout.cpp");
}
return *levels.adjNodes(v, dir).begin();
}
node FastSimpleHierarchyLayout::pred(const node v, const HierarchyLevelsBase &levels, const bool leftToRight)
{
const Hierarchy &H = levels.hierarchy();
int pos = levels.pos(v);
int rank = H.rank(v);
const LevelBase &level = levels[rank];
if ((leftToRight && pos != 0) || (!leftToRight && pos != level.high())) {
return level[leftToRight ? pos - 1 : pos + 1];
}
return nullptr;
}
}
| lgpl-3.0 |
webforge-labs/psc-cms | lib/Psc/CMS/Item/DropBoxButtonableValueObject.php | 866 | <?php
namespace Psc\CMS\Item;
use Psc\CMS\RequestMetaInterface;
class DropBoxButtonableValueObject extends TabButtonableValueObject implements DropBoxButtonable {
protected $identifier;
protected $entityName;
public static function copyFromDropBoxButtonable(DropBoxButtonable $buttonable) {
$valueObject = self::copyFromTabButtonable($buttonable);
$valueObject->setIdentifier($buttonable->getIdentifier());
$valueObject->setEntityName($buttonable->getEntityName());
return $valueObject;
}
public function getIdentifier() {
return $this->identifier;
}
public function setIdentifier($id) {
$this->identifier = $id;
return $this;
}
public function setEntityName($fqn) {
$this->entityName = $fqn;
return $this;
}
public function getEntityName() {
return $this->entityName;
}
}
?> | lgpl-3.0 |
kbss-cvut/reporting-tool | src/main/webapp/tests/__tests__/ReportValidatorTest.js | 3932 | /*
* Copyright (C) 2017 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
describe('Report validator', function () {
var ReportValidator = require('../../js/validation/ReportValidator'),
Constants = require('../../js/constants/Constants'),
report;
beforeEach(function () {
report = {
javaClass: Constants.OCCURRENCE_REPORT_JAVA_CLASS,
occurrence: {
name: 'TestReport',
startTime: Date.now() - 1000,
endTime: Date.now(),
eventType: 'http://onto.fel.cvut.cz/ontologies/eccairs-1.3.0.8/V-24-430-28'
},
severityAssessment: 'INCIDENT',
summary: 'Report narrative',
typeAssessments: [{
eventType: {
id: 'http://onto.fel.cvut.cz/ontologies/eccairs-1.3.0.8/V-24-1-31-31-14-390-2000000-2200000-2200100',
name: '2200100 - Runway incursions'
}
}]
};
});
it('marks valid report as valid', function () {
expect(ReportValidator.isValid(report)).toBeTruthy();
});
it('marks report without occurrence as invalid', () => {
delete report.occurrence;
expect(ReportValidator.isValid(report)).toBeFalsy();
});
it('marks report without headline as invalid', function () {
report.occurrence.name = '';
expect(ReportValidator.isValid(report)).toBeFalsy();
});
it('marks report without severity assessment as invalid', function () {
delete report.severityAssessment;
expect(ReportValidator.isValid(report)).toBeFalsy();
});
it('marks report without occurrence category as invalid', function () {
delete report.occurrence.eventType;
expect(ReportValidator.isValid(report)).toBeFalsy();
});
it('marks report without narrative as invalid', function () {
report.summary = '';
expect(ReportValidator.isValid(report)).toBeFalsy();
});
it('returns missing field message when report without narrative is validated', function () {
report.summary = '';
expect(ReportValidator.getValidationMessage(report)).toEqual('detail.invalid-tooltip');
});
it('marks report with too large occurrence start and end time diff as invalid', function () {
report.occurrence.startTime = Date.now() - Constants.MAX_OCCURRENCE_START_END_DIFF - 1000;
report.occurrence.endTime = Date.now();
expect(ReportValidator.isValid(report)).toBeFalsy();
});
it('reports time difference error message when report with too large occurrence start and end time diff is validated', function () {
report.occurrence.startTime = Date.now() - Constants.MAX_OCCURRENCE_START_END_DIFF - 1000;
report.occurrence.endTime = Date.now();
expect(ReportValidator.getValidationMessage(report)).toEqual('detail.large-time-diff-tooltip');
});
it('marks report with too large occurrence start and end time diff as not renderable', function () {
report.occurrence.startTime = Date.now() - Constants.MAX_OCCURRENCE_START_END_DIFF - 1000;
report.occurrence.endTime = Date.now();
expect(ReportValidator.canRender(report)).toBeFalsy();
});
});
| lgpl-3.0 |
a-lucas/angular.js-server | test/e2e/common/requestUrl.js | 5323 | 'use strict';
var phantomHelper = require('./phantomHelper')
var fs = require('fs-extra');
var path = require('path');
var chai = require('chai');
var debug = require('debug')('mocha-test');
var expect = chai.expect;
module.exports.testClosePhantomJS = function () {
describe('Stopping PhantomJS', function () {
it('should stop it', function (done) {
phantomHelper.closePhantom().then( () => {
done();
}, (err) => {
done(err);
});
});
});
};
module.exports.testDescribeURL = function (url, conf) {
var getFileName = function (url, prefix, name) {
return path.join(__dirname, '/../outputs', encodeURIComponent(url), prefix + '.' + name + '.html');
};
describe('Creating the output directory: ', function () {
it('Should create the directory ' + path.join(__dirname, '/../outputs', encodeURIComponent(url)), function (done) {
try {
fs.mkdirsSync(path.join(__dirname, '/../outputs', encodeURIComponent(url)));
done();
}
catch (e) {
done(e);
}
});
});
describe(`URL: ${url}`, function () {
conf.forEach(function (serverData) {
describe(serverData.desc, function () {
it('phantom with js disabled', function (done) {
phantomHelper.jsDisabled(serverData.url + url).then((html) => {
debug('noJS received ', url);
fs.writeFileSync(getFileName(url, serverData.prefix, 'js-disabled'), html, 'utf-8');
done();
}, (err) => {
debug(err);
done(err);
}).catch( (e) => {
debug('excetion', e);
done(e);
});
});
it('phantom with js enabled - wait 4000ms', function (done) {
phantomHelper.jsEnabled(serverData.url + url).then( html => {
debug('success JS', url);
fs.writeFileSync(getFileName(url, serverData.prefix, 'js-enabled'), html, 'utf-8');
done();
}, err => {
debug(err);
done(err);
}).catch((err) =>{
debug(err);
done(err);
});
});
if (serverData.equals.length >= 2) {
it(serverData.equals[0] + ' should render the same HTML than ' + serverData.equals[1], function (done) {
try {
var file1 = fs.readFileSync(getFileName(url, serverData.prefix, serverData.equals[0]), 'utf-8').trim();
var file2 = fs.readFileSync(getFileName(url, serverData.prefix, serverData.equals[1]), 'utf-8').trim();
expect(file1).to.equal(file2);
done();
} catch( e) {
done(e);
}
});
}
/*
if(serverData.cache === true) {
beforeEach(function() {
cachedUrl = cacheEngine.url(url);
});
it('The files should have been cached by the server', function(done) {
cachedUrl.has().then(function(cached) {
expect(cached).to.be.ok;
done();
}, function(e) {
debug('cachedURL = ', cachedUrl);
done(e);
}).catch(function(err){
done(err);
});
});
it('The server cached file should match phantom.js-enabled\'s output', function(done) {
try {
var phantomJSHtml = fs.readFileSync( getFileName(url, serverData.prefix, 'js-enabled'), 'utf-8').trim();
cachedUrl.get().then(function(content) {
expect(tidy(content).trim()).to.eql(phantomJSHtml);
done();
}, function(err) {
done(err);
}).catch(function(err) {
done(err)
});
} catch(e) {
done(e);
}
});
it('We remove the server\'s cached file', function(done) {
cachedUrl.delete().then(function(removed) {
expect(removed).eql(true);
done();
}, function(err){
done(err);
})
});
};*/
it('Should remove test files ok', function (done) {
try {
fs.unlinkSync(getFileName(url, serverData.prefix, 'js-disabled'));
fs.unlinkSync(getFileName(url, serverData.prefix, 'js-enabled'));
done();
} catch (e) {
done(e);
}
});
});
});
});
}; | lgpl-3.0 |
saullocastro/pyNastran | pyNastran/applications/cart3d_nastran_fsi/delauney_reader.py | 14037 | from __future__ import print_function
import os
from six.moves import zip
from numpy import array, cross, dot, abs as npabs
from numpy.linalg import norm, solve #, cond
from pyNastran.applications.cart3d_nastran_fsi.math_functions import is_list_ranged, list_print, shepard_weight
#from pyNastran.applications.cart3d_nastran_fsi.matTest import fIsNatural
from pyNastran.bdf.field_writer_8 import print_card_8
from logger import dummyLogger
logger_obj = dummyLogger()
log = logger_obj.startLog('debug') # or info
#------------------------------------------------------------------
class Tet4(object):
def __init__(self, p0, p1, p2, p3, ID=None, nodes=None, neighbors=None):
"""
The internal tets dont need a number or list of nodes.
The Delauney TETs do!
"""
if neighbors is None:
neighbors = []
self.p0 = array(p0)
self.p1 = array(p1)
self.p2 = array(p2)
self.p3 = array(p3)
self.ID = ID
self.nodes = nodes
self.neighbors = neighbors
#self.face0 = (self.p0 + self.p1 + self.p2)/3
#self.face1 = (self.p0 + self.p1 + self.p3)/3
#self.face2 = (self.p0 + self.p2 + self.p3)/3
#self.face3 = (self.p1 + self.p2 + self.p3)/3
#print("face0 = ", self.face0)
#print("p0 = ", p0)
#print("p1 = ", p1)
#print("p2 = ", p2)
#print("p3 = ", p3)
self._centroid = self.calculate_centroid()
self._volume = None
#vol = self.volume()
#vol2 = self.testVol(self.p0, self.p1,
# self.p2, self.p3)
#assert vol == vol2
#msg = "volume[%s]=%s" % (ID, vol)
#assert vol>0,msg
#log.info(msg)
def __repr__(self):
nodes = "[%3s, %3s, %3s, %3s]" % (
self.nodes[0], self.nodes[1], self.nodes[2], self.nodes[3])
return "ID=%4s nodes=%s p0=%s p1=%s p2=%s p3=%s" % (
self.ID, nodes, self.p0, self.p1, self.p2, self.p3)
def calculate_centroid(self):
"""
centroid = (a+b+c)/4 with point d at the origin
or more generally...
centroid = ((a-d)+(b-d)+(c-d))/4 = (a+b+c-3d)/4
based on http://en.wikipedia.org/wiki/Tetrahedron
"""
c = (self.p0 + self.p1 + self.p2 - 3 * self.p3) / 4
return c
def centroid(self):
return self._centroid
def abs_volume(self):
return npabs(self.volume())
def test_vol(self, a, b, c, d):
vol = dot(a-d, cross(b-d, c-d)) / 6.
return vol
def volume(self):
"""
volume = dot(a-d, cross(b-d, c-d))/6
based on http://en.wikipedia.org/wiki/Tetrahedron
"""
if self._volume is None:
self._volume = dot(self.p0-self.p3, cross(self.p1-self.p3, self.p2-self.p3))/6.
else:
return self._volume
return self._volume
def map_deflections2(self, deflections, aero_node):
#A =
pass
def map_deflections(self, deflections, aero_node):
"""
determines the mapped x,y,z deflections of the aero node
Parameters
----------
deflections : ???
deflections at p0,p1,p2,p3
aero_node : ???
node to find the deflections at
Solves Ax=b where A is the nodes, x is the abc coeffs,
b is the deflection at the tet node points (x,y,z)
then uses x to find the deflection at an arbitrary point m (aero_node)
"""
A = array([[1.]+list(self.p0),
[1.]+list(self.p1),
[1.]+list(self.p2),
[1.]+list(self.p3)])
#print("m1 = ", m)
(d1, d2, d3, d4) = deflections
log.info('d1=%s' % d1)
log.info('d2=%s' % d2)
log.info('d3=%s' % d3)
log.info('d4=%s' % d4)
#log.info("A = \n%s" % (A))
#condA = cond(A,2)
#log.info("A cond=%g; A=\n%s" % (condA, print_matrix(A)))
#print("ID = ",self.ID)
#condMax = 1E6 # max allowable condition number before alternate approach
if 1:
nodes = [self.p0, self.p1, self.p2, self.p3]
weights = shepard_weight(aero_node, nodes)
du = array([0., 0., 0.])
for (node, weight) in zip(nodes, weights):
du += weight * node
else:
ux = self.map_deflection(A, d1, d2, d3, d4, 0, aero_node, 'x')
uy = self.map_deflection(A, d1, d2, d3, d4, 1, aero_node, 'y')
uz = self.map_deflection(A, d1, d2, d3, d4, 2, aero_node, 'z')
du = array([ux, uy, uz])
log.info("vol = %s" % self.volume())
log.info("du = %s" % du)
return aero_node + du
def map_deflection(self, A, d1, d2, d3, d4, i, aero_node, dType='x'):
"""
see mapDeflections...
based on the posiition matrix, finds the ith deflection component
Then we ratios the new deflection diMax and compares it to the nearby points to 'test'.
"""
di = array([d1[i], d2[i], d3[i], d4[i]])
diMax = max(npabs(di)) # L1 norm
log.info("d%s = %s" % (dType, list_print(di)))
abcd = solve(A, di)
#ui = abcd*aero_node # element-wise multiplication...faster,
# cant make it work; tried dot & transpose too...
(a, b, c, d) = abcd
ui = a + b*aero_node[0] + c*aero_node[1] + d*aero_node[2]
is_ranged = is_list_ranged(0., abcd, 1.)
log.info('is_ranged=%s u%sRatio=%g - a=%g b=%g c=%g d=%g' %(
is_ranged, dType, npabs(ui/diMax), a, b, c, d))
return ui
def is_internal_node(self, pAero):
r"""
If there is an internal node, than the sum of the internal volumes without
an absolute value will equal the volume of the local tet
* 3
/ \
*---* 0 1
\*/ 2
"""
is_contained, gammas = fIsNatural(pAero, self.p0, self.p1, self.p2, self.p3,
V=self._volume)
return is_contained, min(gammas)
#a = Tet4(self.p0, self.p1, self.p2, pAero,ID='a',nodes=[0,1,2,'p'])
#b = Tet4(self.p0, self.p1, pAero,self.p3, ID='b',nodes=[0,1,'p',3])
#c = Tet4(pAero,self.p0, self.p2, self.p3, ID='c',nodes=['p',0,2,3])
#d = Tet4(self.p1,pAero, self.p2, self.p3, ID='d',nodes=[1,'p',2,3])
#aVol = a.volume()
#if aVol >= 0:
# bVol = b.volume()
# if bVol >= 0:
# cVol = c.volume()
# if cVol >= 0.:
# dVol = d.volume()
# if dVol >= 0:
# return True
#return False
#aVol = a.volume()
#bVol = b.volume()
#cVol = c.volume()
#dVol = d.volume()
#allv = [aVol, bVol, cVol, dVol]
#minThis = sum(allv) - max(allv)
#print("vol[%s] = [%g %g %g %g] %g" %(self.ID, aVol, bVol, cVol, dVol, minThis))
#minVol = min(aVol, bVol, cVol, dVol)
#if minVol < 0.:
#return False, minThis
#return True, minThis
#------------------------------------------------------------------
class DelauneyReader(object):
def __init__(self, infilename):
self.infilename = infilename
def build_tets(self):
grids, elements, volume = self.read()
tets = {}
for key, element_neighbors in elements.items():
nodes, neighbors = element_neighbors
id1, id0, id2, id3 = nodes
grid0 = grids[id0]
grid1 = grids[id1]
grid2 = grids[id2]
grid3 = grids[id3]
tet = Tet4(grid0, grid1, grid2, grid3,
ID=key, nodes=nodes, neighbors=neighbors)
tets[key] = tet
#tets.append(tet)
return tets, grids, elements, volume
def distance(self, p1, p2):
#print("p1=", p1)
#print("p2=", p2)
return norm(p1 - p2)
#def testVolume(self):
#vol = 0.
#for tet in tets:
#vol += tet.volume()
#print("volume=%s vol=%s" % (volume, -vol/2.))
def test_mapper(self):
m = array([0., 0., 0.])
tets, grids, elements, volume = self.build_tets()
tet_new = self.find_closest_tet(m, tets)
self.update_node(m, tets)
return tet_new
def update_node(self, m, tets):
"""
Takes in a new point m (mid tet point) and a list of tets
from self.buildTets(), finds the tet the node should go in,
then updates the node based on the deflections at the local
tet.
"""
#m = array([21.18, 0.5, -1.87e-6])
tet_new = self.find_closest_tet(m, tets)
# def = deflections at p0,p1,p2,p3
new_aero_node = tet_new.map_deflections(deflections, m)
return new_aero_node
def find_closest_tet(self, m, tets):
"""
Finds the closest tet. Has the potential to fail, but until then, skipping.
Solution to failure: brute force method.
m = aeroNode
tets =
"""
starting_tet = tets[0]
closest_tet = self.find_closest_tet_recursion(m, starting_tet, tets)
#print("found tet = ", closestTet.ID)
#v1 = array([1., 0., 0.])
return closest_tet
def find_closest_tet_recursion(self, m, tet0, tets, excluded=None):
"""
Makes an assumption that there is a direct line from the starting tet
to the final tet that can be minimized with nearly every subsequent tet.
At worst, it will get the starting node one tet closer to the solution.
m = starting point (mid point)
"""
if excluded is None:
excluded = []
#print("working on tet = ",tet0.ID)
if tet0.is_internal_node(m):
return tet0
cent = tet0.centroid()
dist = m - cent
#faces = [tet0.face0, tet0.face1, tet0.face2, tet0.face3]
dists = [9.e9] * 4
for i, neighbor in enumerate(tet0.neighbors):
if neighbor > 0:
dists[i] = self.distance(m, tets[i].centroid())
#dists[0] = 9.e9
#print("dists = ", dists)
min_value = min(dists)
i = dists.index(min_value)
tet_new = tets[tet0.neighbors[i]]
excluded.append(tet0.ID)
#print("excluding ID=%s\n" % tet0.ID)
closest_tet = self.find_closest_tet_recursion(m, tet_new, tets, excluded)
return closest_tet
def read(self):
"""
reads all the node points, neighbors, and the IDs tet nodes,
determines the volume for testing.
"""
log.info("---reading Delauney Tetrahedralization file...%r" % self.infilename)
with open(self.infilename, 'r') as infile:
lines = infile.readlines()
slines = []
for line in lines:
sline = line.strip().split()
if sline:
slines.append(sline)
#log.info('slines[0] = %s' % (slines[0]))
ngrids, nelements = self.ints(slines[0])
log.info("ngrid=%s nelements=%s" % (ngrids, nelements))
grids = {}
for sline in slines[1:ngrids+1]:
node = self.node(sline)
grids[node[0]] = node[1:]
#print("id=%s grid=%s" %(node[0], node[1:]))
max_x = grids[1][0]
max_y = grids[1][1]
max_z = grids[1][2]
min_x = grids[1][0]
min_y = grids[1][1]
min_z = grids[1][2]
for key, grid in grids.items():
max_x = max(max_x, grid[0])
max_y = max(max_y, grid[1])
max_z = max(max_z, grid[2])
min_x = min(min_x, grid[0])
min_y = min(min_y, grid[1])
min_z = min(min_z, grid[2])
elements = {}
nelements = 1
for sline in slines[ngrids+1:]:
e = self.ints(sline)
#print(e)
neighbors = e[1:5]
#print("e[1:4] = ", element1)
element = e[5:]
#print("e[3:] = ", element2)
#print(len(element1))
#print(len(element2))
elements[nelements] = [element, neighbors]
nelements += 1
#print("e[%s]=%s" %(e[0], e[1:]))
log.info("max_x=%s min_x=%s" % (max_x, min_x))
log.info("max_y=%s min_y=%s" % (max_y, min_y))
log.info("max_z=%s min_z=%s" % (max_z, min_z))
dx = max_x - min_x
dy = max_y - min_y
dz = max_z - min_z
volume = dx * dy * dz
log.info("volume = %s" % volume)
return grids, elements, volume
def write_tets_as_nastran(self, nodes, tets, tet_filename='tet.bdf'):
with open(tet_filename, 'wb') as outfile:
msg = ''
mid = 1 # material id
for nid, node in nodes.items():
card = ['GRID', ID, 0, node[0], node[1], node[2]]
msg += print_card_8(card)
outfile.write(msg)
msg = ''
for i, tet in enumerate(tets):
nodes = tet.nodes
msg += print_card_8(['CTETRA', tet.ID, mid, nodes[0], nodes[1], nodes[2], nodes[3]])
if i % 1000 == 0:
outfile.write(msg)
msg = ''
outfile.write(msg)
log.info("finished writing %s" % tet_filename)
def ints(self, values):
return [int(value) for value in values]
def floats(self, values):
return [float(value) for value in values]
def node(self, values):
return [int(values[0])] + self.floats(values[1:])
def run():
infilename = os.path.join('delauney', 'geometry.morph.in')
d = DelauneyReader(infilename)
tets, nodes, elements, volume = d.build_tets()
m = array([21.18, 0.5, -1.87347e-6])
d.find_closest_tet(m, tets)
d.write_tets_as_nastran(nodes, tets)
#d.read()
#d.testVolume()
if __name__ == '__main__':
run()
| lgpl-3.0 |
consultit/Ely | ely/direct/data_structures_and_algorithms/ch01/gpa2.py | 1333 | # Copyright 2013, Michael H. Goldwasser
#
# Developed for use with the book:
#
# Data Structures and Algorithms in Python
# Michael T. Goodrich, Roberto Tamassia, and Michael H. Goldwasser
# John Wiley & Sons, 2013
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def compute_gpa(grades, points={'A+':4.0, 'A':4.0, 'A-':3.67, 'B+':3.33,
'B':3.0, 'B-':2.67,'C+':2.33, 'C':2.0,
'C':1.67, 'D+':1.33, 'D':1.0, 'F':0.0}):
num_courses = 0
total_points = 0
for g in grades:
if g in points: # a recognizable grade
num_courses += 1
total_points += points[g]
return total_points / num_courses
| lgpl-3.0 |
aimeos/ai-client-html | client/html/src/Client/Html/Basket/Related/Standard.php | 6042 | <?php
/**
* @license LGPLv3, http://opensource.org/licenses/LGPL-3.0
* @copyright Aimeos (aimeos.org), 2015-2022
* @package Client
* @subpackage Html
*/
namespace Aimeos\Client\Html\Basket\Related;
/**
* Default implementation of related basket HTML client.
*
* @package Client
* @subpackage Html
*/
class Standard
extends \Aimeos\Client\Html\Basket\Base
implements \Aimeos\Client\Html\Common\Client\Factory\Iface
{
/**
* Sets the necessary parameter values in the view.
*
* @param \Aimeos\MW\View\Iface $view The view object which generates the HTML output
* @param array &$tags Result array for the list of tags that are associated to the output
* @param string|null &$expire Result variable for the expiration date of the output (null for no expiry)
* @return \Aimeos\MW\View\Iface Modified view object
*/
public function data( \Aimeos\MW\View\Iface $view, array &$tags = [], string &$expire = null ) : \Aimeos\MW\View\Iface
{
$context = $this->context();
$config = $context->config();
$cntl = \Aimeos\Controller\Frontend::create( $context, 'product' );
$basket = \Aimeos\Controller\Frontend::create( $context, 'basket' )->get();
/** client/html/basket/related/bought/limit
* Number of items in the list of bought together products
*
* This option limits the number of suggested products in the
* list of bought together products. The suggested items are
* calculated using the products that are in the current basket
* of the customer.
*
* Note: You need to start the job controller for calculating
* the bought together products regularly to get up to date
* product suggestions.
*
* @param integer Number of products
* @since 2014.09
*/
$size = $config->get( 'client/html/basket/related/bought/limit', 6 );
/** client/html/basket/related/bought/domains
* The list of domain names whose items should be available in the template for the products
*
* The templates rendering product details usually add the images,
* prices and texts, etc. associated to the product
* item. If you want to display additional or less content, you can
* configure your own list of domains (attribute, media, price, product,
* text, etc. are domains) whose items are fetched from the storage.
* Please keep in mind that the more domains you add to the configuration,
* the more time is required for fetching the content!
*
* @param array List of domain names
* @since 2014.09
*/
$domains = $config->get( 'client/html/basket/related/bought/domains', ['text', 'price', 'media'] );
$domains['product'] = ['bought-together'];
/** client/html/basket/related/basket-add
* Display the "add to basket" button for each product item
*
* Enables the button for adding products to the basket for the related products
* in the basket. This works for all type of products, even for selection products
* with product variants and product bundles. By default, also optional attributes
* are displayed if they have been associated to a product.
*
* @param boolean True to display the button, false to hide it
* @since 2020.10
* @see client/html/catalog/home/basket-add
* @see client/html/catalog/lists/basket-add
* @see client/html/catalog/detail/basket-add
* @see client/html/catalog/product/basket-add
*/
if( $view->config( 'client/html/basket/related/basket-add', false ) ) {
$domains = array_merge_recursive( $domains, ['product' => ['default'], 'attribute' => ['variant', 'custom', 'config']] );
}
$prodIds = $basket->getProducts()
->concat( $basket->getProducts()->getProducts() )
->col( 'order.base.product.parentproductid' )
->unique()->all();
$view->boughtItems = $cntl->uses( $domains )->product( $prodIds )->search()
->getListItems( 'product', 'bought-together' )
->flat( 1 )
->usort( function( $a, $b ) {
return $a->getPosition() <=> $b->getPosition();
} )
->getRefItem()
->filter()
->slice( 0, $size )
->col( null, 'product.id' );
return parent::data( $view, $tags, $expire );
}
/** client/html/basket/related/template-body
* Relative path to the HTML body template of the basket related client.
*
* The template file contains the HTML code and processing instructions
* to generate the result shown in the body of the frontend. The
* configuration string is the path to the template file relative
* to the templates directory (usually in client/html/templates).
*
* You can overwrite the template file configuration in extensions and
* provide alternative templates. These alternative templates should be
* named like the default one but suffixed by
* an unique name. You may use the name of your project for this. If
* you've implemented an alternative client class as well, it
* should be suffixed by the name of the new class.
*
* @param string Relative path to the template creating code for the HTML page body
* @since 2014.03
* @see client/html/basket/related/template-header
*/
/** client/html/basket/related/template-header
* Relative path to the HTML header template of the basket related client.
*
* The template file contains the HTML code and processing instructions
* to generate the HTML code that is inserted into the HTML page header
* of the rendered page in the frontend. The configuration string is the
* path to the template file relative to the templates directory (usually
* in client/html/templates).
*
* You can overwrite the template file configuration in extensions and
* provide alternative templates. These alternative templates should be
* named like the default one but suffixed by
* an unique name. You may use the name of your project for this. If
* you've implemented an alternative client class as well, it
* should be suffixed by the name of the new class.
*
* @param string Relative path to the template creating code for the HTML page head
* @since 2014.03
* @see client/html/basket/related/template-body
*/
}
| lgpl-3.0 |
beangle/beanfuse | beanfuse-commons/src/main/java/org/beanfuse/text/BundleTextResource.java | 800 | package org.beanfuse.text;
import java.text.MessageFormat;
import java.util.Locale;
import java.util.ResourceBundle;
public class BundleTextResource extends AbstractTextResource {
private Locale locale;
private ResourceBundle bundle;
public Locale getLocale() {
return locale;
}
public String getText(String key) {
return bundle.getString(key);
}
public String getText(String key, Object[] args) {
String text = bundle.getString(key);
MessageFormat format = new MessageFormat(text);
format.setLocale(locale);
format.applyPattern(text);
return format.format(args);
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public ResourceBundle getBundle() {
return bundle;
}
public void setBundle(ResourceBundle bundle) {
this.bundle = bundle;
}
}
| lgpl-3.0 |
ymanvieu/trading | trading-common/src/main/java/fr/ymanvieu/trading/common/provider/lookup/ProviderCode.java | 833 | /**
* Copyright (C) 2016 Yoann Manvieu
*
* This software is free software: you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package fr.ymanvieu.trading.common.provider.lookup;
public enum ProviderCode {
YAHOO,
GOOGLE
}
| lgpl-3.0 |
qrooel/madison_square | lib/PEAR/PEAR/Frontend/Web.php | 91440 | <?php
/**
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2007 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Christian Dickmann <dickmann@php.net> |
| Tias Guns <tias@ulyssis.org> |
+----------------------------------------------------------------------+
* @category pear
* @package PEAR_Frontend_Web
* @author Christian Dickmann <dickmann@php.net>
* @author Tias Guns <tias@ulyssis.org>
* @copyright 1997-2007 The PHP Group
* @license http://www.php.net/license/2_02.txt PHP License 2.02
* @version CVS: $Id: Web.php 6 2011-03-27 19:01:27Z gekosale $
* @link http://pear.php.net/package/PEAR_Frontend_Web
* @since File available since Release 0.1
*/
/**
* base class
*/
require_once 'PEAR.php';
require_once 'PEAR/Config.php';
require_once 'PEAR/Frontend.php';
require_once 'HTML/Template/IT.php';
/**
* PEAR_Frontend_Web is a HTML based Webfrontend for the PEAR Installer
*
* The Webfrontend provides basic functionality of the Installer, such as
* a package list grouped by categories, a search mask, the possibility
* to install/upgrade/uninstall packages and some minor things.
* PEAR_Frontend_Web makes use of the PEAR::HTML_IT Template engine which
* provides the possibillity to skin the Installer.
*
* @category pear
* @package PEAR_Frontend_Web
* @author Christian Dickmann <dickmann@php.net>
* @author Tias Guns <tias@ulyssis.org>
* @copyright 1997-2007 The PHP Group
* @license http://www.php.net/license/2_02.txt PHP License 2.02
* @version CVS: $Id: Web.php 6 2011-03-27 19:01:27Z gekosale $
* @link http://pear.php.net/package/PEAR_Frontend_Web
* @since File available since Release 0.1
*/
class PEAR_Frontend_Web extends PEAR_Frontend
{
// {{{ properties
/**
* What type of user interface this frontend is for.
* @var string
* @access public
*/
var $type = 'Web';
/**
* Container, where values can be saved temporary
* @var array
*/
var $_data = array();
/**
* Used to save output, to display it later
*/
var $_savedOutput = array();
/**
* The config object
*/
var $config;
/**
* List of packages that will not be deletable thourgh the webinterface
*/
var $_no_delete_pkgs = array(
'pear.php.net/Archive_Tar',
'pear.php.net/Console_Getopt',
'pear.php.net/HTML_Template_IT',
'pear.php.net/PEAR',
'pear.php.net/PEAR_Frontend_Web',
'pear.php.net/Structures_Graph',
'pear.php.net/XML_Util',
);
/**
* List of channels that will not be deletable thourgh the webinterface
*/
var $_no_delete_chans = array(
'pear.php.net',
'__uri',
);
/**
* How many categories to display on one 'list-all' page
*/
var $_paging_cats = 4;
/**
* Flag to determine whether to treat all output as information from a post-install script
* @var bool
*/
var $_installScript = false;
// }}}
// {{{ constructor
function PEAR_Frontend_Web()
{
parent::PEAR();
$this->config = &$GLOBALS['_PEAR_Frontend_Web_config'];
}
function setConfig(&$config)
{
$this->config = &$config;
}
// }}}
// {{{ _initTemplate()
/**
* Initialize a TemplateObject
*
* @param string $file filename of the template file
*
* @return object Object of HTML/IT - Template - Class
*/
function _initTemplate($file)
{
// Errors here can not be displayed using the UI
PEAR::staticPushErrorHandling(PEAR_ERROR_DIE);
$tpl_dir = $this->config->get('data_dir').DIRECTORY_SEPARATOR.'PEAR_Frontend_Web'.DIRECTORY_SEPARATOR.'data'.DIRECTORY_SEPARATOR.'templates';
if (!file_exists($tpl_dir) || !is_readable($tpl_dir)) {
PEAR::raiseError('<b>Error:</b> the template directory <i>('.$tpl_dir.')</i> is not a directory, or not readable. Make sure the \'data_dir\' of your config file <i>('.$this->config->get('data_dir').')</i> points to the correct location !');
}
$tpl = new HTML_Template_IT($tpl_dir);
$tpl->loadTemplateFile($file);
$tpl->setVariable("InstallerURL", $_SERVER["PHP_SELF"]);
PEAR::staticPopErrorHandling(); // reset error handling
return $tpl;
}
// }}}
// {{{ displayError()
/**
* Display an error page
*
* @param mixed $eobj PEAR_Error object or string containing the error message
* @param string $title (optional) title of the page
* @param string $img (optional) iconhandle for this page
* @param boolean $popup (optional) popuperror or normal?
*
* @access public
*
* @return null does not return anything, but exit the script
*/
function displayError($eobj, $title = 'Error', $img = 'error', $popup = false)
{
$msg = '';
if (PEAR::isError($eobj)) {
$msg .= trim($eobj->getMessage());
} else {
$msg .= trim($eobj);
}
$msg = nl2br($msg."\n");
$tplfile = ($popup ? "error.popup.tpl.html" : "error.tpl.html");
$tpl = $this->_initTemplate($tplfile);
$tpl->setVariable("Error", $msg);
$command_map = array(
"install" => "list",
"uninstall" => "list",
"upgrade" => "list",
);
if (isset($_GET['command'])) {
if (isset($command_map[$_GET['command']])) {
$_GET['command'] = $command_map[$_GET['command']];
}
$tpl->setVariable("param", '?command='.$_GET['command']);
}
$tpl->show();
exit;
}
// }}}
// {{{ displayFatalError()
/**
* Alias for PEAR_Frontend_Web::displayError()
*
* @see PEAR_Frontend_Web::displayError()
*/
function displayFatalError($eobj, $title = 'Error', $img = 'error')
{
$this->displayError($eobj, $title, $img);
}
// }}}
// {{{ _outputListChannels()
/**
* Output the list of channels
*/
function _outputListChannels($data)
{
$tpl = $this->_initTemplate('channel.list.tpl.html');
$tpl->setVariable("Caption", $data['caption']);
if (!isset($data['data'])) {
$data['data'] = array();
}
$reg = &$this->config->getRegistry();
foreach($data['data'] as $row) {
list($channel, $summary) = $row;
$url = sprintf('%s?command=channel-info&chan=%s',
$_SERVER['PHP_SELF'], urlencode($channel));
$channel_info = sprintf('<a href="%s" class="blue">%s</a>', $url, $channel);
// detect whether any packages from this channel are installed
$anyinstalled = $reg->listPackages($channel);
$id = 'id="'.$channel.'_href"';
if (in_array($channel, $this->_no_delete_chans) || (is_array($anyinstalled) && count($anyinstalled))) {
// dont delete
$del = ' ';
} else {
$img = '<img src="'.$_SERVER["PHP_SELF"].'?img=uninstall" width="18" height="17" border="0" alt="delete">';
$url = sprintf('%s?command=channel-delete&chan=%s',
$_SERVER["PHP_SELF"], urlencode($channel));
$del = sprintf('<a href="%s" onClick="return deleteChan(\'%s\');" %s >%s</a>',
$url, $channel, $id, $img);
}
$tpl->setCurrentBlock("Row");
$tpl->setVariable("ImgPackage", $_SERVER["PHP_SELF"].'?img=package');
$tpl->setVariable("UpdateChannelsURL", $_SERVER['PHP_SELF']);
$tpl->setVariable("Delete", $del);
$tpl->setVariable("Channel", $channel_info);
$tpl->setVariable("Summary", nl2br($summary));
$tpl->parseCurrentBlock();
}
$tpl->show();
return true;
}
// }}}
// {{{ _outputListAll()
/**
* Output a list of packages, grouped by categories. Uses Paging
*
* @param array $data array containing all data to display the list
* @param boolean $paging (optional) use Paging or not
*
* @return boolean true (yep. i am an optimist)
*
* DEPRECATED BY list-categories
*/
function _outputListAll($data, $paging=true)
{
if (!isset($data['data'])) {
return true;
}
$tpl = $this->_initTemplate('package.list.tpl.html');
$tpl->setVariable('Caption', $data['caption']);
if (!is_array($data['data'])) {
$tpl->show();
print('<p><table><tr><td width="50"> </td><td>'.$data['data'].'</td></tr></table></p>');
return true;
}
$command = isset($_GET['command']) ? $_GET['command']:'list-all';
$mode = isset($_GET['mode'])?$_GET['mode']:'';
$links = array('back' => '',
'next' => '',
'current' => '&mode='.$mode,
);
if ($paging) {
// Generate Linkinformation to redirect to _this_ page after performing an action
$link_str = '<a href="?command=%s&from=%s&mode=%s" class="paging_link">%s</a>';
$pageId = isset($_GET['from']) ? $_GET['from'] : 0;
$paging_data = $this->__getData($pageId, $this->_paging_cats, count($data['data']), false);
$data['data'] = array_slice($data['data'], $pageId, $this->_paging_cats);
$from = $paging_data['from'];
$to = $paging_data['to'];
if ($paging_data['from']>1) {
$links['back'] = sprintf($link_str, $command, $paging_data['prev'], $mode, '<<');
}
if ( $paging_data['next']) {
$links['next'] = sprintf($link_str, $command, $paging_data['next'], $mode, '>>');
}
$links['current'] = '&from=' . $paging_data['from'];
$blocks = array('Paging_pre', 'Paging_post');
foreach ($blocks as $block) {
$tpl->setCurrentBlock($block);
$tpl->setVariable('Prev', $links['back']);
$tpl->setVariable('Next', $links['next']);
$tpl->setVariable('PagerFrom', $from);
$tpl->setVariable('PagerTo', $to);
$tpl->setVariable('PagerCount', $paging_data['numrows']);
$tpl->parseCurrentBlock();
}
}
$reg = &$this->config->getRegistry();
foreach($data['data'] as $category => $packages) {
foreach($packages as $row) {
list($pkgChannel, $pkgName, $pkgVersionLatest, $pkgVersionInstalled, $pkgSummary) = $row;
$parsed = $reg->parsePackageName($pkgName, $pkgChannel);
$pkgChannel = $parsed['channel'];
$pkgName = $parsed['package'];
$pkgFull = sprintf('%s/%s-%s',
$pkgChannel,
$pkgName,
substr($pkgVersionLatest, 0, strpos($pkgVersionLatest, ' ')));
$tpl->setCurrentBlock("Row");
$tpl->setVariable("ImgPackage", $_SERVER["PHP_SELF"].'?img=package');
$images = array(
'install' => '<img src="'.$_SERVER["PHP_SELF"].'?img=install" width="13" height="13" border="0" alt="install">',
'uninstall' => '<img src="'.$_SERVER["PHP_SELF"].'?img=uninstall" width="18" height="17" border="0" alt="uninstall">',
'upgrade' => '<img src="'.$_SERVER["PHP_SELF"].'?img=install" width="13" height="13" border="0" alt="upgrade">',
'info' => '<img src="'.$_SERVER["PHP_SELF"].'?img=info" width="17" height="19" border="0" alt="info">',
'infoExt' => '<img src="'.$_SERVER["PHP_SELF"].'?img=infoplus" width="18" height="19" border="0" alt="extended info">',
);
$urls = array(
'install' => sprintf('%s?command=install&pkg=%s%s',
$_SERVER["PHP_SELF"], $pkgFull, $links['current']),
'uninstall' => sprintf('%s?command=uninstall&pkg=%s%s',
$_SERVER["PHP_SELF"], $pkgFull, $links['current']),
'upgrade' => sprintf('%s?command=upgrade&pkg=%s%s',
$_SERVER["PHP_SELF"], $pkgFull, $links['current']),
'info' => sprintf('%s?command=info&pkg=%s',
$_SERVER["PHP_SELF"], $pkgFull),
'remote-info' => sprintf('%s?command=remote-info&pkg=%s',
$_SERVER["PHP_SELF"], $pkgFull),
'infoExt' => 'http://' . $this->config->get('preferred_mirror').'/package/'.$pkgName,
);
$compare = version_compare($pkgVersionLatest, $pkgVersionInstalled);
$id = 'id="'.$pkgName.'_href"';
if (!$pkgVersionInstalled || $pkgVersionInstalled == "- no -") {
$inst = sprintf('<a href="%s" onClick="return installPkg(\'%s\');" %s>%s</a>',
$urls['install'], $pkgName, $id, $images['install']);
$del = '';
$info = sprintf('<a href="%s">%s</a>', $urls['remote-info'], $images['info']);
} else if ($compare == 1) {
$inst = sprintf('<a href="%s" onClick="return installPkg(\'%s\');" %s>%s</a>',
$urls['upgrade'], $pkgName, $id, $images['upgrade']);
$del = sprintf('<a href="%s" onClick="return uninstallPkg(\'%s\');" %s >%s</a>',
$urls['uninstall'], $pkgName, $id, $images['uninstall']);
$info = sprintf('<a href="%s">%s</a>', $urls['info'], $images['info']);
} else {
$inst = '';
$del = sprintf('<a href="%s" onClick="return uninstallPkg(\'%s\');" %s >%s</a>',
$urls['uninstall'], $pkgName, $id, $images['uninstall']);
$info = sprintf('<a href="%s">%s</a>', $urls['info'], $images['info']);
}
$infoExt = sprintf('<a href="%s">%s</a>', $urls['infoExt'], $images['infoExt']);
if (in_array($pkgChannel.'/'.$pkgName, $this->_no_delete_pkgs)) {
$del = '';
}
$tpl->setVariable("Latest", $pkgVersionLatest);
$tpl->setVariable("Installed", $pkgVersionInstalled);
$tpl->setVariable("Install", $inst);
$tpl->setVariable("Delete", $del);
$tpl->setVariable("Info", $info);
$tpl->setVariable("InfoExt", $infoExt);
$tpl->setVariable("Package", $pkgName);
$tpl->setVariable("Channel", $pkgChannel);
$tpl->setVariable("Summary", nl2br($pkgSummary));
$tpl->parseCurrentBlock();
}
$tpl->setCurrentBlock("Category");
$tpl->setVariable("categoryName", $category);
$tpl->setVariable("ImgCategory", $_SERVER["PHP_SELF"].'?img=category');
$tpl->parseCurrentBlock();
}
$tpl->show();
return true;
}
// }}}
// {{{ _outputListFiles()
/**
* Output a list of files of a packagename
*
* @param array $data array containing all files of a package
*
* @return boolean true (yep. i am an optimist)
*/
function _outputListFiles($data)
{
sort($data['data']);
return $this->_outputGenericTableVertical($data['caption'], $data['data']);
}
// }}}
// {{{ _outputListDocs()
/**
* Output a list of documentation files of a packagename
*
* @param array $data array containing all documentation files of a package
*
* @return boolean true (yep. i am an optimist)
*/
function _outputListDocs($data)
{
$tpl = $this->_initTemplate('caption.tpl.html');
$tpl->setVariable('Caption', $data['caption']);
$tpl->show();
if (is_array($data['data'])) {
print $this->_getListDocsDiv($data['channel'].'/'.$data['package'], $data['data']);
} else {
print $data['data'];
}
return true;
}
/**
* Get list of the docs of a package in a HTML div
*
* @param string $pkg full package name (channel/package)
* @param array $files array of all files and there location
* @return string HTML
*/
function _getListDocsDiv($pkg, $files) {
$out = '<div id="listdocs"><ul>';
foreach($files as $name => $location) {
$out .= sprintf('<li><a href="%s?command=doc-show&pkg=%s&file=%s" title="%s">%s</a></li>',
$_SERVER['PHP_SELF'],
$pkg,
urlencode($name),
$location,
$name);
}
$out .= '</ul></div>';
return $out;
}
// }}}
// {{{ _outputDocShow()
/**
* Output a documentation file of a packagename
*
* @param array $data array containing all documentation files of a packages
*
* @return boolean true (yep. i am an optimist)
*/
function _outputDocShow($data)
{
$tpl = $this->_initTemplate('caption.tpl.html');
$tpl->setVariable('Caption', $data['caption']);
$tpl->show();
print '<div id="docshow">'.nl2br(htmlentities($data['data'])).'</div>';
return true;
}
// }}}
// {{{ _outputListPackages()
/**
* Output packagenames (of a channel or category)
*
* @param array $data array containing all information about the packages
*
* @return boolean true (yep. i am an optimist)
*/
function _outputListPackages($data)
{
$ROWSPAN=3;
$caption = sprintf('<a name="%s"><img src="%s?img=category" /> %s (%s)</a>',
$data['channel'],
$_SERVER['PHP_SELF'],
$data['caption'],
count($data['data']));
$newdata = null;
if (!is_array($data['data'])) {
$newdata = $data['data'];
} else {
$newdata = array(0 => array());
$row = 0;
$col = 0;
$rows = ceil(count($data['data'])/$ROWSPAN);
foreach ($data['data'] as $package) {
if ($row == $rows) { // row is full
$row = 0;
$col++;
}
if ($col == 0) { // create clean arrays
$newdata[$row] = array();
}
$newdata[$row][$col] = sprintf('<img src="%s?img=package" /> <a href="%s?command=info&pkg=%s/%s" class="blue">%s</a>',
$_SERVER['PHP_SELF'],
$_SERVER['PHP_SELF'],
$package[0],
$package[1],
$package[1]);
$row++;
}
while ($row != $rows) {
$newdata[$row][$col] = ' ';
$row++;
}
}
return $this->_outputGenericTableHorizontal($caption, $newdata);
}
// }}}
// {{{ _outputListCategories()
/**
* Prepare output per channel/category
*
* @param array $data array containing caption, channel and headline
*
* @return $tpl Template Object
*/
function _prepareListCategories($data)
{
$channel = $data['channel'];
if (!is_array($data['data']) && $channel == '__uri') {
// no categories in __uri, don't show this ugly duck !
return true;
}
$tpl = $this->_initTemplate('categories.list.tpl.html');
$tpl->setVariable('categoryName', $data['caption']);
$tpl->setVariable('channel', $data['channel']);
// set headlines
if (isset($data['headline']) && is_array($data['headline'])) {
foreach($data['headline'] as $text) {
$tpl->setCurrentBlock('Headline');
$tpl->setVariable('Text', $text);
$tpl->parseCurrentBlock();
}
} else {
$tpl->setCurrentBlock('Headline');
$tpl->setVariable('Text', $data['data']);
$tpl->parseCurrentBlock();
unset($data['data']); //clear
}
// set extra title info
$tpl->setCurrentBlock('Title_info');
$info = sprintf('<a href="%s?command=list-packages&chan=%s" class="green">List all packagenames of this channel.</a>',
$_SERVER['PHP_SELF'],
$channel
);
$tpl->setVariable('Text', $info);
$tpl->parseCurrentBlock();
$tpl->setCurrentBlock('Title_info');
$info = sprintf('<a href="%s?command=list-categories&chan=%s&opt=packages" class="green">List all packagenames, by category, of this channel.</a>',
$_SERVER['PHP_SELF'],
$channel
);
$tpl->setVariable('Text', $info);
$tpl->parseCurrentBlock();
return $tpl;
}
/**
* Output the list of categories of a channel
*
* @param array $data array containing all data to display the list
*
* @return boolean true (yep. i am an optimist)
*/
function _outputListCategories($data)
{
$tpl = $this->_prepareListCategories($data);
if (isset($data['data']) && is_array($data['data'])) {
foreach($data['data'] as $row) {
@list($channel, $category, $packages) = $row;
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $channel);
$tpl->parseCurrentBlock();
$tpl->setCurrentBlock('Data_row');
$info = sprintf('<a href="%s?command=list-category&chan=%s&cat=%s" class="green">%s</a>',
$_SERVER['PHP_SELF'],
$channel,
$category,
$category
);
$tpl->setVariable('Text', $info);
$tpl->parseCurrentBlock();
if (is_array($packages)) {
if (count($packages) == 0) {
$info = '<i>(no packages registered)</i>';
} else {
$info = sprintf('<img src="%s?img=package" />: ',
$_SERVER['PHP_SELF']);
}
foreach($packages as $i => $package) {
$info .= sprintf('<a href="%s?command=info&pkg=%s/%s" class="blue">%s</a>',
$_SERVER['PHP_SELF'],
$channel,
$package,
$package
);
if ($i+1 != count($packages)) {
$info .= ', ';
}
}
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $info);
$tpl->parseCurrentBlock();
}
$tpl->setCurrentBlock('Data');
$tpl->setVariable('Img', 'category');
$tpl->parseCurrentBlock();
}
}
$tpl->show();
return true;
}
/**
* Output the list of packages of a category of a channel
*
* @param array $data array containing all data to display the list
*
* @return boolean true (yep. i am an optimist)
*/
function _outputListCategory($data)
{
if (isset($data['headline'])) {
// create place for install/uninstall icon:
$summary = array_pop($data['headline']);
$data['headline'][] = ' '; // icon
$data['headline'][] = $summary; // restore summary
}
$tpl = $this->_prepareListCategories($data);
$channel = $data['channel'];
if (isset($data['data']) && is_array($data['data'])) {
foreach($data['data'] as $row) {
// output summary after install icon
$summary = array_pop($row);
foreach ($row as $i => $col) {
if ($i == 1) {
$package = $col;
// package name, make URL
$col = $this->_prepPkgName($package, $channel);
}
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $col);
$tpl->parseCurrentBlock();
}
// install or uninstall icon
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $this->_prepIcons($package, $channel));
$tpl->parseCurrentBlock();
// now the summary
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $summary);
$tpl->parseCurrentBlock();
// and finish.
$tpl->setCurrentBlock('Data');
$tpl->setVariable('Img', 'package');
$tpl->parseCurrentBlock();
}
}
$tpl->show();
return true;
}
// }}}
// {{{ _outputList()
/**
* Output the list of installed packages.
*
* @param array $data array containing all data to display the list
*
* @return boolean true (yep. i am an optimist)
*/
function _outputList($data)
{
$channel = $data['channel'];
if (!is_array($data['data']) && $channel == '__uri') {
// no packages in __uri, don't show this ugly duck !
return true;
}
$tpl = $this->_initTemplate('package.list_nocat.tpl.html');
$tpl->setVariable('categoryName', $data['caption']);
//$tpl->setVariable('Border', $data['border']);
// set headlines
if (isset($data['headline']) && is_array($data['headline'])) {
// overwrite
$data['headline'] = array('Channel', 'Package', 'Local', ' ', 'Summary');
foreach($data['headline'] as $text) {
$tpl->setCurrentBlock('Headline');
$tpl->setVariable('Text', $text);
$tpl->parseCurrentBlock();
}
} else {
$tpl->setCurrentBlock('Headline');
if (is_array($data['data']) && isset($data['data'][0])) {
$tpl->setVariable('Text', $data['data'][0][0]);
} else {
$tpl->setVariable('Text', $data['data']);
}
$tpl->parseCurrentBlock();
unset($data['data']); //clear
}
if (isset($data['data']) && is_array($data['data'])) {
foreach($data['data'] as $row) {
$package = $row[0].'/'.$row[1];
$package_name = $row[1];
$local = sprintf('%s (%s)', $row[2], $row[3]);
// Channel
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $channel);
$tpl->parseCurrentBlock();
// Package
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $this->_prepPkgName($package_name, $channel));
$tpl->parseCurrentBlock();
// Local
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $local);
$tpl->parseCurrentBlock();
// Icons (uninstall)
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $this->_prepIcons($package_name, $channel, true));
$tpl->parseCurrentBlock();
// Summary
$tpl->setCurrentBlock('Data_row');
$reg = $this->config->getRegistry();
$tpl->setVariable('Text', $reg->packageInfo($package_name, 'summary', $channel));
$tpl->parseCurrentBlock();
// and finish.
$tpl->setCurrentBlock('Data');
$tpl->setVariable("ImgPackage", $_SERVER["PHP_SELF"].'?img=package');
$tpl->parseCurrentBlock();
}
}
$tpl->show();
return true;
}
// }}}
// {{{ _outputListUpgrades()
/**
* Output the list of available upgrades packages.
*
* @param array $data array containing all data to display the list
*
* @return boolean true (yep. i am an optimist)
*/
function _outputListUpgrades($data)
{
$tpl = $this->_initTemplate('package.list_nocat.tpl.html');
$tpl->setVariable('categoryName', $data['caption']);
//$tpl->setVariable('Border', $data['border']);
$channel = $data['channel'];
// set headlines
if (isset($data['headline']) && is_array($data['headline'])) {
$data['headline'][] = ' ';
foreach($data['headline'] as $text) {
$tpl->setCurrentBlock('Headline');
$tpl->setVariable('Text', $text);
$tpl->parseCurrentBlock();
}
} else {
$tpl->setCurrentBlock('Headline');
$tpl->setVariable('Text', $data['data']);
$tpl->parseCurrentBlock();
unset($data['data']); //clear
}
if (isset($data['data']) && is_array($data['data'])) {
foreach($data['data'] as $row) {
$package = $channel.'/'.$row[1];
$package_name = $row[1];
foreach($row as $i => $text) {
if ($i == 1) {
// package name
$text = $this->_prepPkgName($text, $channel);
}
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', $text);
$tpl->parseCurrentBlock();
}
// upgrade link
$tpl->setCurrentBlock('Data_row');
$img = sprintf('<img src="%s?img=install" width="18" height="17" border="0" alt="upgrade">', $_SERVER["PHP_SELF"]);
$url = sprintf('%s?command=upgrade&pkg=%s', $_SERVER["PHP_SELF"], $package);
$text = sprintf('<a href="%s" onClick="return installPkg(\'%s\');" id="%s">%s</a>', $url, $package, $package.'_href', $img);
$tpl->setVariable('Text', $text);
$tpl->parseCurrentBlock();
// and finish.
$tpl->setCurrentBlock('Data');
$tpl->setVariable("ImgPackage", $_SERVER["PHP_SELF"].'?img=package');
$tpl->parseCurrentBlock();
}
}
$tpl->show();
return true;
}
// }}}
function _getPackageDeps($deps)
{
if (count($deps) == 0) {
return "<i>No dependencies registered.</i>\n";
} else {
$rel_trans = array(
'lt' => 'older than %s',
'le' => 'version %s or older',
'eq' => 'version %s',
'ne' => 'any version but %s',
'gt' => 'newer than %s',
'ge' => '%s or newer',
);
$dep_type_desc = array(
'pkg' => 'PEAR Package',
'ext' => 'PHP Extension',
'php' => 'PHP Version',
'prog' => 'Program',
'ldlib' => 'Development Library',
'rtlib' => 'Runtime Library',
'os' => 'Operating System',
'websrv' => 'Web Server',
'sapi' => 'SAPI Backend',
);
$result = " <dl>\n";
foreach($deps as $row) {
// Print link if it's a PEAR package
if ($row['type'] == 'pkg') {
$package = $row['channel'].'/'.$row['name'];
$row['name'] = sprintf('<a class="green" href="%s?command=remote-info&pkg=%s">%s</a>',
$_SERVER['PHP_SELF'], $package, $package);
}
if (isset($rel_trans[$row['rel']])) {
$rel = sprintf($rel_trans[$row['rel']], $row['version']);
$optional = isset($row['optional']) && $row['optional'] == 'yes';
$result .= sprintf("%s: %s %s" . $optional,
$dep_type_desc[$row['type']], @$row['name'], $rel);
} else {
$result .= sprintf("%s: %s", $dep_type_desc[$row['type']], $row['name']);
}
$result .= '<br>';
}
$result .= " </dl>\n";
}
return $result;
}
/**
* Output details of one package, info (local)
*
* @param array $data array containing all information about the package
*
* @return boolean true (yep. i am an optimist)
*/
function _outputPackageInfo($data)
{
$data['data'] = $this->htmlentities_recursive($data['data']);
if (!isset($data['raw']['channel'])) {
// package1.xml, channel by default pear
$channel = 'pear.php.net';
$package_name = $data['raw']['package'];
} else {
$channel = $data['raw']['channel'];
$package_name = $data['raw']['name'];
}
$package = $channel.'/'.$package_name;
// parse extra options
if (!in_array($package, $this->_no_delete_pkgs)) {
$image = sprintf('<img src="%s?img=uninstall" width="18" height="17" border="0" alt="uninstall">', $_SERVER["PHP_SELF"]);
$output = sprintf(
'<a href="%s?command=uninstall&pkg=%s" class="green" %s>%s Uninstall package</a>',
$_SERVER["PHP_SELF"],
$package,
'onClick="return uninstallPkg(\''.$package.'\');"',
$image);
$data['data'][] = array('Options', $output);
}
$output = '';
// More: Local Documentation
require_once('PEAR/Frontend/Web/Docviewer.php');
if (count(PEAR_Frontend_Web_Docviewer::getDocFiles($package_name, $channel)) !== 0) {
$image = sprintf('<img src="%s?img=manual" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="%s?command=list-docs&pkg=%s" class="green">%s Package Documentation</a>',
$_SERVER["PHP_SELF"],
$package,
$image);
$output .= '<br />';
}
$output .= sprintf(
'<a href="%s?command=list-files&pkg=%s" class="green">./.. List Files</a>',
$_SERVER["PHP_SELF"],
$package);
$output .= '<br />';
// More: Extended Package Information
$image = sprintf('<img src="%s?img=infoplus" border="0" alt="extra info">', $_SERVER["PHP_SELF"]);
if ($channel == 'pear.php.net' || $channel == 'pecl.php.net') {
$url = 'http://%s/package/%s/download/%s';
} else {
// the normal default
$url = 'http://%s/index.php?package=%s&release=%s';
}
$output .= sprintf(
'<a href="'.$url.'" class="green" target="_new">%s Extended Package Information</a>',
$this->config->get('preferred_mirror', null, $channel),
$package_name,
$data['raw']['version']['release'],
$image);
// More: Developer Documentation && Package Manual
if ($channel == 'pear.php.net') {
$output .= '<br />';
$image = sprintf('<img src="%s?img=manualplus" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="http://pear.php.net/package/%s/docs/latest" class="green" target="_new">%s pear.php.net Developer Documentation</a>',
$package_name,
$image);
$output .= '<br />';
$image = sprintf('<img src="%s?img=manualplus" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="http://pear.php.net/manual/en/" class="green" target="_new">%s pear.php.net Package Manual </a>',
$image);
}
$data['data'][] = array('More', $output);
return $this->_outputGenericTableVertical($data['caption'], $data['data']);
}
/**
* Output details of one package, remote-info
*
* @param array $data array containing all information about the package
*
* @return boolean true (yep. i am an optimist)
*/
function _outputPackageRemoteInfo($data)
{
include_once "PEAR/Downloader.php";
$tpl = $this->_initTemplate('package.info.tpl.html');
$tpl->setVariable("PreferredMirror", $this->config->get('preferred_mirror'));
/*
$dl = &new PEAR_Downloader($this, array(), $this->config);
// don't call private functions
// gives error, not gonna fix, but gonna skip
$info = $dl->_getPackageDownloadUrl(array('package' => $data['name'],
'channel' => $this->config->get('default_channel'), 'version' => $data['stable']));
if (isset($info['url'])) {
$tpl->setVariable("DownloadURL", $info['url']);
} else {
$tpl->setVariable("DownloadURL", $_SERVER['PHP_SELF']);
}
*/
$channel = $data['channel'];
$package = $data['channel'].'/'.$data['name'];
$package_full = $data['channel'].'/'.$data['name'].'-'.$data['stable'];
$tpl->setVariable("Latest", $data['stable']);
$tpl->setVariable("Installed", $data['installed']);
$tpl->setVariable("Package", $data['name']);
$tpl->setVariable("License", $data['license']);
$tpl->setVariable("Category", $data['category']);
$tpl->setVariable("Summary", nl2br($data['summary']));
$tpl->setVariable("Description", nl2br($data['description']));
$deps = @$data['releases'][$data['stable']]['deps'];
$tpl->setVariable("Dependencies", $this->_getPackageDeps($deps));
$compare = version_compare($data['stable'], $data['installed']);
$images = array(
'install' => '<img src="'.$_SERVER["PHP_SELF"].'?img=install" width="13" height="13" border="0" alt="install">',
'uninstall' => '<img src="'.$_SERVER["PHP_SELF"].'?img=uninstall" width="18" height="17" border="0" alt="uninstall">',
'upgrade' => '<img src="'.$_SERVER["PHP_SELF"].'?img=install" width="13" height="13" border="0" alt="upgrade">',
);
$opt_img = array();
$opt_text = array();
if (!$data['installed'] || $data['installed'] == "- no -") {
$opt_img[] = sprintf(
'<a href="%s?command=install&pkg=%s" %s>%s</a>',
$_SERVER["PHP_SELF"], $package_full,
'onClick="return installPkg(\''.$package_full.'\');"',
$images['install']);
$opt_text[] = sprintf(
'<a href="%s?command=install&pkg=%s" class="green" %s>Install package</a>',
$_SERVER["PHP_SELF"], $package_full,
'onClick="return installPkg(\''.$package_full.'\');"');
} else if ($compare == 1) {
$opt_img[] = sprintf(
'<a href="%s?command=upgrade&pkg=%s" %s>%s</a><br>',
$_SERVER["PHP_SELF"], $package,
'onClick="return installPkg(\''.$package.'\');"',
$images['install']);
$opt_text[] = sprintf(
'<a href="%s?command=upgrade&pkg=%s" class="green" %s>Upgrade package</a>',
$_SERVER["PHP_SELF"], $package,
'onClick="return installPkg(\''.$package.'\');"');
if (!in_array($package, $this->_no_delete_pkgs)) {
$opt_img[] = sprintf(
'<a href="%s?command=uninstall&pkg=%s" %s>%s</a>',
$_SERVER["PHP_SELF"], $package,
'onClick="return uninstallPkg(\''.$package.'\');"',
$images['uninstall']);
$opt_text[] = sprintf(
'<a href="%s?command=uninstall&pkg=%s" class="green" %s>Uninstall package</a>',
$_SERVER["PHP_SELF"], $package,
'onClick="return uninstallPkg(\''.$package.'\');"');
}
} else {
if (!in_array($package, $this->_no_delete_pkgs)) {
$opt_img[] = sprintf(
'<a href="%s?command=uninstall&pkg=%s" %s>%s</a>',
$_SERVER["PHP_SELF"], $package,
'onClick="return uninstallPkg(\''.$package.'\');"',
$images['uninstall']);
$opt_text[] = sprintf(
'<a href="%s?command=uninstall&pkg=%s" class="green" %s>Uninstall package</a>',
$_SERVER["PHP_SELF"], $package,
'onClick="return uninstallPkg(\''.$package.'\');"');
}
}
if (isset($opt_img[0]))
{
$tpl->setVariable('Opt_Img_1', $opt_img[0]);
$tpl->setVariable('Opt_Text_1', $opt_text[0]);
}
if (isset($opt_img[1]))
{
$tpl->setVariable('Opt_Img_2', $opt_img[1]);
$tpl->setVariable('Opt_Text_2', $opt_text[1]);
}
$tpl->setVariable('More_Title', 'More');
// More: Extended Package Information
$image = sprintf('<img src="%s?img=infoplus" border="0" alt="extra info">', $_SERVER["PHP_SELF"]);
if ($channel == 'pear.php.net' || $channel == 'pecl.php.net') {
$url = 'http://%s/package/%s/download/%s';
} else {
// the normal default
$url = 'http://%s/index.php?package=%s&release=%s';
}
$output = sprintf(
'<a href="'.$url.'" class="green" target="_new">%s Extended Package Information</a>',
$this->config->get('preferred_mirror', null, $channel),
$data['name'],
$data['stable'],
$image);
// More: Developer Documentation && Package Manual
if ($channel == 'pear.php.net') {
$output .= '<br />';
$image = sprintf('<img src="%s?img=manualplus" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="http://pear.php.net/package/%s/docs/latest" class="green" target="_new">%s pear.php.net Developer Documentation</a>',
$data['name'],
$image);
$output .= '<br />';
$image = sprintf('<img src="%s?img=manualplus" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="http://pear.php.net/manual/en/" class="green" target="_new">%s pear.php.net Package Manual </a>',
$image);
}
$tpl->setVariable('More_Data', $output);
$tpl->show();
return true;
}
/**
* Output given data in a horizontal generic table:
* table headers in the top row.
* Possibly prepend caption
*
* @var string $caption possible caption for table
* @var array $data array of data items
* @return true optimist etc
*/
function _outputGenericTableHorizontal($caption, $data) {
$tpl = $this->_initTemplate('generic_table_horizontal.tpl.html');
if (!is_null($caption) && $caption != '') {
$tpl->setVariable('Caption', $caption);
}
if (!is_array($data)) {
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Text', nl2br($data));
$tpl->parseCurrentBlock();
} else {
foreach ($data as $row) {
foreach ($row as $col) {
$tpl->setCurrentBlock('Row_item');
$tpl->setVariable('Text', nl2br($col));
$tpl->parseCurrentBlock();
}
$tpl->setCurrentBlock('Data_row');
$tpl->parseCurrentBlock();
}
}
$tpl->show();
return true;
}
/**
* Output given data in a vertical generic table:
* table headers in the left column.
* Possibly prepend caption
*
* @var string $caption possible caption for table
* @var array $data array of data items
* @return true optimist etc
*/
function _outputGenericTableVertical($caption, $data) {
$tpl = $this->_initTemplate('generic_table_vertical.tpl.html');
if (!is_null($caption) && $caption != '') {
$tpl->setVariable("Caption", $caption);
}
if (!is_array($data)) {
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Title', ' ');
$tpl->setVariable('Text', nl2br($data));
$tpl->parseCurrentBlock();
} else {
foreach($data as $row) {
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Title', $row[0]);
$tpl->setVariable('Text', nl2br($row[1]));
$tpl->parseCurrentBlock();
}
}
$tpl->show();
return true;
}
/**
* Output details of one channel
*
* @param array $data array containing all information about the channel
*
* @return boolean true (yep. i am an optimist)
*/
function _outputChannelInfo($data)
{
$data['main']['data'] = $this->htmlentities_recursive($data['main']['data']);
$channel = $data['main']['data']['server'][1];
$output = '';
if ($channel != '__uri') {
// add 'More' options
$image = sprintf('<img src="%s?img=package" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="%s?command=list-packages&chan=%s" class="green">%s List all packagenames of this channel</a>',
$_SERVER["PHP_SELF"],
$channel,
$image);
$output .= '<br />';
$image = sprintf('<img src="%s?img=category" border="0" alt="manual">', $_SERVER["PHP_SELF"]);
$output .= sprintf(
'<a href="%s?command=list-categories&chan=%s" class="green">%s List all categories of this channel</a>',
$_SERVER["PHP_SELF"],
$channel,
$image);
$output .= '<br />';
$output .= sprintf(
'<a href="%s?command=list-categories&chan=%s&opt=packages" class="green">%s List all categories, with packagenames, of this channel</a>',
$_SERVER["PHP_SELF"],
$channel,
$image);
$data['main']['data']['more'] = array('More', $output);
}
return $this->_outputGenericTableVertical($data['main']['caption'], $data['main']['data']);
}
/**
* Output all kinds of data depending on the command which called this method
*
* @param mixed $data datastructure containing the information to display
* @param string $command (optional) command from which this method was called
*
* @access public
*
* @return mixed highly depends on the command
*/
function outputData($data, $command = '_default')
{
switch ($command) {
case 'config-show':
$prompt = array();
$default = array();
foreach($data['data'] as $group) {
foreach($group as $row) {
$prompt[$row[1]] = $row[0];
$default[$row[1]] = $row[2];
}
}
$title = 'Configuration :: '.$GLOBALS['pear_user_config'];
$GLOBALS['_PEAR_Frontend_Web_Config'] =
$this->userDialog($command, $prompt, array(), $default, $title, 'config');
return true;
case 'list-files':
return $this->_outputListFiles($data);
case 'list-docs':
return $this->_outputListDocs($data);
case 'doc-show':
return $this->_outputDocShow($data);
case 'list-all':
return $this->_outputListAll($data);
case 'list-packages':
return $this->_outputListPackages($data);
case 'list-categories':
return $this->_outputListCategories($data);
case 'list-category':
return $this->_outputListCategory($data);
case 'list-upgrades':
return $this->_outputListUpgrades($data);
case 'list':
return $this->_outputList($data);
case 'list-channels':
return $this->_outputListChannels($data);
case 'search':
return $this->_outputListAll($data, false);
case 'remote-info':
return $this->_outputPackageRemoteInfo($data);
case 'package-info': // = 'info' command
return $this->_outputPackageInfo($data);
case 'channel-info':
return $this->_outputChannelInfo($data);
case 'login':
if ($_SERVER["REQUEST_METHOD"] != "POST")
$this->_data[$command] = $data;
return true;
case 'logout':
$this->displayError($data, 'Logout', 'logout');
break;
case 'install':
case 'upgrade':
case 'upgrade-all':
case 'uninstall':
case 'channel-delete':
case 'package':
case 'channel-discover':
case 'update-channels':
case 'channel-update':
if (is_array($data)) {
print($data['data'].'<br />');
} else {
print($data.'<br />');
}
break;
default:
if ($this->_installScript) {
$this->_savedOutput[] = $_SESSION['_PEAR_Frontend_Web_SavedOutput'][] = $data;
break;
}
if (!is_array($data)) {
// WARNING: channel "pear.php.net" has updated its protocols, use "channel-update pear.php.net" to update: auto-URL
if (preg_match('/use "channel-update ([\S]+)" to update$/', $data, $matches)) {
$channel = $matches[1];
$url = sprintf('<a href="%s?command=channel-update&chan=%s" class="green">channel-update %s</a>',
$_SERVER['PHP_SELF'],
$channel,
$channel);
$data = preg_replace('/channel-update '.$channel.'/',
$url,
$data);
}
// pearified/Role_Web has post-install scripts: bold
if (strpos($data, 'has post-install scripts:') !== false) {
$data = '<br /><i>'.$data.'</i>';
}
// Use "pear run-scripts pearified/Role_Web" to run
if (preg_match('/^Use "pear run-scripts ([\S]+)"$/', $data, $matches)) {
$pkg = $matches[1];
$url = sprintf('<a href="%s?command=run-scripts&pkg=%s" class="green">pear run-scripts %s</a>',
$_SERVER['PHP_SELF'],
$pkg,
$pkg);
$pkg = str_replace('/', '\/', $pkg);
$data = preg_replace('/pear run-scripts '.$pkg.'/',
$url,
$data);
$data = '<b>Attention !</b> '.$data.' !';
}
if (strpos($data, 'DO NOT RUN SCRIPTS FROM UNTRUSTED SOURCES') !== false) {
break;
}
// TODO: div magic, give it a color and a box etc.
print('<div>'.$data.'<div>');
}
}
return true;
}
/**
* Output a Table Of Channels:
* Table of contents like thing for all channels
* (using <a name= stuff
*/
function outputTableOfChannels()
{
$tpl = $this->_initTemplate('tableofchannels.tpl.html');
$tpl->setVariable('Caption', 'All available channels:');
$reg = $this->config->getRegistry();
$channels = $reg->getChannels();
foreach ($channels as $channel) {
if ($channel->getName() != '__uri') {
$tpl->setCurrentBlock('Data_row');
$tpl->setVariable('Channel', $channel->getName());
$tpl->parseCurrentBlock();
}
}
$tpl->show();
}
/**
* Output the 'upgrade-all' page
*/
function outputUpgradeAll()
{
$tpl = $this->_initTemplate('upgrade_all.tpl.html');
$tpl->setVariable('UpgradeAllURL', $_SERVER['PHP_SELF']);
$tpl->show();
}
/**
* Output the 'search' page
*/
function outputSearch()
{
$reg = $this->config->getRegistry();
$channels = $reg->getChannels();
$channel_select = array('all' => 'All channels');
foreach ($channels as $channel) {
if ($channel->getName() != '__uri') {
$channel_select[$channel->getName()] = $channel->getName();
}
}
// search-types to display
$arr = array(
'name' => array('title' => 'Search package by name (fast)',
'descr' => 'Package name'),
'description' => array('title' => 'Search package by name and description (slow)',
'descr' => 'Search:'),
);
foreach($arr as $type => $values) {
$tpl = $this->_initTemplate('search.tpl.html');
$tpl->setCurrentBlock('Search');
foreach($channel_select as $key => $value) {
$tpl->setCurrentBlock('Search_channel');
$tpl->setVariable('Key', $key);
$tpl->setVariable('Value', $value);
$tpl->parseCurrentBlock();
}
$tpl->setVariable('InstallerURL', $_SERVER['PHP_SELF']);
$tpl->setVariable('Search_type', $type);
$tpl->setVariable('Title', $values['title']);
$tpl->setVariable('Description', $values['descr']);
$tpl->parseCurrentBlock();
$tpl->show();
}
}
/**
* Start session: starts saving output temporary
*/
function startSession()
{
if ($this->_installScript) {
if (!isset($_SESSION['_PEAR_Frontend_Web_SavedOutput'])) {
$_SESSION['_PEAR_Frontend_Web_SavedOutput'] = array();
}
$this->_savedOutput = $_SESSION['_PEAR_Frontend_Web_SavedOutput'];
} else {
$this->_savedOutput = array();
}
}
/**
* End session: output all saved output
*/
function finishOutput($command, $redirectLink = false)
{
unset($_SESSION['_PEAR_Frontend_Web_SavedOutput']);
$tpl = $this->_initTemplate('info.tpl.html');
foreach($this->_savedOutput as $row) {
$tpl->setCurrentBlock('Infoloop');
$tpl->setVariable("Info", $row);
$tpl->parseCurrentBlock();
}
if ($redirectLink) {
$tpl->setCurrentBlock('Infoloop');
$tpl->setVariable("Info", '<a href="' . $redirectLink['link'] . '" class="green">' .
$redirectLink['text'] . '</a>');
$tpl->parseCurrentBlock();
}
$tpl->show();
}
/**
* Run postinstall scripts
*
* @param array An array of PEAR_Task_Postinstallscript objects (or related scripts)
* @param PEAR_PackageFile_v2
*/
function runPostinstallScripts(&$scripts, $pkg)
{
if (!isset($_SESSION['_PEAR_Frontend_Web_Scripts'])) {
$saves = array();
foreach ($scripts as $i => $task) {
$saves[$i] = (array) $task->_obj;
}
$_SESSION['_PEAR_Frontend_Web_Scripts'] = $saves;
$nonsession = true;
} else {
$nonsession = false;
}
foreach ($scripts as $i => $task) {
if (!isset($_SESSION['_PEAR_Frontend_Web_ScriptIndex'])) {
$_SESSION['_PEAR_Frontend_Web_ScriptIndex'] = $i;
}
if ($i != $_SESSION['_PEAR_Frontend_Web_ScriptIndex']) {
continue;
}
if (!$nonsession) {
// restore values from previous sessions to the install script
foreach ($_SESSION['_PEAR_Frontend_Web_Scripts'][$i] as $name => $val) {
if ($name{0} == '_') {
// only public variables will be restored
continue;
}
$scripts[$i]->_obj->$name = $val;
}
}
$this->_installScript = true;
$this->startSession();
$this->runInstallScript($scripts[$i]->_params, $scripts[$i]->_obj, $pkg);
$saves = $scripts;
foreach ($saves as $i => $task) {
$saves[$i] = (array) $task->_obj;
}
$_SESSION['_PEAR_Frontend_Web_Scripts'] = $saves;
unset($_SESSION['_PEAR_Frontend_Web_ScriptIndex']);
}
$this->_installScript = false;
unset($_SESSION['_PEAR_Frontend_Web_Scripts']);
$pkg_full = $pkg->getChannel().'/'.$pkg->getPackage();
$this->finishOutput($pkg_full . ' Install Script',
array('link' => $_SERVER['PHP_SELF'] .
'?command=info&pkg='.$pkg_full,
'text' => 'Click for ' .$pkg_full. ' Information'));
}
/**
* Instruct the runInstallScript method to skip a paramgroup that matches the
* id value passed in.
*
* This method is useful for dynamically configuring which sections of a post-install script
* will be run based on the user's setup, which is very useful for making flexible
* post-install scripts without losing the cross-Frontend ability to retrieve user input
* @param string
*/
function skipParamgroup($id)
{
$_SESSION['_PEAR_Frontend_Web_ScriptSkipSections'][$sectionName] = true;
}
/**
* @param array $xml contents of postinstallscript tag
* example: Array (
[paramgroup] => Array (
[id] => webSetup
[param] => Array (
[name] => webdirpath
[prompt] => Where should... ?
[default] => '/var/www/htdocs/webpear
[type] => string
)
)
)
* @param object $script post-installation script
* @param PEAR_PackageFile_v1|PEAR_PackageFile_v2 $pkg
* @param string $contents contents of the install script
*/
function runInstallScript($xml, &$script, &$pkg)
{
if (!isset($_SESSION['_PEAR_Frontend_Web_ScriptCompletedPhases'])) {
$_SESSION['_PEAR_Frontend_Web_ScriptCompletedPhases'] = array();
$_SESSION['_PEAR_Frontend_Web_ScriptSkipSections'] = array();
}
if (isset($_SESSION['_PEAR_Frontend_Web_ScriptObj'])) {
foreach ($_SESSION['_PEAR_Frontend_Web_ScriptObj'] as $name => $val) {
if ($name{0} == '_') {
// only public variables will be restored
continue;
}
$script->$name = $val;
}
} else {
$_SESSION['_PEAR_Frontend_Web_ScriptObj'] = (array) $script;
}
if (!is_array($xml) || !isset($xml['paramgroup'])) {
$script->run(array(), '_default');
} else {
if (!isset($xml['paramgroup'][0])) {
$xml['paramgroup'] = array($xml['paramgroup']);
}
foreach ($xml['paramgroup'] as $i => $group) {
if (isset($_SESSION['_PEAR_Frontend_Web_ScriptSkipSections'][$group['id']])) {
continue;
}
if (isset($_SESSION['_PEAR_Frontend_Web_ScriptSection'])) {
if ($i < $_SESSION['_PEAR_Frontend_Web_ScriptSection']) {
$lastgroup = $group;
continue;
}
}
if (isset($_SESSION['_PEAR_Frontend_Web_answers'])) {
$answers = $_SESSION['_PEAR_Frontend_Web_answers'];
}
if (isset($group['name'])) {
if (isset($answers)) {
if (isset($answers[$group['name']])) {
switch ($group['conditiontype']) {
case '=' :
if ($answers[$group['name']] != $group['value']) {
continue 2;
}
break;
case '!=' :
if ($answers[$group['name']] == $group['value']) {
continue 2;
}
break;
case 'preg_match' :
if (!@preg_match('/' . $group['value'] . '/',
$answers[$group['name']])) {
continue 2;
}
break;
default :
$this->_clearScriptSession();
return;
}
}
} else {
$this->_clearScriptSession();
return;
}
}
if (!isset($group['param'][0])) {
$group['param'] = array($group['param']);
}
$_SESSION['_PEAR_Frontend_Web_ScriptSection'] = $i;
if (!isset($answers)) {
$answers = array();
}
if (isset($group['param'])) {
if (method_exists($script, 'postProcessPrompts')) {
$prompts = $script->postProcessPrompts($group['param'], $group['name']);
if (!is_array($prompts) || count($prompts) != count($group['param'])) {
$this->outputData('postinstall', 'Error: post-install script did not ' .
'return proper post-processed prompts');
$prompts = $group['param'];
} else {
foreach ($prompts as $i => $var) {
if (!is_array($var) || !isset($var['prompt']) ||
!isset($var['name']) ||
($var['name'] != $group['param'][$i]['name']) ||
($var['type'] != $group['param'][$i]['type'])) {
$this->outputData('postinstall', 'Error: post-install script ' .
'modified the variables or prompts, severe security risk. ' .
'Will instead use the defaults from the package.xml');
$prompts = $group['param'];
}
}
}
$answers = array_merge($answers,
$this->confirmDialog($prompts,
$pkg->getChannel().'/'.$pkg->getPackage()));
} else {
$answers = array_merge($answers,
$this->confirmDialog($group['param'],
$pkg->getChannel().'/'.$pkg->getPackage()));
}
}
if ($answers) {
array_unshift($_SESSION['_PEAR_Frontend_Web_ScriptCompletedPhases'],
$group['id']);
if (!$script->run($answers, $group['id'])) {
$script->run($_SESSION['_PEAR_Frontend_Web_ScriptCompletedPhases'],
'_undoOnError');
$this->_clearScriptSession();
return;
}
} else {
$script->run(array(), '_undoOnError');
$this->_clearScriptSession();
return;
}
$lastgroup = $group;
foreach ($group['param'] as $param) {
// rename the current params to save for future tests
$answers[$group['id'] . '::' . $param['name']] = $answers[$param['name']];
unset($answers[$param['name']]);
}
// save the script's variables and user answers for the next round
$_SESSION['_PEAR_Frontend_Web_ScriptObj'] = (array) $script;
$_SESSION['_PEAR_Frontend_Web_answers'] = $answers;
$_SERVER['REQUEST_METHOD'] = '';
}
}
$this->_clearScriptSession();
}
function _clearScriptSession()
{
unset($_SESSION['_PEAR_Frontend_Web_ScriptObj']);
unset($_SESSION['_PEAR_Frontend_Web_answers']);
unset($_SESSION['_PEAR_Frontend_Web_ScriptSection']);
unset($_SESSION['_PEAR_Frontend_Web_ScriptCompletedPhases']);
unset($_SESSION['_PEAR_Frontend_Web_ScriptSkipSections']);
}
/**
* Ask for user input, confirm the answers and continue until the user is satisfied
*
* @param array an array of arrays, format array('name' => 'paramname', 'prompt' =>
* 'text to display', 'type' => 'string'[, default => 'default value'])
* @param string Package Name
* @return array|false
*/
function confirmDialog($params, $pkg)
{
$answers = array();
$prompts = $types = array();
foreach ($params as $param) {
$prompts[$param['name']] = $param['prompt'];
$types[$param['name']] = $param['type'];
if (isset($param['default'])) {
$answers[$param['name']] = $param['default'];
} else {
$answers[$param['name']] = '';
}
}
$attempt = 0;
do {
if ($attempt) {
$_SERVER['REQUEST_METHOD'] = '';
}
$title = !$attempt ? $pkg . ' Install Script Input' : 'Please fill in all values';
$answers = $this->userDialog('run-scripts', $prompts, $types, $answers, $title, '',
array('pkg' => $pkg));
if ($answers === false) {
return false;
}
$attempt++;
} while (count(array_filter($answers)) != count($prompts));
$_SERVER['REQUEST_METHOD'] = 'POST';
return $answers;
}
/**
* Useless function that needs to exists for Frontend::setFrontendObject()
* Reported in bug #10656
*/
function userConfirm($prompt, $default = 'yes')
{
trigger_error("PEAR_Frontend_Web::userConfirm not used", E_USER_ERROR);
}
/**
* Display a formular and return the given input (yes. needs to requests)
*
* @param string $command command from which this method was called
* @param array $prompts associative array. keys are the inputfieldnames
* and values are the description
* @param array $types (optional) array of inputfieldtypes (text, password,
* etc.) keys have to be the same like in $prompts
* @param array $defaults (optional) array of defaultvalues. again keys have
* to be the same like in $prompts
* @param string $title (optional) title of the page
* @param string $icon (optional) iconhandle for this page
* @param array $extra (optional) extra parameters to put in the form action
*
* @access public
*
* @return array input sended by the user
*/
function userDialog($command, $prompts, $types = array(), $defaults = array(), $title = '',
$icon = '', $extra = array())
{
// If this is an POST Request, we can return the userinput
if (isset($_GET["command"]) && $_GET["command"]==$command
&& $_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['cancel'])) {
return false;
}
$result = array();
foreach($prompts as $key => $prompt) {
$result[$key] = $_POST[$key];
}
return $result;
}
// If this is an Answer GET Request , we can return the userinput
if (isset($_GET["command"]) && $_GET["command"]==$command
&& isset($_GET["userDialogResult"]) && $_GET["userDialogResult"]=='get') {
$result = array();
foreach($prompts as $key => $prompt) {
$result[$key] = $_GET[$key];
}
return $result;
}
// Assign title and icon to some commands
if ($command == 'login') {
$title = 'Login';
}
$tpl = $this->_initTemplate('userDialog.tpl.html');
$tpl->setVariable("Command", $command);
$extrap = '';
if (count($extra)) {
$extrap = '&';
foreach ($extra as $name => $value) {
$extrap .= urlencode($name) . '=' . urlencode($value);
}
}
$tpl->setVariable("extra", $extrap);
if ($title != '') {
$tpl->setVariable('Caption', $title);
} else {
$tpl->setVariable('Caption', ucfirst($command));
}
if (is_array($prompts)) {
$maxlen = 0;
foreach($prompts as $key => $prompt) {
if (strlen($prompt) > $maxlen) {
$maxlen = strlen($prompt);
}
}
foreach($prompts as $key => $prompt) {
$tpl->setCurrentBlock("InputField");
$type = (isset($types[$key]) ? $types[$key] : 'text');
$default = (isset($defaults[$key]) ? $defaults[$key] : '');
$tpl->setVariable("prompt", $prompt);
$tpl->setVariable("name", $key);
$tpl->setVariable("default", $default);
$tpl->setVariable("type", $type);
if ($maxlen > 25) {
$tpl->setVariable("width", 'width="275"');
}
$tpl->parseCurrentBlock();
}
}
if ($command == 'run-scripts') {
$tpl->setVariable("cancel", '<input type="submit" value="Cancel" name="cancel">');
}
$tpl->show();
exit;
}
/**
* Write message to log
*
* @param string $text message which has to written to log
*
* @access public
*
* @return boolean true
*/
function log($text)
{
if ($text == '.') {
print($text);
} else {
// filter some log output:
// color some things, drop some others
$styled = false;
// color:error {Failed to download pear/MDB2_Schema within preferred state "stable", latest release is version 0.7.2, stability "beta", use "channel://pear.php.net/MDB2_Schema-0.7.2" to install}
// make hyperlink the 'channel://...' part
$pattern = 'Failed to download';
if (substr($text, 0, strlen($pattern)) == $pattern) {
// hyperlink
if (preg_match('/use "channel:\/\/([\S]+)" to install/', $text, $matches)) {
$pkg = $matches[1];
$url = sprintf('<a href="%s?command=upgrade&pkg=%s" onClick="return installPkg(\'%s\');" class="green">channel://%s</a>',
$_SERVER['PHP_SELF'],
urlencode($pkg),
$pkg,
$pkg);
$text = preg_replace('/channel:\/\/'.addcslashes($pkg, '/').'/',
$url,
$text);
}
// color
$text = '<div id="error">'.$text.'</div>';
$styled = true;
}
// color:warning {chiara/Chiara_Bugs requires package "chiara/Chiara_PEAR_Server" (version >= 0.18.4) || chiara/Chiara_Bugs requires package "channel://savant.pearified.com/Savant3" (version >= 3.0.0)}
// make hyperlink the 'ch/pkg || channel://ch/pkg' part
$pattern = ' requires package "';
if (!$styled && strpos($text, $pattern) !== false) {
// hyperlink
if (preg_match('/ package "([\S]+)" \(version /', $text, $matches)) {
$pkg = $matches[1];
if (substr($pkg, 0, strlen('channel://')) == 'channel://') {
$pkg = substr($pkg, strlen('channel://'));
}
$url = sprintf('<a href="%s?command=info&pkg=%s" class="green">%s</a>',
$_SERVER['PHP_SELF'],
urlencode($pkg),
$matches[1]);
$text = preg_replace('/'.addcslashes($matches[1], '/').'/',
$url,
$text);
}
// color
$text = '<div id="warning">'.$text.'</div>';
$styled = true;
}
// color:warning {Could not download from "http://pear.php.net/get/HTML_QuickForm-3.2.9.tgz", cannot download "pear/html_quickform" (could not open /home/tias/WASP/pear/cvs//temp/download/HTML_QuickForm-3.2.9.tgz for writing)}
$pattern = 'Could not download from';
if (substr($text, 0, strlen($pattern)) == $pattern) {
// color
$text = '<div id="warning">'.$text.'</div>';
$styled = true;
}
// color:error {Error: cannot download "pear/HTML_QuickForm"}
$pattern = 'Error:';
if (substr($text, 0, strlen($pattern)) == $pattern) {
// color
$text = '<div id="error">'.$text.'</div>';
$styled = true;
}
// and output...
if (!$styled) {
$text = '<div id="log">'.$text.'</div>';
}
print($text);
}
return true;
}
/**
* Totaly deprecated function
* Needed to install pearified's role_web : /
* Don't use this !
*/
function bold($text)
{
print('<b>'.$text.'</b><br />');
}
/**
* Sends the required file along with Headers and exits the script
*
* @param string $handle handle of the requested file
* @param string $group group of the requested file
*
* @access public
*
* @return null nothing, because script exits
*/
function outputFrontendFile($handle, $group)
{
$handles = array(
"css" => array(
"style" => "style.css",
),
"js" => array(
"package" => "package.js",
),
"image" => array(
"logout" => array(
"type" => "gif",
"file" => "logout.gif",
),
"login" => array(
"type" => "gif",
"file" => "login.gif",
),
"config" => array(
"type" => "gif",
"file" => "config.gif",
),
"pkglist" => array(
"type" => "png",
"file" => "pkglist.png",
),
"pkgsearch" => array(
"type" => "png",
"file" => "pkgsearch.png",
),
"package" => array(
"type" => "jpeg",
"file" => "package.jpg",
),
"category" => array(
"type" => "jpeg",
"file" => "category.jpg",
),
"install" => array(
"type" => "gif",
"file" => "install.gif",
),
"install_wait" => array(
"type" => "gif",
"file" => "install_wait.gif",
),
"install_ok" => array(
"type" => "gif",
"file" => "install_ok.gif",
),
"install_fail" => array(
"type" => "gif",
"file" => "install_fail.gif",
),
"uninstall" => array(
"type" => "gif",
"file" => "trash.gif",
),
"info" => array(
"type" => "gif",
"file" => "info.gif",
),
"infoplus" => array(
"type" => "gif",
"file" => "infoplus.gif",
),
"pear" => array(
"type" => "gif",
"file" => "pearsmall.gif",
),
"error" => array(
"type" => "gif",
"file" => "error.gif",
),
"manual" => array(
"type" => "gif",
"file" => "manual.gif",
),
"manualplus" => array(
"type" => "gif",
"file" => "manualplus.gif",
),
"download" => array(
"type" => "gif",
"file" => "download.gif",
),
),
);
$file = $handles[$group][$handle];
switch ($group) {
case 'css':
header("Content-Type: text/css");
readfile($this->config->get('data_dir').'/PEAR_Frontend_Web/data/'.$file);
exit;
case 'image':
$filename = $this->config->get('data_dir').'/PEAR_Frontend_Web/data/images/'.$file['file'];
header("Content-Type: image/".$file['type']);
header("Expires: ".gmdate("D, d M Y H:i:s \G\M\T", time() + 60*60*24*100));
header("Last-Modified: ".gmdate("D, d M Y H:i:s \G\M\T", filemtime($filename)));
header("Cache-Control: public");
header("Pragma: ");
readfile($filename);
exit;
case 'js':
header("Content-Type: text/javascript");
readfile($this->config->get('data_dir').'/PEAR_Frontend_Web/data/'.$file);
exit;
}
}
/*
* From DB::Pager. Removing Pager dependency.
* @private
*/
function __getData($from, $limit, $numrows, $maxpages = false)
{
if (empty($numrows) || ($numrows < 0)) {
return null;
}
$from = (empty($from)) ? 0 : $from;
if ($limit <= 0) {
return false;
}
// Total number of pages
$pages = ceil($numrows/$limit);
$data['numpages'] = $pages;
// first & last page
$data['firstpage'] = 1;
$data['lastpage'] = $pages;
// Build pages array
$data['pages'] = array();
for ($i=1; $i <= $pages; $i++) {
$offset = $limit * ($i-1);
$data['pages'][$i] = $offset;
// $from must point to one page
if ($from == $offset) {
// The current page we are
$data['current'] = $i;
}
}
if (!isset($data['current'])) {
return PEAR::raiseError (null, 'wrong "from" param', null,
null, null, 'DB_Error', true);
}
// Limit number of pages (Goole algorithm)
if ($maxpages) {
$radio = floor($maxpages/2);
$minpage = $data['current'] - $radio;
if ($minpage < 1) {
$minpage = 1;
}
$maxpage = $data['current'] + $radio - 1;
if ($maxpage > $data['numpages']) {
$maxpage = $data['numpages'];
}
foreach (range($minpage, $maxpage) as $page) {
$tmp[$page] = $data['pages'][$page];
}
$data['pages'] = $tmp;
$data['maxpages'] = $maxpages;
} else {
$data['maxpages'] = null;
}
// Prev link
$prev = $from - $limit;
$data['prev'] = ($prev >= 0) ? $prev : null;
// Next link
$next = $from + $limit;
$data['next'] = ($next < $numrows) ? $next : null;
// Results remaining in next page & Last row to fetch
if ($data['current'] == $pages) {
$data['remain'] = 0;
$data['to'] = $numrows;
} else {
if ($data['current'] == ($pages - 1)) {
$data['remain'] = $numrows - ($limit*($pages-1));
} else {
$data['remain'] = $limit;
}
$data['to'] = $data['current'] * $limit;
}
$data['numrows'] = $numrows;
$data['from'] = $from + 1;
$data['limit'] = $limit;
return $data;
}
// }}}
// {{{ outputBegin($command)
/**
* Start output, HTML header etc
*/
function outputBegin($command)
{
if (is_null($command)) {
// just the header
$tpl = $this->_initTemplate('header.inc.tpl.html');
} else {
$tpl = $this->_initTemplate('top.inc.tpl.html');
$tpl->setCurrentBlock('Search');
$tpl->parseCurrentBlock();
if (!$this->_isProtected()) {
$tpl->setCurrentBlock('NotProtected');
$tpl->setVariable('Filler', ' ');
$tpl->parseCurrentBlock();
}
}
// Initialise begin vars
if ($this->config->get('preferred_mirror') != $this->config->get('default_channel')) {
$mirror = ' (mirror ' .$this->config->get('preferred_mirror') . ')';
} else {
$mirror = '';
}
$tpl->setVariable('_default_channel', $this->config->get('default_channel') . $mirror);
$tpl->setVariable('ImgPEAR', $_SERVER['PHP_SELF'].'?img=pear');
$tpl->setVariable('Title', 'PEAR Package Manager, '.$command);
$tpl->setVariable('Headline', 'Webbased PEAR Package Manager on '.$_SERVER['SERVER_NAME']);
$tpl->setCurrentBlock();
$tpl->show();
// submenu's for list, list-upgrades and list-all
if ($command == 'list' ||
$command == 'list-upgrades' ||
$command == 'list-all' ||
$command == 'list-categories' ||
$command == 'list-category' ||
$command == 'list-packages') {
$tpl = $this->_initTemplate('package.submenu.tpl.html');
$menus = array(
'list' => 'list installed packages',
'list-upgrades' => 'list available upgrades',
'list-packages' => 'list all packagenames',
'list-categories' => 'list all categories',
);
$highlight_map = array(
'list' => 'list',
'list-upgrades' => 'list-upgrades',
'list-all' => 'list-categories',
'list-categories' => 'list-categories',
'list-category' => 'list-category',
'list-packages' => 'list-packages',
);
foreach ($menus as $name => $text) {
$tpl->setCurrentBlock('Submenu');
$tpl->setVariable("href", $_SERVER["PHP_SELF"].'?command='.$name);
$tpl->setVariable("text", $text);
if ($name == $highlight_map[$command]) {
$tpl->setVariable("class", 'red');
} else {
$tpl->setVariable("class", 'green');
}
$tpl->parseCurrentBlock();
}
$tpl->show();
}
}
// }}}
// {{{ outputEnd($command)
/**
* End output, HTML footer etc
*/
function outputEnd($command)
{
if ($command == 'list') {
// show 'install package' footer
$tpl = $this->_initTemplate('package.manually.tpl.html');
$tpl->show();
}
if (is_null($command)) {
// just the header
$tpl = $this->_initTemplate('footer.inc.tpl.html');
} else {
$tpl = $this->_initTemplate('bottom.inc.tpl.html');
}
$tpl->setVariable('Filler', '');
$tpl->show();
}
// }}}
/**
* Checks if this webfrontend is protected:
* - when the client sais so
* - when having .htaccess authentication
*
* @return boolean
*/
function _isProtected()
{
if (isset($GLOBALS['_PEAR_Frontend_Web_protected']) &&
$GLOBALS['_PEAR_Frontend_Web_protected'] === true) {
return true;
}
if (isset($_SERVER['PHP_AUTH_USER'])) {
return true;
}
if (isset($_SERVER['AUTH_TYPE']) && !empty($_SERVER['AUTH_TYPE'])) {
return true;
}
if (isset($_SERVER['PHP_AUTH_DIGEST']) && !empty($_SERVER['PHP_AUTH_DIGEST'])) {
return true;
}
return false;
}
/**
* Prepare packagename for HTML output:
* make it a link
*
* @param $package package name (evt 'chan/pkg')
* @param $channel channel name (when pkg not 'chan/pkg')
*/
function _prepPkgName($package, $channel=null)
{
if (is_null($channel)) {
$full = $package;
} else {
$full = $channel.'/'.$package;
}
return sprintf('<a href="%s?command=info&pkg=%s" class="blue">%s</a>',
$_SERVER['PHP_SELF'],
$full,
$package);
}
/**
* Prepare Icons (install/uninstall) for HTML output:
* make img and url
*
* @param $package package name
* @param $channel channel name
* @param $installed optional when we already know the package is installed
*/
function _prepIcons($package_name, $channel, $installed=false)
{
$reg = $this->config->getRegistry();
$package = $channel.'/'.$package_name;
if ($installed || $reg->packageExists($package_name, $channel)) {
if (in_array($package, $this->_no_delete_pkgs)) {
// don't allow to uninstall
$out = ' ';
} else {
$img = sprintf('<img src="%s?img=uninstall" width="18" height="17" border="0" alt="uninstall">', $_SERVER["PHP_SELF"]);
$url = sprintf('%s?command=uninstall&pkg=%s', $_SERVER["PHP_SELF"], $package);
$out = sprintf('<a href="%s" onClick="return uninstallPkg(\'%s\');" id="%s">%s</a>', $url, $package, $package.'_href', $img);
}
} elseif (!$installed) {
$img = sprintf('<img src="%s?img=install" width="13" height="13" border="0" alt="install">', $_SERVER["PHP_SELF"]);
$url = sprintf('%s?command=install&pkg=%s', $_SERVER["PHP_SELF"], $package);
$out = sprintf('<a href="%s" onClick="return installPkg(\'%s\');" id="%s">%s</a>', $url, $package, $package.'_href', $img);
}
return $out;
}
/**
* apply 'htmlentities' to every value of the array
* array_walk_recursive($array, 'htmlentities') in PHP5
*/
function htmlentities_recursive($data) {
foreach($data as $key => $value) {
if (is_array($value)) {
$data[$key] = $this->htmlentities_recursive($value);
} else {
$data[$key] = htmlentities($value);
}
}
return $data;
}
}
?>
| lgpl-3.0 |
NovanMK2/UnrealLibNoise | Documentation/html/_cylinders_8h.js | 135 | var _cylinders_8h =
[
[ "DEFAULT_CYLINDERS_FREQUENCY", "group__generatormodules.html#ga21cecd2175693791092566a3974d6c69", null ]
]; | lgpl-3.0 |
sdruix/AutomaticParallelization | tests/06_phases_openmp.dg/nanos4/cxx/old_udr/success_udr_08.cpp | 1679 | /*--------------------------------------------------------------------
(C) Copyright 2006-2011 Barcelona Supercomputing Center
Centro Nacional de Supercomputacion
This file is part of Mercurium C/C++ source-to-source compiler.
See AUTHORS file in the top level directory for information
regarding developers and contributors.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 3 of the License, or (at your option) any later version.
Mercurium C/C++ source-to-source compiler is distributed in the hope
that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public
License along with Mercurium C/C++ source-to-source compiler; if
not, write to the Free Software Foundation, Inc., 675 Mass Ave,
Cambridge, MA 02139, USA.
--------------------------------------------------------------------*/
/*
<testinfo>
test_generator=config/mercurium-nanos4
test_CXXFLAGS=--variable=new_udr:0
</testinfo>
*/
struct my_int
{
int _n;
my_int() : _n ( 0 ) { }
my_int(int n) : _n(n) { }
};
void fun(const my_int&, my_int*);
#pragma omp declare reduction(fun:my_int) identity(constructor) order(right)
void g()
{
my_int s;
#pragma omp parallel for reduction(fun : s)
for (int i = 0; i < 100; i++)
{
my_int k(i);
fun(i, &s);
}
}
| lgpl-3.0 |
Allors/allors1 | Base/Domain/Custom/General/OrderObjectStates.cs | 2399 | //-------------------------------------------------------------------------------------------------
// <copyright file="OrderObjectStates.cs" company="Allors bvba">
// Copyright 2002-2016 Allors bvba.
//
// Dual Licensed under
// a) the General Public Licence v3 (GPL)
// b) the Allors License
//
// The GPL License is included in the file gpl.txt.
// The Allors License is an addendum to your contract.
//
// Allors Applications is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// For more information visit http://www.allors.com/legal
// </copyright>
// <summary>Defines the HomeAddress type.</summary>
//-------------------------------------------------------------------------------------------------
namespace Allors.Domain
{
using System;
public partial class OrderObjectStates
{
private static readonly Guid InitialId = new Guid("173EF3AF-B5AC-4610-8AC1-916D2C09C1D1");
private static readonly Guid ConfirmedId = new Guid("BD2FF235-301A-445A-B794-5D76B86006B3");
private static readonly Guid ClosedId = new Guid("0750D8B3-3B10-465F-BBC0-81D12F40A3DF");
private static readonly Guid CancelledId = new Guid("F72CEBEE-D12C-4321-83A3-77019A7B8C76");
private UniquelyIdentifiableCache<OrderObjectState> cache;
public Cache<Guid, OrderObjectState> Cache => this.cache ?? (this.cache = new UniquelyIdentifiableCache<OrderObjectState>(this.Session));
public OrderObjectState Initial => this.Cache[InitialId];
public OrderObjectState Confirmed => this.Cache[ConfirmedId];
public OrderObjectState Closed => this.Cache[ClosedId];
public OrderObjectState Cancelled => this.Cache[CancelledId];
protected override void BaseSetup(Setup config)
{
new OrderObjectStateBuilder(this.Session).WithUniqueId(InitialId).WithName("Initial").Build();
new OrderObjectStateBuilder(this.Session).WithUniqueId(ConfirmedId).WithName("Confirmed").Build();
new OrderObjectStateBuilder(this.Session).WithUniqueId(ClosedId).WithName("Closed").Build();
new OrderObjectStateBuilder(this.Session).WithUniqueId(CancelledId).WithName("Cancelled").Build();
}
}
} | lgpl-3.0 |
fa35/another-webshop | impl/admin/article/delete.php | 995 | <?php
require_once "../../classes/Utils.class.php";
$error = "";
$title = "";
$id = 0;
$utils = new Utils();
if (!$utils->isAdmin()) {
header("Location: ../../index.php");
}
require_once("../../header.inc.php");
if (isset($_POST['submit-delete'])) {
$id = (integer)$_POST["id"];
if ($utils->deleteArticle($id)) {
header("Location: administration.php");
} else {
$error = "Artikel konnte nicht gelöscht werden.";
}
}
if (isset($_POST['post-delete'])) {
$id = (integer)$_POST["id"];
$title = $_POST["title"];
}
?>
<h1>Artikel löschen</h1>
Möchten Sie die Artikel <?php echo $title . " wirklich löschen?"; ?>
<form action="delete.php" method="post">
<input type="hidden" name="id" value="<?php echo $id; ?>"/>
<input type="submit" value="Artikel löschen" name="submit-delete"/>
</form>
<?php
require_once("../../footer.inc.php");
if ($error != "") {
echo "<script>alert(\"" . $error . "\");</script>";
}
?> | lgpl-3.0 |
cfscosta/fenix | src/main/java/org/fenixedu/academic/ui/renderers/providers/executionDegree/DegreesToCreateRegistration.java | 1916 | /**
* Copyright © 2002 Instituto Superior Técnico
*
* This file is part of FenixEdu Academic.
*
* FenixEdu Academic is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* FenixEdu Academic is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>.
*/
package org.fenixedu.academic.ui.renderers.providers.executionDegree;
import java.util.stream.Collectors;
import org.fenixedu.academic.domain.Degree;
import org.fenixedu.academic.domain.accessControl.academicAdministration.AcademicAccessRule;
import org.fenixedu.academic.domain.accessControl.academicAdministration.AcademicOperationType;
import org.fenixedu.bennu.core.security.Authenticate;
import pt.ist.fenixWebFramework.rendererExtensions.converters.DomainObjectKeyConverter;
import pt.ist.fenixWebFramework.renderers.DataProvider;
import pt.ist.fenixWebFramework.renderers.components.converters.Converter;
public class DegreesToCreateRegistration implements DataProvider {
@Override
public Object provide(Object source, Object currentValue) {
return AcademicAccessRule
.getDegreesAccessibleToFunction(AcademicOperationType.CREATE_REGISTRATION, Authenticate.getUser())
.sorted(Degree.COMPARATOR_BY_DEGREE_TYPE_AND_NAME_AND_ID).collect(Collectors.toSet());
}
@Override
public Converter getConverter() {
return new DomainObjectKeyConverter();
}
}
| lgpl-3.0 |
Shockah/Custom-Hearthstone | Engine/src/pl/shockah/hs/events/EventManager.java | 2101 | package pl.shockah.hs.events;
import java.util.ArrayList;
import java.util.List;
import pl.shockah.Box;
import pl.shockah.func.Func1;
import pl.shockah.hs.Board;
import pl.shockah.hs.Player;
import pl.shockah.hs.cards.Card;
import pl.shockah.hs.units.MinionUnit;
import pl.shockah.hs.units.Unit;
public class EventManager {
public static final EventHandler defaultHandler = new EventHandler();
public static <A extends Enum<A>, B> A handleEnum(List<B> list, Func1<B, A> f) {
A finalResult = null;
for (B b : list) {
A result = f.f(b);
if (finalResult == null || result.ordinal() > finalResult.ordinal())
finalResult = result;
}
return finalResult;
}
public final Board board;
public final List<EventHandler> handlers = new ArrayList<>();
public EventManager(Board board) {
this.board = board;
handlers.add(defaultHandler);
}
public CardPlayedAction preCardPlayed(Player player, Card card) {
return handleEnum(handlers, (handler) -> handler.preCardPlayed(player, card));
}
public void postCardPlayed(Player player, Card card) {
for (EventHandler handler : handlers)
handler.postCardPlayed(player, card);
}
public MinionSummonedAction preMinionSummoned(Player player, MinionUnit minion) {
return handleEnum(handlers, (handler) -> handler.preMinionSummoned(player, minion));
}
public void postMinionSummoned(Player player, MinionUnit minion) {
for (EventHandler handler : handlers)
handler.postMinionSummoned(player, minion);
}
public void onResolveMinionSummonEffects(MinionUnit minion) {
for (EventHandler handler : handlers)
handler.onResolveMinionSummonEffects(minion);
}
public void onFindAttackTargets(Unit source, List<Unit> units) {
for (EventHandler handler : handlers)
handler.onFindAttackTargets(source, units);
}
public UnitAttackAction preUnitAttack(Unit source, Unit target) {
return handleEnum(handlers, (handler) -> handler.preUnitAttack(source, target));
}
public void preUnitDamaged(Unit unit, Box<Integer> damage) {
for (EventHandler handler : handlers)
handler.preUnitDamaged(unit, damage);
}
} | lgpl-3.0 |
arcualberta/Catfish | Catfish/Models/Blocks/TileGrid/TileGrid.cs | 1799 | using Catfish.Core.Models;
using Catfish.Models.Fields;
using Piranha;
using Piranha.Extend;
using Piranha.Extend.Fields;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Catfish.Models.Blocks.TileGrid
{
[BlockType(Name = "Tile Grid", Category = "Content", Component = "tile-grid", Icon = "fas fa-th")]
public class TileGrid : Block, ICatfishBlock
{
public void RegisterBlock() => App.Blocks.Register<TileGrid>();
// public ICollection<Tile> Tiles { get; set; } = new List<Tile>();
[Field(Title = "Keywords", Placeholder = "Please list keywords separated by a comma")]
public TextField KeywordList { get; set; }
public CatfishSelectList<Collection> Collections { get; set; }
public TextField SelectedCollection { get; set; }
public CatfishSelectList<ItemTemplate> ItemTemplates { get; set; }
public TextField SelectedItemTemplate { get; set; }
[Field(Title = "Css class for the Block")]
public TextField BlockCss { get; set; }
[Field(Title = "Css class for each Tile")]
public TextField TileCss { get; set; }
public TextField SelectedMapTitleId { get; set; }
public TextField SelectedMapSubtitleId { get; set; }
public TextField SelectedMapContentId { get; set; }
public TextField SelectedMapThumbnailId { get; set; }
public TextField DetailedViewUrl { get; set; }
public TextField KeywordSourceId { get; set; }
public TextField ClassificationMetadataSetId { get; set; }
public string GetKeywords()
{
if (KeywordList != null)
{
return KeywordList.Value;
}
return "";
}
}
}
| lgpl-3.0 |