code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
cask 'feeder' do
version '3.6.8'
sha256 '4399609c1b04b1b92aa51bf9c240fc7dfec49e534eae014dbe750e7c7bbdfd2d'
url "https://reinventedsoftware.com/feeder/downloads/Feeder_#{version}.dmg"
appcast "https://reinventedsoftware.com/feeder/downloads/Feeder#{version.major}.xml"
name 'Feeder'
homepage 'https://reinventedsoftware.com/feeder/'
app "Feeder #{version.major}.app"
end
|
Java
|
{-# LANGUAGE TemplateHaskell, QuasiQuotes, OverloadedStrings #-}
module Handler.Root where
import Foundation
-- This is a handler function for the GET request method on the RootR
-- resource pattern. All of your resource patterns are defined in
-- config/routes
--
-- The majority of the code you will write in Yesod lives in these handler
-- functions. You can spread them across multiple files if you are so
-- inclined, or create a single monolithic file.
getRootR :: Handler RepHtml
getRootR = do
defaultLayout $ do
h2id <- lift newIdent
setTitle "TierList homepage"
$(widgetFile "homepage")
|
Java
|
<?php
/**
* MtMail - e-mail module for Zend Framework
*
* @link http://github.com/mtymek/MtMail
* @copyright Copyright (c) 2013-2017 Mateusz Tymek
* @license BSD 2-Clause
*/
namespace MtMail\Factory;
use Interop\Container\ContainerInterface;
use MtMail\ComposerPlugin\DefaultHeaders;
class DefaultHeadersPluginFactory
{
public function __invoke(ContainerInterface $serviceLocator)
{
if (!method_exists($serviceLocator, 'configure')) {
$serviceLocator = $serviceLocator->getServiceLocator();
}
$config = $serviceLocator->get('Configuration');
$plugin = new DefaultHeaders();
if (isset($config['mt_mail']['default_headers'])) {
$plugin->setHeaders($config['mt_mail']['default_headers']);
}
return $plugin;
}
}
|
Java
|
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
Inherits System.Windows.Forms.Form
'Form overrides dispose to clean up the component list.
<System.Diagnostics.DebuggerNonUserCode()> _
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
Try
If disposing AndAlso components IsNot Nothing Then
components.Dispose()
End If
Finally
MyBase.Dispose(disposing)
End Try
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
<System.Diagnostics.DebuggerStepThrough()> _
Private Sub InitializeComponent()
Me.Button1 = New System.Windows.Forms.Button()
Me.DataGridView1 = New System.Windows.Forms.DataGridView()
Me.Table1TableAdapter1 = New WindowsApplication1.Database1DataSetTableAdapters.Table1TableAdapter()
CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).BeginInit()
Me.SuspendLayout()
'
'Button1
'
Me.Button1.Location = New System.Drawing.Point(52, 218)
Me.Button1.Name = "Button1"
Me.Button1.Size = New System.Drawing.Size(75, 23)
Me.Button1.TabIndex = 1
Me.Button1.Text = "Button1"
Me.Button1.UseVisualStyleBackColor = True
'
'DataGridView1
'
Me.DataGridView1.AllowUserToOrderColumns = True
Me.DataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
Me.DataGridView1.Location = New System.Drawing.Point(52, 25)
Me.DataGridView1.Name = "DataGridView1"
Me.DataGridView1.Size = New System.Drawing.Size(417, 162)
Me.DataGridView1.TabIndex = 2
'
'Table1TableAdapter1
'
Me.Table1TableAdapter1.ClearBeforeFill = True
'
'Form1
'
Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
Me.ClientSize = New System.Drawing.Size(522, 344)
Me.Controls.Add(Me.DataGridView1)
Me.Controls.Add(Me.Button1)
Me.Name = "Form1"
Me.Text = "Form1"
CType(Me.DataGridView1, System.ComponentModel.ISupportInitialize).EndInit()
Me.ResumeLayout(False)
End Sub
Friend WithEvents Button1 As System.Windows.Forms.Button
Friend WithEvents DataGridView1 As System.Windows.Forms.DataGridView
Friend WithEvents Table1TableAdapter1 As WindowsApplication1.Database1DataSetTableAdapters.Table1TableAdapter
End Class
|
Java
|
// This file was procedurally generated from the following sources:
// - src/async-generators/yield-as-identifier-reference-escaped.case
// - src/async-generators/syntax/async-class-expr-method.template
/*---
description: yield is a reserved keyword within generator function bodies and may not be used as an identifier reference. (Async generator method as a ClassExpression element)
esid: prod-AsyncGeneratorMethod
features: [async-iteration]
flags: [generated]
negative:
phase: parse
type: SyntaxError
info: |
ClassElement :
MethodDefinition
MethodDefinition :
AsyncGeneratorMethod
Async Generator Function Definitions
AsyncGeneratorMethod :
async [no LineTerminator here] * PropertyName ( UniqueFormalParameters ) { AsyncGeneratorBody }
IdentifierReference : Identifier
It is a Syntax Error if this production has a [Yield] parameter and
StringValue of Identifier is "yield".
---*/
throw "Test262: This statement should not be evaluated.";
var C = class { async *gen() {
void yi\u0065ld;
}};
|
Java
|
/*****************************************************************************************
*
* Portable classes for the HSFC
* These are (semi-)portable representations of a state that can be serialised
* and loaded between any HSFC instances loaded with the same GDL (we hope!!!).
*
*****************************************************************************************/
#ifndef HSFC_PORTABLE_H
#define HSFC_PORTABLE_H
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <memory>
#include <iterator>
#include <algorithm>
#include <stdint.h>
#include <boost/assert.hpp>
#include <boost/exception/all.hpp>
#include <boost/scoped_ptr.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/serialization/serialization.hpp>
#include <boost/serialization/utility.hpp>
#include <boost/serialization/vector.hpp>
#include <boost/serialization/map.hpp>
#include <boost/serialization/set.hpp>
#include <boost/serialization/shared_ptr.hpp>
#include <boost/serialization/access.hpp>
#include <hsfc/hsfcexception.h>
#include <hsfc/impl/fwd_decl.h>
namespace HSFC
{
/*****************************************************************************************
* PortableState.
*****************************************************************************************/
class PortableState
{
public:
PortableState();
PortableState(const State& state);
PortableState(const PortableState& other);
PortableState& operator=(const PortableState& other);
bool operator==(const PortableState& other) const;
bool operator!=(const PortableState& other) const;
bool operator<(const PortableState& other) const;
std::size_t hash_value() const;
private:
friend class State;
friend class boost::serialization::access;
int round_;
int currentstep_;
std::set<std::pair<int,int> > relationset_;
template<typename Archive>
void serialize(Archive& ar, const unsigned int version);
};
std::size_t hash_value(const PortableState& ps); /* Can be used as a key in boost::unordered_* */
template<typename Archive>
void PortableState::serialize(Archive& ar, const unsigned int version)
{
ar & round_;
ar & currentstep_;
ar & relationset_;
}
/*****************************************************************************************
* PortablePlayer
*****************************************************************************************/
class PortablePlayer
{
public:
PortablePlayer();
PortablePlayer(const Player& player);
PortablePlayer(const PortablePlayer& other);
PortablePlayer& operator=(const PortablePlayer& other);
bool operator==(const PortablePlayer& other) const;
bool operator!=(const PortablePlayer& other) const;
bool operator<(const PortablePlayer& other) const;
std::size_t hash_value() const;
private:
friend class Player;
friend class boost::serialization::access;
/* PortablePlayer default constructor is now public!
// NOTE: 1) Need to make PortablePlayerMove and PortablePlayerGoal friends
// to allow the deserialization of these objects to work.
// This is ugly and does in theory allow empty Portable objects to
// be created by a user (by way of the friend pair).
// 2) cannot be a friend of a typedef. I think this has changed in C++11.
friend class std::pair<PortablePlayer, unsigned int>;
friend class std::pair<const PortablePlayer, unsigned int>;
friend class std::pair<PortablePlayer, uint64_t>;
friend class std::pair<const PortablePlayer, uint64_t>;
friend class std::pair<PortablePlayer, PortableMove>;
friend class std::pair<const PortablePlayer, PortableMove>;
friend class std::pair<PortablePlayer, const PortableMove>;
friend class std::pair<const PortablePlayer, const PortableMove>;
*/
template<typename Archive>
void serialize(Archive& ar, const unsigned int version);
unsigned int roleid_;
};
template<typename Archive>
void PortablePlayer::serialize(Archive& ar, const unsigned int version)
{
ar & roleid_;
}
std::size_t hash_value(const PortablePlayer& pp); /* Can be used as a key in boost::unordered_* */
/*****************************************************************************************
* PortableMove
*****************************************************************************************/
class PortableMove
{
public:
PortableMove();
PortableMove(const Move& move);
PortableMove(const PortableMove& other);
PortableMove& operator=(const PortableMove& other);
bool operator==(const PortableMove& other) const;
bool operator!=(const PortableMove& other) const;
bool operator<(const PortableMove& other) const;
std::size_t hash_value() const;
private:
friend class Move;
friend class boost::serialization::access;
/*
PortableMove default constructor is now public!
// NOTE: 1) Need to make PortablePlayerMove a friend to allow the deserialization
// of these objects to work. This is ugly and does in theory allow empty
// Portable objects to be created by a user (by way of the friend pair).
// 2) cannot be a friend of a typedef. I think this has changed in C++11.
friend class std::pair<PortablePlayer, PortableMove>;
friend class std::pair<const PortablePlayer, PortableMove>;
friend class std::pair<PortablePlayer, const PortableMove>;
friend class std::pair<const PortablePlayer, const PortableMove>;
*/
template<typename Archive>
void serialize(Archive& ar, const unsigned int version);
int RoleIndex_;
std::string Text_;
int RelationIndex_;
int ID_;
};
template<typename Archive>
void PortableMove::serialize(Archive& ar, const unsigned int version)
{
ar & RoleIndex_;
ar & Text_;
ar & RelationIndex_;
ar & ID_;
}
std::size_t hash_value(const PortableMove& pm); /* Can be used as a key in boost::unordered_* */
/*****************************************************************************************
* Support functor to convert to/from collection of PortableX's. Here is an example
* of how to use it:
*
* Game game(<some_game>);
* std::vector<PortablePlayerMove> ppmoves;
*
* .... // Assign to ppmoves;
*
* std::vector<PlayerMove> pmoves;
* std::transform(ppmoves.begin(), ppmoves.end(),
* std::back_inserter(pmoves), FromPortable(game));
*
* To convert in the opposite direction use ToPortable(). This is only strictly necessary
* necessary for PortableJointMove and PortableJointGoal conversion, since in the other
* cases the std::copy could be used. However, these other functions have been defined for
* conversion to all portable types for simplicity/completeness.
*
* std::transform(pmoves.begin(), pmoves.end(), std::back_inserter(ppmoves), ToPortable());
*
* NOTE: I think the value_type for PortableJointMove is:
* std::pair<const PortablePlayer,PortableMove> This seems to be making conversion for
* PortablePlayerMove (which is std::pair<PortablePlayer,PortableMove>) ambiguous. So
* explicitly add conversions for this. Doing the same for PortableJointGoal as well.
*
*****************************************************************************************/
struct FromPortable
{
public:
FromPortable(Game& game);
JointMove operator()(const PortableJointMove& pjm);
JointGoal operator()(const PortableJointGoal& pjg);
PlayerMove operator()(const PortablePlayerMove& ppm);
PlayerMove operator()(const std::pair<const PortablePlayer, PortableMove>& ppm);
PlayerGoal operator()(const PortablePlayerGoal& ppg);
PlayerGoal operator()(const std::pair<const PortablePlayer, unsigned int>& ppg);
Player operator()(const PortablePlayer& pp);
Move operator()(const PortableMove& pm);
State operator()(const PortableState& ps);
private:
Game& game_;
};
/*****************************************************************************************
* Inlined implementation of FromPortable.
*****************************************************************************************/
inline FromPortable::FromPortable(Game& game) : game_(game) { }
inline JointMove FromPortable::operator()(const PortableJointMove& pjm)
{
JointMove jm;
std::transform(pjm.begin(), pjm.end(), std::inserter(jm,jm.begin()),*this);
return jm;
}
inline JointGoal FromPortable::operator()(const PortableJointGoal& pjg)
{
JointGoal jg;
std::transform(pjg.begin(), pjg.end(), std::inserter(jg,jg.begin()),*this);
return jg;
}
inline PlayerMove FromPortable::operator()(const PortablePlayerMove& ppm)
{ return PlayerMove(Player(game_, ppm.first), Move(game_,ppm.second)); }
inline PlayerMove FromPortable::operator()(const std::pair<const PortablePlayer, PortableMove>& ppm)
{ return PlayerMove(Player(game_, ppm.first), Move(game_,ppm.second)); }
inline PlayerGoal FromPortable::operator()(const PortablePlayerGoal& ppg)
{ return PlayerGoal(Player(game_, ppg.first), ppg.second); }
inline PlayerGoal FromPortable::operator()(const std::pair<const PortablePlayer, unsigned int>& ppg)
{ return PlayerGoal(Player(game_, ppg.first), ppg.second); }
inline Player FromPortable::operator()(const PortablePlayer& pp)
{ return Player(game_, pp); }
inline Move FromPortable::operator()(const PortableMove& pm)
{ return Move(game_, pm); }
inline State FromPortable::operator()(const PortableState& ps)
{ return State(game_, ps); }
/*****************************************************************************************
* ToPortable. See explanation of FromPortable.
*****************************************************************************************/
struct ToPortable
{
public:
ToPortable();
ToPortable(Game& game);
PortableJointMove operator()(const JointMove& jm);
PortableJointGoal operator()(const JointGoal& jg);
PortablePlayerMove operator()(const PlayerMove& ppm);
PortablePlayerGoal operator()(const PlayerGoal& ppg);
PortablePlayer operator()(const Player& pp);
PortableMove operator()(const Move& pm);
PortableState operator()(const State& ps);
};
/*****************************************************************************************
* inlined implementation of ToPortable.
*****************************************************************************************/
inline ToPortable::ToPortable(){ }
inline ToPortable::ToPortable(Game& game){ }
inline PortableJointMove ToPortable::operator()(const JointMove& jm)
{
PortableJointMove pjm;
std::copy(jm.begin(), jm.end(), std::inserter(pjm,pjm.begin()));
return pjm;
}
inline PortableJointGoal ToPortable::operator()(const JointGoal& jg)
{
PortableJointGoal pjg;
std::copy(jg.begin(), jg.end(), std::inserter(pjg,pjg.begin()));
return pjg;
}
inline PortablePlayerMove ToPortable::operator()(const PlayerMove& pm)
{ return PortablePlayerMove(pm); }
inline PortablePlayerGoal ToPortable::operator()(const PlayerGoal& pg)
{ return PortablePlayerGoal(pg); }
inline PortablePlayer ToPortable::operator()(const Player& p)
{ return PortablePlayer(p); }
inline PortableMove ToPortable::operator()(const Move& m)
{ return PortableMove(m); }
inline PortableState ToPortable::operator()(const State& s)
{ return PortableState(s); }
}; /* namespace HSFC */
#endif // HSFC_PORTABLE_H
|
Java
|
#!/usr/bin/env python
#Copyright (c) <2015>, <Jaakko Leppakangas>
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without
#modification, are permitted provided that the following conditions are met:
#
#1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#2. 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.
#
#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.
#
#The views and conclusions contained in the software and documentation are those
#of the authors and should not be interpreted as representing official policies,
#either expressed or implied, of the FreeBSD Project.
'''
Created on Dec 16, 2014
@author: Jaakko Leppakangas
'''
import sys
from PyQt4 import QtGui
from ui.preprocessDialog import PreprocessDialog
def main():
app = QtGui.QApplication(sys.argv)
window=PreprocessDialog()
window.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
|
Java
|
# Customize below path information
#TET_INSTALL_PATH=/scratchbox/TETware
CURRENT_USER=`echo $HOME`
TET_INSTALL_PATH=$CURRENT_USER/sbs/TETware
# temporary fix for SPRC
if [ "$TET_ROOT_DIR" != "" ]; then
TET_INSTALL_PATH=$TET_ROOT_DIR
fi
TET_SIMUL_PATH=$TET_INSTALL_PATH/tetware-simulator
TET_TARGET_PATH=$TET_INSTALL_PATH/tetware-target
TET_MOUNTED_PATH=/mnt/nfs/sbs/TETware/tetware-target
#TET_MOUNTED_PATH=/opt/home/root/tmp/sbs/TETware/tetware-target
#MACHINE=`echo $SBOX_UNAME_MACHINE`
MACHINE=`echo $DEB_BUILD_ARCH_ABI`
if [ $MACHINE = "gnu" ] # SBS i386
then
export ARCH=simulator
export TET_ROOT=$TET_SIMUL_PATH
elif [ $MACHINE = "gnueabi" ] # SBS ARM
then
export ARCH=target
export TET_ROOT=$TET_TARGET_PATH
else
export ARCH=target
export TET_ROOT=$TET_MOUNTED_PATH
fi
export PATH=$TET_ROOT/bin:$PATH
export LD_LIBRARY_PATH=$TET_ROOT/lib/tet3:$LD_LIBRARY_PATH
set $(pwd)
export TET_SUITE_ROOT=$1
set $(date +%y%m%d_%H%M%S)
FILE_NAME_EXTENSION=$1
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0_22) on Tue Mar 08 15:19:00 PST 2011 -->
<TITLE>
Uses of Class com.perforce.p4java.ant.tasks.ServerTask.GlobalOption (P4Ant)
</TITLE>
<META NAME="date" CONTENT="2011-03-08">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.perforce.p4java.ant.tasks.ServerTask.GlobalOption (P4Ant)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/perforce/p4java/ant/tasks//class-useServerTask.GlobalOption.html" target="_top"><B>FRAMES</B></A>
<A HREF="ServerTask.GlobalOption.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>com.perforce.p4java.ant.tasks.ServerTask.GlobalOption</B></H2>
</CENTER>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Packages that use <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks">ServerTask.GlobalOption</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><A HREF="#com.perforce.p4java.ant.tasks"><B>com.perforce.p4java.ant.tasks</B></A></TD>
<TD>
The Perforce tasks implement Perforce commands using the Perforce Java API. </TD>
</TR>
</TABLE>
<P>
<A NAME="com.perforce.p4java.ant.tasks"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
Uses of <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks">ServerTask.GlobalOption</A> in <A HREF="../../../../../../com/perforce/p4java/ant/tasks/package-summary.html">com.perforce.p4java.ant.tasks</A></FONT></TH>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Fields in <A HREF="../../../../../../com/perforce/p4java/ant/tasks/package-summary.html">com.perforce.p4java.ant.tasks</A> with type parameters of type <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks">ServerTask.GlobalOption</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE>protected java.util.List<<A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks">ServerTask.GlobalOption</A>></CODE></FONT></TD>
<TD><CODE><B>ServerTask.</B><B><A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.html#globaloptions">globaloptions</A></B></CODE>
<BR>
Collection of globaloptions (name-value pairs) contained in the
"globaloption" nested elements.</TD>
</TR>
</TABLE>
<P>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../com/perforce/p4java/ant/tasks/package-summary.html">com.perforce.p4java.ant.tasks</A> that return <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks">ServerTask.GlobalOption</A></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks">ServerTask.GlobalOption</A></CODE></FONT></TD>
<TD><CODE><B>ServerTask.</B><B><A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.html#createGlobalOption()">createGlobalOption</A></B>()</CODE>
<BR>
This method is called by an Ant factory method to instantiates a
collection of "globaloption" nested elements.</TD>
</TR>
</TABLE>
<P>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../com/perforce/p4java/ant/tasks/ServerTask.GlobalOption.html" title="class in com.perforce.p4java.ant.tasks"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/perforce/p4java/ant/tasks//class-useServerTask.GlobalOption.html" target="_top"><B>FRAMES</B></A>
<A HREF="ServerTask.GlobalOption.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright (c) 2010 Perforce Software. All rights reserved.</i>
</BODY>
</HTML>
|
Java
|
L.CommunistWorker = L.AbstractWorker.extend({
statics: {
// number of web workers, not using web workers when falsy
NUM_WORKERS: 2
},
initialize: function (workerFunc) {
this.workerFunc = workerFunc;
},
onAdd: function (map) {
this._workers = L.CommunistWorker.createWorkers(this.workerFunc);
},
onRemove: function (map) {
if (this._workers) {
// TODO do not close when other layers are still using the static instance
//this._workers.close();
}
},
process: function(tile, callback) {
if (this._workers){
tile._worker = this._workers.data(tile.datum).then(function(parsed) {
if (tile._worker) {
tile._worker = null;
tile.parsed = parsed;
tile.datum = null;
callback(null, tile);
} else {
// tile has been unloaded, don't continue with adding
//console.log('worker aborted ' + tile.key);
}
});
} else {
callback(null, tile);
}
},
abort: function(tile) {
if (tile._worker) {
// TODO abort worker, would need to recreate after close
//tile._worker.close();
tile._worker = null;
}
}
});
L.communistWorker = function (workerFunc) {
return new L.CommunistWorker(workerFunc);
};
L.extend(L.CommunistWorker, {
createWorkers: function(workerFunc) {
if ( L.CommunistWorker.NUM_WORKERS && typeof Worker === "function" && typeof communist === "function"
&& !("workers" in L.CommunistWorker)) {
L.CommunistWorker.workers = communist({
//data : L.TileLayer.Vector.parseData
data : workerFunc
}, L.CommunistWorker.NUM_WORKERS);
}
return L.CommunistWorker.workers;
}
});
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace nora.clara.machine {
public enum Event {
OPEN_REQUEST,
ACTION_REQUEST,
DEATH_REQUEST,
CONNECTED_TO_STEAM,
PLAYING_STATE_OPENED,
PLAYING_STATE_CLOSED,
DISCONNECTED_FROM_STEAM,
WELCOMED_STALE_LOBBY,
WELCOMED,
JOINED_CHAT,
CREATED_LOBBY,
LEFT_LOBBY,
PLAYER_JOINED,
EMPTIED,
LOBBY_READY,
LOBBY_NOT_READY,
GOT_APP_TICKET,
GOT_AUTH,
GOT_SESSION,
GOT_TV,
GAME_SERVER_NOT_FOUND,
DENIED_TV,
SERVER_RUNNING,
SERVER_WAITING_FOR_PLAYERS,
GAME_SERVER_QUIT,
}
}
|
Java
|
About
=====
The 'reproject' package is a Python package to reproject astronomical images using various techniques via a uniform interface. By *reprojection*, we mean the re-gridding of images from one world coordinate system to another (for example changing the pixel resolution, orientation, coordinate system). Currently, we have implemented reprojection of celestial images by interpolation (like [SWARP](http://www.astromatic.net/software/swarp)), as well as by finding the exact overlap between pixels on the celestial sphere (like [Montage](http://montage.ipac.caltech.edu/index.html)). It can also reproject to/from HEALPIX projections by relying on the [healpy](https://github.com/healpy/healpy) package.
For more information, including on how to install the package, see http://reproject.readthedocs.org


Note on license
===============
The code in this package is released under the BSD license. However, the
functions relating to HEALPIX rely on the
[healpy](https://github.com/healpy/healpy) package, which is GPLv2, so if you
use these functions in your code, you are indirectly using healpy and therefore
will need to abide with the GPLv2 license.
Status
======
[](https://travis-ci.org/astrofrog/reproject) [](https://coveralls.io/r/astrofrog/reproject?branch=master) [](http://astrofrog.github.io/reproject-benchmarks/)
|
Java
|
# -*- coding: utf-8 -*-
"""
Pygments HTML formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2009 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
import re
import unittest
import StringIO
import tempfile
from os.path import join, dirname, isfile, abspath
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter, NullFormatter
from pygments.formatters.html import escape_html
import support
TESTFILE, TESTDIR = support.location(__file__)
tokensource = list(PythonLexer(encoding='utf-8').get_tokens(open(TESTFILE).read()))
class HtmlFormatterTest(unittest.TestCase):
def test_correct_output(self):
hfmt = HtmlFormatter(nowrap=True)
houtfile = StringIO.StringIO()
hfmt.format(tokensource, houtfile)
nfmt = NullFormatter()
noutfile = StringIO.StringIO()
nfmt.format(tokensource, noutfile)
stripped_html = re.sub('<.*?>', '', houtfile.getvalue())
escaped_text = escape_html(noutfile.getvalue())
self.assertEquals(stripped_html, escaped_text)
def test_external_css(self):
# test correct behavior
# CSS should be in /tmp directory
fmt1 = HtmlFormatter(full=True, cssfile='fmt1.css', outencoding='utf-8')
# CSS should be in TESTDIR (TESTDIR is absolute)
fmt2 = HtmlFormatter(full=True, cssfile=join(TESTDIR, 'fmt2.css'),
outencoding='utf-8')
tfile = tempfile.NamedTemporaryFile(suffix='.html')
fmt1.format(tokensource, tfile)
try:
fmt2.format(tokensource, tfile)
self.assert_(isfile(join(TESTDIR, 'fmt2.css')))
except IOError:
# test directory not writable
pass
tfile.close()
self.assert_(isfile(join(dirname(tfile.name), 'fmt1.css')))
os.unlink(join(dirname(tfile.name), 'fmt1.css'))
try:
os.unlink(join(TESTDIR, 'fmt2.css'))
except OSError:
pass
def test_all_options(self):
for optdict in [dict(nowrap=True),
dict(linenos=True),
dict(linenos=True, full=True),
dict(linenos=True, full=True, noclasses=True)]:
outfile = StringIO.StringIO()
fmt = HtmlFormatter(**optdict)
fmt.format(tokensource, outfile)
def test_valid_output(self):
# test all available wrappers
fmt = HtmlFormatter(full=True, linenos=True, noclasses=True,
outencoding='utf-8')
handle, pathname = tempfile.mkstemp('.html')
tfile = os.fdopen(handle, 'w+b')
fmt.format(tokensource, tfile)
tfile.close()
catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc')
try:
try:
import subprocess
ret = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname],
stdout=subprocess.PIPE).wait()
except ImportError:
# Python 2.3 - no subprocess module
ret = os.popen('nsgmls -s -c "%s" "%s"' % (catname, pathname)).close()
if ret == 32512: raise OSError # not found
except OSError:
# nsgmls not available
pass
else:
self.failIf(ret, 'nsgmls run reported errors')
os.unlink(pathname)
def test_get_style_defs(self):
fmt = HtmlFormatter()
sd = fmt.get_style_defs()
self.assert_(sd.startswith('.'))
fmt = HtmlFormatter(cssclass='foo')
sd = fmt.get_style_defs()
self.assert_(sd.startswith('.foo'))
sd = fmt.get_style_defs('.bar')
self.assert_(sd.startswith('.bar'))
sd = fmt.get_style_defs(['.bar', '.baz'])
fl = sd.splitlines()[0]
self.assert_('.bar' in fl and '.baz' in fl)
def test_unicode_options(self):
fmt = HtmlFormatter(title=u'Föö',
cssclass=u'bär',
cssstyles=u'div:before { content: \'bäz\' }',
encoding='utf-8')
handle, pathname = tempfile.mkstemp('.html')
tfile = os.fdopen(handle, 'w+b')
fmt.format(tokensource, tfile)
tfile.close()
|
Java
|
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* 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 'jMonkeyEngine' 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.
*/
package com.jme3.gde.core.filters.impl;
import com.jme3.gde.core.filters.AbstractFilterNode;
import com.jme3.gde.core.filters.FilterNode;
import com.jme3.post.Filter;
import com.jme3.water.WaterFilter;
import org.openide.loaders.DataObject;
import org.openide.nodes.Node;
import org.openide.nodes.Sheet;
/**
*
* @author Rémy Bouquet
*/
@org.openide.util.lookup.ServiceProvider(service = FilterNode.class)
public class JmeWaterFilter extends AbstractFilterNode {
public JmeWaterFilter() {
}
public JmeWaterFilter(WaterFilter filter, DataObject object, boolean readOnly) {
super(filter);
this.dataObject = object;
this.readOnly = readOnly;
}
@Override
protected Sheet createSheet() {
Sheet sheet = super.createSheet();
Sheet.Set set = Sheet.createPropertiesSet();
set.setDisplayName("Water");
set.setName("Water");
WaterFilter obj = (WaterFilter) filter;
if (obj == null) {
return sheet;
}
createFields(WaterFilter.class, set, obj);
sheet.put(set);
return sheet;
}
@Override
public Class<?> getExplorerObjectClass() {
return WaterFilter.class;
}
@Override
public Node[] createNodes(Object key, DataObject dataObject, boolean readOnly) {
return new Node[]{new JmeWaterFilter((WaterFilter) key, dataObject, readOnly)};
}
}
|
Java
|
<?php
namespace Nether\Object\Meta;
use Attribute;
use Nether\Object\Prototype\AttributeInterface;
use Nether\Object\Prototype\PropertyAttributes;
#[Attribute(Attribute::TARGET_PROPERTY)]
class PropertyOrigin
implements AttributeInterface {
/*//
@date 2021-08-05
@related Nether\Object\Prototype::__Construct
when attached to a class property with a single string argument that will
tell the prototype object to pull the data stored in the arguement and to put
it into the property this is attached to.
//*/
public string
$Name;
public function
__Construct(string $Name) {
$this->Name = $Name;
return;
}
public function
OnPropertyAttributes(PropertyAttributes $Attrib):
static {
$Attrib->Origin = $this->Name;
return $this;
}
}
|
Java
|
#!/usr/bin/perl
#
# Adduser script
# Rootnode, http://rootnode.net
#
# Copyright (C) 2012 Marcin Hlybin
# All rights reserved.
#
# Get user data from signup database
# Create PAM+Satan user
# Insert user data into adduser database
# Assign servers to user
# Create containers with lxc-add remote script
use warnings;
use strict;
use Readonly;
use FindBin qw($Bin);
use File::Basename qw(basename);
use POSIX qw(isdigit);
use DBI;
use Getopt::Long;
use Smart::Comments;
# Server ID's
Readonly my $WEB_SERVER_ID => 1;
Readonly my $APP_SERVER_ID => 1;
Readonly my $DEV_SERVER_ID => 1;
# Satan connection params
Readonly my $SATAN_ADDR => '10.101.0.5';
Readonly my $SATAN_PORT => '1600';
Readonly my $SATAN_KEY => '/etc/satan/key';
Readonly my $SATAN_BIN => '/usr/local/bin/satan';
# SSH params
Readonly my $SSH_BIN => '/usr/bin/ssh';
Readonly my $SSH_ADD_KEY => '/root/.ssh/lxc_add_rsa';
Readonly my $SSH_ADD_COMMAND => '/usr/local/sbin/lxc-add';
# Usage
Readonly my $BASENAME => basename($0);
Readonly my $USAGE => <<END_OF_USAGE;
Adduser script
Usage:
$BASENAME signup get signup data and create pam user
$BASENAME pam --uid <uid> create pam user omitting signup DB
$BASENAME container --uid <uid> --server <type> create container of given type
END_OF_USAGE
# Check configuration
-f $SATAN_BIN or die "\$SATAN_BIN ($SATAN_BIN) not found.\n";
-f $SATAN_KEY or die "\$SATAN_KEY ($SATAN_KEY) not found.\n";
-f $SSH_ADD_KEY or die "\$SSH_ADD_KEY ($SSH_ADD_KEY) not found.\n";
# Signup database
my %db_signup;
$db_signup{dbh} = DBI->connect("dbi:mysql:signup;mysql_read_default_file=$Bin/config/my.signup.cnf", undef, undef, { RaiseError => 1, AutoCommit => 1 });
$db_signup{get_user} = $db_signup{dbh}->prepare("SELECT * FROM users WHERE status IS NULL LIMIT 1");
$db_signup{del_user} = $db_signup{dbh}->prepare("DELETE FROM users WHERE id=?");
$db_signup{set_status} = $db_signup{dbh}->prepare("UPDATE users SET status=? WHERE id=?");
# Adduser database
my %db_adduser;
$db_adduser{dbh} = DBI->connect("dbi:mysql:adduser;mysql_read_default_file=$Bin/config/my.adduser.cnf", undef, undef, { RaiseError => 1, AutoCommit => 1 });
$db_adduser{add_user} = $db_adduser{dbh}->prepare("INSERT INTO users (uid, user_name, mail, created_at) VALUES(?,?,?, NOW())");
$db_adduser{get_user} = $db_adduser{dbh}->prepare("SELECT * FROM users WHERE uid=?");
$db_adduser{add_credentials} = $db_adduser{dbh}->prepare("INSERT INTO credentials(uid, satan_key, pam_passwd, pam_shadow, user_password, user_password_p) VALUES(?,?,?,?,?,?)");
$db_adduser{get_credentials} = $db_adduser{dbh}->prepare("SELECT * FROM credentials WHERE uid=?");
$db_adduser{add_container} = $db_adduser{dbh}->prepare("INSERT INTO containers(uid, server_type, server_no) VALUES(?,?,?)");
$db_adduser{get_container} = $db_adduser{dbh}->prepare("SELECT server_no FROM containers WHERE uid=? AND server_type=? and status is NULL");
$db_adduser{set_container_status} = $db_adduser{dbh}->prepare("UPDATE containers SET status=? WHERE uid=? AND server_type=?");
# Get arguments
die $USAGE unless @ARGV;
my $mode_type = shift or die "Mode not specified. Use 'signup', 'container' or 'pam'.\n";
# Get command line arguments
my ($opt_uid, $opt_server);
GetOptions(
'uid=i' => \$opt_uid,
'server=s' => \$opt_server,
);
# SIGNUP MODE
# Get 1 user from signup database
# Create Pam+Satan user
# Store data in adduser database
if ($mode_type eq 'signup') {
# Get one record from signup database
$db_signup{get_user}->execute;
# Exit if nothing found
my $record_found = $db_signup{get_user}->rows;
$record_found or exit;
# Get user data
my $signup_record = $db_signup{get_user}->fetchall_hashref('user_name');
### $signup_record
# Get username
my @user_names = keys %$signup_record;
my $user_name = shift @user_names;
### $user_name
# User record
my $user_record = $signup_record->{$user_name};
### $user_record
# Add PAM+Satan user
my $satan_response;
eval {
$satan_response = satan('admin', 'adduser', $user_name);
};
# Satan error
if ($@) {
my $error_message = $@;
chomp $error_message;
my $user_id = $user_record->{id};
$db_signup{set_status}->execute($error_message, $user_id);
die "Satan error: $@";
}
my $uid = $satan_response->{uid} or die "Didn't get uid from satan";
### $satan_response
# XXX Catch satan error
# $db_signup{set_status}->execute($error_message, $user_record->{id});
# Add record to adduser database
$db_adduser{add_user}->execute(
$uid,
$user_record->{user_name},
$user_record->{mail},
);
# Insert user credentials
$db_adduser{add_credentials}->execute(
$uid,
$satan_response->{satan_key},
$satan_response->{pam_passwd},
$satan_response->{pam_shadow},
$satan_response->{user_password},
$satan_response->{user_password_p}
);
# Assign servers
set_containers($uid);
# Remove record from signup database
$db_signup{del_user}->execute($user_record->{id});
exit;
}
# PAM MODE
# Create pam and satan user only.
if ($mode_type eq 'pam') {
# Mandatory arguments
defined $opt_uid or die "Uid not specified.";
my $uid = $opt_uid;
# Get user from adduser database
$db_adduser{get_user}->execute($uid);
my $user_found = $db_adduser{get_user}->rows;
$user_found or die "Uid '$uid' not found in adduser database.\n";
# User record
my $user_record = $db_adduser{get_user}->fetchall_hashref('uid')->{$uid};
my $user_name = $user_record->{user_name} or die "User name not found";
# Add PAM+Satan user with predefined uid
my $satan_response = satan('admin', 'adduser', $user_name, 'uid', $uid);
# Insert user credentials
$db_adduser{add_credentials}->execute(
$uid,
$satan_response->{satan_key},
$satan_response->{pam_passwd},
$satan_response->{pam_shadow},
$satan_response->{user_password},
$satan_response->{user_password_p}
);
# Assign servers to user
set_containers($uid);
exit;
}
# CONTAINER MODE
# Create user container on specified server.
# User must exist in adduser database.
if ($mode_type eq 'container') {
# Mandatory arguments
defined $opt_uid or die "Uid not specified.";
defined $opt_server or die "Server name not specified.";
my $uid = $opt_uid;
my $server_type = $opt_server;
# Get user from adduser database
$db_adduser{get_user}->execute($uid);
my $user_found = $db_adduser{get_user}->rows;
$user_found or die "Uid '$uid' not found in adduser database.\n";
# User record
my $user_record = $db_adduser{get_user}->fetchall_hashref('uid')->{$uid};
my $user_name = $user_record->{user_name} or die "User name not found";
### $user_name
# Get credentials
$db_adduser{get_credentials}->execute($uid);
my $credentials_found = $db_adduser{get_credentials}->rows;
$credentials_found or die "Uid '$uid' not found in database.\n";
my $credentials = $db_adduser{get_credentials}->fetchall_hashref('uid')->{$uid};
# Get container number
$db_adduser{get_container}->execute($uid, $server_type);
my $server_found = $db_adduser{get_container}->rows;
$server_found or die "Container type '$server_type' not defined for user '$uid'.\n";
my $server_no = $db_adduser{get_container}->fetchrow_arrayref->[0];
isdigit($server_no) or die "Server no '$server_no' not a number.\n";
my $server_name = $server_type . $server_no;
# Set SSH command arguments
my $command_args = "satan_key $credentials->{satan_key} "
. "pam_passwd $credentials->{pam_passwd} "
. "pam_shadow $credentials->{pam_shadow} "
. "uid $uid "
. "user_name $user_name";
### $command_args
system("$SSH_BIN -i $SSH_ADD_KEY root\@system.$server_name.rootnode.net $SSH_ADD_COMMAND $command_args");
if ($?) {
my $error_message = $!;
chomp $error_message;
$db_adduser{set_container_status}->execute($error_message, $uid, $server_type);
die "lxc-add failed: $!";
}
$db_adduser{set_container_status}->execute('OK', $uid, $server_type);
exit;
}
die "Unknown mode '$mode_type'. Cannot proceed.\n";
sub set_containers {
my ($uid) = @_;
defined $uid or die "Uid not defined in set_servers sub";
# Set server IDs
my %server_no_for = (
web => $WEB_SERVER_ID,
app => $APP_SERVER_ID,
dev => $DEV_SERVER_ID,
);
# Assing servers to user
foreach my $server_type (keys %server_no_for) {
# Get server number
my $server_no = $server_no_for{$server_type};
# Add server to database
$db_adduser{add_container}->execute(
$uid,
$server_type,
$server_no
);
}
return;
}
sub satan {
local @ARGV;
# Satan arguments
push @ARGV, '-a', $SATAN_ADDR if defined $SATAN_ADDR;
push @ARGV, '-p', $SATAN_PORT if defined $SATAN_PORT;
push @ARGV, '-k', $SATAN_KEY if defined $SATAN_KEY;
push @ARGV, @_;
# Send to satan
my $response = do $SATAN_BIN;
# Catch satan error
if ($@) {
my $error_message = $@;
die "Cannot proccess $@";
}
return $response;
}
sub do_rollback {
my ($error_message, $user_id) = @_;
$db_signup{set_status}->execute($error_message, $user_id);
}
exit;
|
Java
|
/**
* Copyright (c) 2013, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* https://raw.github.com/facebook/regenerator/master/LICENSE file. An
* additional grant of patent rights can be found in the PATENTS file in
* the same directory.
*/
var assert = require("assert");
var types = require("ast-types");
var n = types.namedTypes;
var b = types.builders;
var inherits = require("util").inherits;
function Entry() {
assert.ok(this instanceof Entry);
}
function FunctionEntry(returnLoc) {
Entry.call(this);
n.Literal.assert(returnLoc);
Object.defineProperties(this, {
returnLoc: { value: returnLoc }
});
}
inherits(FunctionEntry, Entry);
exports.FunctionEntry = FunctionEntry;
function LoopEntry(breakLoc, continueLoc, label) {
Entry.call(this);
n.Literal.assert(breakLoc);
n.Literal.assert(continueLoc);
if (label) {
n.Identifier.assert(label);
} else {
label = null;
}
Object.defineProperties(this, {
breakLoc: { value: breakLoc },
continueLoc: { value: continueLoc },
label: { value: label }
});
}
inherits(LoopEntry, Entry);
exports.LoopEntry = LoopEntry;
function SwitchEntry(breakLoc) {
Entry.call(this);
n.Literal.assert(breakLoc);
Object.defineProperties(this, {
breakLoc: { value: breakLoc }
});
}
inherits(SwitchEntry, Entry);
exports.SwitchEntry = SwitchEntry;
function TryEntry(catchEntry, finallyEntry) {
Entry.call(this);
if (catchEntry) {
assert.ok(catchEntry instanceof CatchEntry);
} else {
catchEntry = null;
}
if (finallyEntry) {
assert.ok(finallyEntry instanceof FinallyEntry);
} else {
finallyEntry = null;
}
Object.defineProperties(this, {
catchEntry: { value: catchEntry },
finallyEntry: { value: finallyEntry }
});
}
inherits(TryEntry, Entry);
exports.TryEntry = TryEntry;
function CatchEntry(firstLoc, paramId) {
Entry.call(this);
n.Literal.assert(firstLoc);
n.Identifier.assert(paramId);
Object.defineProperties(this, {
firstLoc: { value: firstLoc },
paramId: { value: paramId }
});
}
inherits(CatchEntry, Entry);
exports.CatchEntry = CatchEntry;
function FinallyEntry(firstLoc, nextLocTempVar) {
Entry.call(this);
n.Literal.assert(firstLoc);
n.Identifier.assert(nextLocTempVar);
Object.defineProperties(this, {
firstLoc: { value: firstLoc },
nextLocTempVar: { value: nextLocTempVar }
});
}
inherits(FinallyEntry, Entry);
exports.FinallyEntry = FinallyEntry;
function LeapManager(emitter) {
assert.ok(this instanceof LeapManager);
var Emitter = require("./emit").Emitter;
assert.ok(emitter instanceof Emitter);
Object.defineProperties(this, {
emitter: { value: emitter },
entryStack: {
value: [new FunctionEntry(emitter.finalLoc)]
}
});
}
var LMp = LeapManager.prototype;
exports.LeapManager = LeapManager;
LMp.withEntry = function(entry, callback) {
assert.ok(entry instanceof Entry);
this.entryStack.push(entry);
try {
callback.call(this.emitter);
} finally {
var popped = this.entryStack.pop();
assert.strictEqual(popped, entry);
}
};
LMp._leapToEntry = function(predicate, defaultLoc) {
var entry, loc;
var finallyEntries = [];
var skipNextTryEntry = null;
for (var i = this.entryStack.length - 1; i >= 0; --i) {
entry = this.entryStack[i];
if (entry instanceof CatchEntry ||
entry instanceof FinallyEntry) {
// If we are inside of a catch or finally block, then we must
// have exited the try block already, so we shouldn't consider
// the next TryStatement as a handler for this throw.
skipNextTryEntry = entry;
} else if (entry instanceof TryEntry) {
if (skipNextTryEntry) {
// If an exception was thrown from inside a catch block and this
// try statement has a finally block, make sure we execute that
// finally block.
if (skipNextTryEntry instanceof CatchEntry &&
entry.finallyEntry) {
finallyEntries.push(entry.finallyEntry);
}
skipNextTryEntry = null;
} else if ((loc = predicate.call(this, entry))) {
break;
} else if (entry.finallyEntry) {
finallyEntries.push(entry.finallyEntry);
}
} else if ((loc = predicate.call(this, entry))) {
break;
}
}
if (loc) {
// fall through
} else if (defaultLoc) {
loc = defaultLoc;
} else {
return null;
}
n.Literal.assert(loc);
var finallyEntry;
while ((finallyEntry = finallyEntries.pop())) {
this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc);
loc = finallyEntry.firstLoc;
}
return loc;
};
function getLeapLocation(entry, property, label) {
var loc = entry[property];
if (loc) {
if (label) {
if (entry.label &&
entry.label.name === label.name) {
return loc;
}
} else {
return loc;
}
}
return null;
}
LMp.emitBreak = function(label) {
var loc = this._leapToEntry(function(entry) {
return getLeapLocation(entry, "breakLoc", label);
});
if (loc === null) {
throw new Error("illegal break statement");
}
this.emitter.clearPendingException();
this.emitter.jump(loc);
};
LMp.emitContinue = function(label) {
var loc = this._leapToEntry(function(entry) {
return getLeapLocation(entry, "continueLoc", label);
});
if (loc === null) {
throw new Error("illegal continue statement");
}
this.emitter.clearPendingException();
this.emitter.jump(loc);
};
|
Java
|
{--
Copyright (c) 2014-2020, Clockwork Dev Studio
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
--}
{-# LANGUAGE CPP #-}
module Arguments where
import Prelude hiding (catch)
import LexerData
import Common
import Options
import Data.Char
import System.FilePath.Posix
import System.Directory
import System.IO
import Control.Exception
import System.Exit
import Control.Monad.State
import Control.Monad.Except
import Control.Monad.Identity
import Debug.Trace
import qualified Data.Sequence as Seq
data ConfigFile =
ConfigFile
{
configFileVariableList :: [ConfigFileVariable]
} deriving (Show,Eq)
data ConfigFileVariable =
ConfigFileVariable
{
configFileVariableName :: String,
configFileVariableValue :: String
} deriving (Show, Eq)
loadConfigFile :: Handle -> ConfigFile -> IO ConfigFile
loadConfigFile handle (ConfigFile variables) =
do let endOfFile :: IOError -> IO String
endOfFile e = do return "EOF"
line <- catch (hGetLine handle) endOfFile
if line == "EOF"
then return (ConfigFile variables)
else do let (variable,rest) = span (isAlpha) line
if variable == [] || rest == [] || head rest /= '='
then loadConfigFile handle (ConfigFile variables)
else do loadConfigFile handle (ConfigFile (variables ++ [(ConfigFileVariable variable (tail rest))]))
adjustOptionsBasedOnConfigFile :: Options -> [ConfigFileVariable] -> Options
adjustOptionsBasedOnConfigFile originalOptions (configFileVariable:rest) =
case configFileVariableName configFileVariable of
"backend" -> adjustOptionsBasedOnConfigFile (originalOptions {optionAssembler = configFileVariableValue configFileVariable}) rest
adjustOptionsBasedOnConfigFile originalOptions _ = originalOptions
processArguments :: CodeTransformation ()
processArguments =
do homeDirectory <- liftIO $ getHomeDirectory
let writeDefaultConfigFile :: IOError -> IO Handle
writeDefaultConfigFile _ =
do newConfHandle <- openFile (homeDirectory ++ "/.idlewild-lang.conf") WriteMode
hPutStrLn newConfHandle "backend=nasm"
hClose newConfHandle
newConfHandle <- openFile (homeDirectory ++ "/.idlewild-lang.conf") ReadMode
return newConfHandle
confHandle <- liftIO $ (catch (openFile (homeDirectory ++ "/.idlewild-lang.conf") ReadMode) writeDefaultConfigFile)
configFile <- liftIO $ loadConfigFile confHandle (ConfigFile [])
let customisedOptions = adjustOptionsBasedOnConfigFile defaultOptions (configFileVariableList configFile)
liftIO $ hClose confHandle
arguments <- gets argumentStateArguments
(options, nonOptions) <- liftIO $ processOptions customisedOptions arguments
if optionShowVersion options == True
then do liftIO $ putStrLn "Idlewild-Lang version 0.0.5."
liftIO $ exitSuccess
else return ()
if length nonOptions /= 1
then do liftIO $ putStrLn "Please specify one (and only one) source file name."
liftIO $ exitSuccess
else return ()
let sourceFileName = head nonOptions
asmFileName = replaceExtension sourceFileName ".asm"
#if LINUX==1 || MAC_OS==1
objectFileName = replaceExtension sourceFileName ".o"
#elif WINDOWS==1
objectFileName = replaceExtension sourceFileName ".obj"
#endif
verbose = optionVerbose options
fromHandle <- liftIO $ openFile sourceFileName ReadMode
toHandle <- liftIO $ openFile asmFileName WriteMode
code <- liftIO $ hGetContents fromHandle
put LexState
{lexStateID = LEX_PENDING,
lexStateIncludeFileDepth = 0,
lexStateIncludeFileNameStack = [sourceFileName],
lexStateIncludeFileNames = [],
lexStateCurrentToken = emptyToken,
lexStatePendingTokens = Seq.empty,
lexStateTokens = Seq.singleton (createBOFToken sourceFileName),
lexStateLineNumber = 1,
lexStateLineOffset = 0,
lexStateCharacters = code,
lexStateCompoundTokens = allCompoundTokens,
lexStateConfig = Config {configInputFile = fromHandle,
configOutputFile = toHandle,
configSourceFileName = sourceFileName,
configAsmFileName = asmFileName,
configObjectFileName = objectFileName,
configOptions = options}}
verboseCommentary ("Program arguments okay...\n") verbose
verboseCommentary ("Source file '" ++ sourceFileName ++ "'...\n") verbose
|
Java
|
#ifndef AOS_COMMON_STL_MUTEX_H_
#define AOS_COMMON_STL_MUTEX_H_
#include <mutex>
#include "aos/linux_code/ipc_lib/aos_sync.h"
#include "aos/common/logging/logging.h"
#include "aos/common/type_traits.h"
#include "aos/common/macros.h"
namespace aos {
// A mutex with the same API and semantics as ::std::mutex, with the addition of
// methods for checking if the previous owner died and a constexpr default
// constructor.
// Definitely safe to put in SHM.
// This uses the pthread_mutex semantics for owner-died: once somebody dies with
// the lock held, anybody else who takes it will see true for owner_died() until
// one of them calls consistent(). It is an error to call unlock() when
// owner_died() returns true.
class stl_mutex {
public:
constexpr stl_mutex() : native_handle_() {}
void lock() {
const int ret = mutex_grab(&native_handle_);
switch (ret) {
case 0:
break;
case 1:
owner_died_ = true;
break;
default:
LOG(FATAL, "mutex_grab(%p) failed with %d\n", &native_handle_, ret);
}
}
bool try_lock() {
const int ret = mutex_trylock(&native_handle_);
switch (ret) {
case 0:
return true;
case 1:
owner_died_ = true;
return true;
case 4:
return false;
default:
LOG(FATAL, "mutex_trylock(%p) failed with %d\n", &native_handle_, ret);
}
}
void unlock() {
CHECK(!owner_died_);
mutex_unlock(&native_handle_);
}
typedef aos_mutex *native_handle_type;
native_handle_type native_handle() { return &native_handle_; }
bool owner_died() const { return owner_died_; }
void consistent() { owner_died_ = false; }
private:
aos_mutex native_handle_;
bool owner_died_ = false;
DISALLOW_COPY_AND_ASSIGN(stl_mutex);
};
// A mutex with the same API and semantics as ::std::recursive_mutex, with the
// addition of methods for checking if the previous owner died and a constexpr
// default constructor.
// Definitely safe to put in SHM.
// This uses the pthread_mutex semantics for owner-died: once somebody dies with
// the lock held, anybody else who takes it will see true for owner_died() until
// one of them calls consistent(). It is an error to call unlock() or lock()
// again when owner_died() returns true.
class stl_recursive_mutex {
public:
constexpr stl_recursive_mutex() {}
void lock() {
if (mutex_islocked(mutex_.native_handle())) {
CHECK(!owner_died());
++recursive_locks_;
} else {
mutex_.lock();
if (mutex_.owner_died()) {
recursive_locks_ = 0;
} else {
CHECK_EQ(0, recursive_locks_);
}
}
}
bool try_lock() {
if (mutex_islocked(mutex_.native_handle())) {
CHECK(!owner_died());
++recursive_locks_;
return true;
} else {
if (mutex_.try_lock()) {
if (mutex_.owner_died()) {
recursive_locks_ = 0;
} else {
CHECK_EQ(0, recursive_locks_);
}
return true;
} else {
return false;
}
}
}
void unlock() {
if (recursive_locks_ == 0) {
mutex_.unlock();
} else {
--recursive_locks_;
}
}
typedef stl_mutex::native_handle_type native_handle_type;
native_handle_type native_handle() { return mutex_.native_handle(); }
bool owner_died() const { return mutex_.owner_died(); }
void consistent() { mutex_.consistent(); }
private:
stl_mutex mutex_;
int recursive_locks_ = 0;
DISALLOW_COPY_AND_ASSIGN(stl_recursive_mutex);
};
// Convenient typedefs for various types of locking objects.
typedef ::std::lock_guard<stl_mutex> mutex_lock_guard;
typedef ::std::lock_guard<stl_recursive_mutex> recursive_lock_guard;
typedef ::std::unique_lock<stl_mutex> mutex_unique_lock;
typedef ::std::unique_lock<stl_recursive_mutex> recursive_unique_lock;
} // namespace aos
#endif // AOS_COMMON_STL_MUTEX_H_
|
Java
|
#pragma once
//-----------------------------------------------------------------------------------------------------
/*
NAMESPACE::CLASS
DESC
Copyright 2015 - See license file LICENSE.txt
*/
//-----------------------------------------------------------------------------------------------------
namespace ASL
{
struct Expr
{
public:
/// constructor
Expr();
/// destructor
virtual ~Expr();
private:
};
} // namespace ASL
|
Java
|
{% extends "fieldsight/fieldsight_base.html" %}
{% load i18n staticfiles %}
{% load filters %}
{% block content %}
<div id="main-content" class="padding">
{% if messages %}
{% for message in messages %}
<div class="alert alert-{% if message.tags %}{{ message.tags }}{% else %}info{% endif %}">
<strong class="text-capitalize">{% if message.tags %}{{ message.tags }}{% else %}info{% endif %}!</strong> {{ message }}
</div>
{% endfor %}
{% endif %}
{% if obj.children.all %}
<section class="panel">
<header class="panel-heading clearfix">
<h3>{% trans 'Sub regions' %}</h3>
</header>
<div class="panel-body">
<div class="row">
{% for child in obj.children.all %}
<div class="col-md-4 col-sm-6">
<a class="site-item-wrap margin-top" href="{% url 'fieldsight:regional-sites' child.project.pk child.pk %}">
<div class="basic-info clearfix">
<h4 class="detail-text1">{{ child.name }}</h4>
<h6 class="detail-text0">{{ child.identifier }}</h6>
<div>Total sites: {{ child.get_sites_count }}</div>
</div>
</a>
</div>
{% endfor %}
</div>
</div>
</section>
{% endif %}
<section class="panel">
<header class="panel-heading clearfix">
<h3><i class="la la-map-marker"></i>{% if request.GET.q %}{% trans 'Search' %} {% trans 'result' %} {% trans 'for' %} "{{request.GET.q}}"{% else %}{% trans 'Sites' %}{% endif %}</h3>
<div class="panel-heading-right">
<!-- <select name ="sortby" class="form-control form-control-sm" data-bind="value:sortby, valueUpdate:'afterkeydown'">
<option class="dropdown-list" value="sitename" disabled selected>{% trans 'Sort' %} {% trans 'By' %}</option>
<option value="progress">{% trans 'Site Progress' %}</option>
<option value="identifier">{% trans 'Site Identifier' %}</option>
<option value="sitename">{% trans 'Site Name' %}</option>
<option value="pending">{% trans 'Number of Pending Submissions' %}</option>
<option value="approved">{% trans 'Number of Approved Submissions' %}</option>
<option value="flagged">{% trans 'Number of Flagged Submissions' %}</option>
<option value="rejected">{% trans 'Number of Rejected Submissions' %}</option>
</select> -->
<a class="btn btn-sm btn-primary" data-toggle="collapse" href="#searchSite" aria-expanded="false" aria-controls="searchSite"><i class="la la-search"></i> {% trans 'Search' %}</a>
{% if type == "project" %}
<a href="{% url 'fieldsight:site-add' pk %}" title="" class="btn btn-sm btn-primary"><i class="la la-plus"></i> {% trans 'Add' %} {% trans 'New' %}</a>
<a href="{% url 'fieldsight:define-site-meta' pk %}" title="" class="btn btn-sm btn-primary"><i class="la la-cogs"></i> {% trans 'Meta' %} {% trans 'Attributes' %}</a>
<a href="{% url 'fieldsight:site-upload' pk %}" title="" class="btn btn-sm btn-primary"><i class="la la-files-o"></i> {% trans 'Bulk' %} {% trans 'Upload' %} {% trans 'Sites' %}</a>
<a href="{% url 'fieldsight:bulk-edit-site' pk %}" title="" class="btn btn-sm btn-primary"><i class="la la-files-o"></i> {% trans 'Bulk' %} {% trans 'edit' %} {% trans 'Sites' %}</a>
{% verbatim %}
<div id="export_button"></div>
{% endverbatim %}
<script>
configure_settings = {};
configure_settings.is_project_dashboard = false;
configure_settings.url = "{% url 'fieldsight_export:export_xls_project_level_sites' pk %}";
</script>
<!-- <a href="{% url 'fieldsight_export:export_xls_project_sites' pk %}" title="" class="btn btn-sm
btn-primary"><i class="la la-plus"></i> {% trans 'Export' %} {% trans 'Sites' %} {% trans 'data' %} </a> -->
{% endif %}
{% if type == "region" %}
<a href="{% url 'fieldsight:regional-site-add' pk region_id %}" title="" class="btn btn-sm
btn-primary"><i class="la la-plus"></i> {% trans 'Add' %} {% trans 'New' %} {% trans 'Regional' %} {% trans 'Site' %}</a>
<a href="{% url 'fieldsight:define-site-meta' pk %}" title="" class="btn btn-sm btn-primary"><i class="la la-cogs"></i> {% trans 'Meta' %} {% trans 'Attributes' %}</a>
{% verbatim %}
<div id="export_button"></div>
{% endverbatim %}
<script>
configure_settings = {};
configure_settings.is_project_dashboard = false;
configure_settings.url = "{% url 'fieldsight_export:export_xls_region_sites' pk region_id %}";
</script>
<!-- <a href="{% url 'fieldsight_export:export_xls_region_sites' pk region_id %}" title="" class="btn btn-sm
btn-primary"><i class="la la-plus"></i> {% trans 'Export' %} {% trans 'Sites' %} {% trans 'data' %} </a> -->
{% elif type == "Unregioned" %}
<a href="{% url 'fieldsight:site-add' project_id %}" title="" class="btn btn-sm
btn-primary"><i class="la la-plus"></i> {% trans 'Add' %} {% trans 'New' %} {% trans 'Regional' %} {% trans 'Site' %}</a>
<a href="{% url 'fieldsight:define-site-meta' project_id %}" title="" class="btn btn-sm btn-primary"><i class="la la-files-o"></i> {% trans 'Meta' %} {% trans 'Attributes' %}</a>
{% verbatim %}
<div id="export_button"></div>
{% endverbatim %}
<script>
configure_settings = {};
configure_settings.is_project_dashboard = false;
configure_settings.url = "{% url 'fieldsight_export:export_xls_region_sites' project_id 0 %}";
</script>
<!-- <a href="{% url 'fieldsight_export:export_xls_project_sites' project_id %}" title="" class="btn btn-sm
btn-primary"><i class="la la-plus"></i> {% trans 'Export' %} {% trans 'Sites' %} {% trans 'data' %} </a> -->
{% endif %}
</div>
</header>
<div class="panel-body">
<!--Search Organization-->
<div class="collapse margin-top" id="searchSite">
<form class="padding" action="{% if region_id %}{% url 'fieldsight:search-regional-site-list' pk region_id %}{% else %}{% url 'fieldsight:search-site-list' pk %}{% endif %}" method="GET">
<div class="row">
<div class="col-md-6 ml-md-auto">
<div class="input-group">
<input type="text" class="form-control" name="q" placeholder="Search for..." required value='{{ request.GET.q }}'/>
<span class="input-group-btn">
<button class="btn btn-primary" type="submit"><i class="la la-search"></i> {% trans 'Search' %}</button>
</span>
</div>
</div>
<div class="col-md-3"></div>
</div>
</form>
</div>
<div class="row" >
{% for site in object_list %}
<div class="col-md-4 col-sm-6">
<a href= {% url 'fieldsight:site-dashboard' site.pk %} title="" class="site-item-wrap margin-top clearfix">
<div class="logo">
<img src="{{ site.logo.url }}" alt="" width="100" height="100">
</div>
<div class="basic-info clearfix">
<h4 class="detail-text1" >{{site.name}}</h4>
<h6 class="detail-text0" >{{ site.identifier }}</h6>
<p class="address"><i class="fa fa-map-marker" aria-hidden="true"></i> <span class="detail-text1">{{ site.address }}</span></p>
<p class="phone"><i class="fa fa-phone" aria-hidden="true"></i> <span class="detail-text1">{{ site.phone }}</span></p>
</div>
{% with site.get_site_submission_count as count %}
<ul class="icon-listing clearfix margin-top">
<li>
<i class="la la-thumbs-up"></i>
<span>{{ count.approved }}
</span>
</li>
<li>
<i class="la la-flag"></i>
<span>
{{ count.flagged }}
</span>
</li>
<li>
<i class="la la-hourglass-half"></i>
<span>
{{ count.outstanding }}
</span>
</li>
<li>
<i class="la la-exclamation"></i>
<span>
{{ count.rejected }}
</span>
</li>
</ul>
{% endwith %}
<div class="progress margin-top">
<div class="progress progress-striped active progress-sm" style="width:100%;">
<div class="progress-bar progress-bar-success" role="progressbar" style="width:{{ site.site_progress }}%;}">
<span class="progress-bar-value" style="color:grey;">{{ site.site_progress }}% Complete'"</span>
</div>
</div>
</div>
</a>
</div>
{% empty %}
<div class="col-md-4 col-sm-6">
<h3>No Site</h3>
</div>
{% endfor %}
</div>
<br>
{% if is_paginated %}
<nav class="pagination justify-content-center" aria-label="page-navigation">
<ul class="pagination">
{% if page_obj.number == 1 %}
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ 1 }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">First</a></li>
{% endif %}
{% if page_obj.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">«</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">«</a></li>
{% endif %}
{% if paginator.num_pages > 21 %}
{% page_offsets page_obj.number paginator.num_pages 20 as data %}
{% for item in data.front_range %}
<li class="page-item"><a class="page-link" href="?page={{ item }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">{{ item }}</a></li>
{% endfor %}
<li class="page-item active"><a class="page-link" href="?page={{ page_obj.number }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">{{ page_obj.number }}</a></li>
{% for item in data.back_range %}
<li class="page-item"><a class="page-link" href="?page={{ item }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">{{ item }}</a></li>
{% endfor %}
{% else %}
{% for i in paginator.page_range %}
{% if page_obj.number == i %}
<li class="page-item active"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% endif %}
{% if page_obj.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">»</a></li>
{% else %}
<li class="page-item disabled"><a class="page-link" href="#">»</a></li>
{% endif %}
{% if page_obj.number == paginator.num_pages %}
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ paginator.num_pages }}{% if request.GET.q %}&q={{request.GET.q}}{% endif %}">Last</a></li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
</section>
</div>
{% endblock %}
{%block extrascript %}
<script type="text/javascript" src="{% static 'vendor/vue.js' %}"></script>
<script src="{% static 'js/forms/vue-resource.min.js' %}"></script>
<script src="{% static 'js/fieldsight/site_export.js' %}?v=0.4"></script>
{% endblock %}
|
Java
|
/*
* Software written by Jared Bruni https://github.com/lostjared
This software is dedicated to all the people that experience mental illness.
Website: http://lostsidedead.com
YouTube: http://youtube.com/LostSideDead
Instagram: http://instagram.com/lostsidedead
Twitter: http://twitter.com/jaredbruni
Facebook: http://facebook.com/LostSideDead0x
You can use this program free of charge and redistrubute it online as long
as you do not charge anything for this program. This program is meant to be
100% free.
BSD 2-Clause License
Copyright (c) 2020, Jared Bruni
All rights reserved.
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.
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 HOLDER 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.
*/
#import<Foundation/Foundation.h>
#import<Cocoa/Cocoa.h>
extern NSMutableArray *search_results;
@interface SearchController : NSObject<NSTableViewDataSource, NSTableViewDelegate> {
}
@end
|
Java
|
class Gosec < Formula
desc "Golang security checker"
homepage "https://securego.io/"
url "https://github.com/securego/gosec/archive/v2.7.0.tar.gz"
sha256 "fd0b1ba1874cad93680c9e398af011560cd43b638c2b8d34850987a4cf984ba0"
license "Apache-2.0"
head "https://github.com/securego/gosec.git"
bottle do
sha256 cellar: :any_skip_relocation, arm64_big_sur: "8eaa54d014d924fa1ca807c25d7b2827023103582d7b269234f35a448787da64"
sha256 cellar: :any_skip_relocation, big_sur: "12d452f02f025f62136d866c00cdd54e0594e3ec1930d70f3aecd4960388273b"
sha256 cellar: :any_skip_relocation, catalina: "d6d5c69d310d0471950f4682193d27c4e59ef3b26acd185c01f9ab3cc7f78f92"
sha256 cellar: :any_skip_relocation, mojave: "7b07d7387e6477c1be027fd6f12eba5b3ac3f19b4fe5762cab07171aed40a514"
end
depends_on "go"
def install
system "go", "build", *std_go_args, "-ldflags", "-X main.version=v#{version}", "./cmd/gosec"
end
test do
(testpath/"test.go").write <<~EOS
package main
import "fmt"
func main() {
username := "admin"
var password = "f62e5bcda4fae4f82370da0c6f20697b8f8447ef"
fmt.Println("Doing something with: ", username, password)
}
EOS
output = shell_output("#{bin}/gosec ./...", 1)
assert_match "G101 (CWE-798)", output
assert_match "Issues: 1", output
end
end
|
Java
|
var http = require('http')
var url = require('url')
var path = require('path')
var sleep = require('sleep-ref')
var Router = require("routes-router")
var concat = require('concat-stream')
var ldj = require('ldjson-stream')
var manifest = require('level-manifest')
var multilevel = require('multilevel')
var extend = require('extend')
var prettyBytes = require('pretty-bytes')
var jsonStream = require('JSONStream')
var prebuiltEditor = require('dat-editor-prebuilt')
var debug = require('debug')('rest-handler')
var auth = require('./auth.js')
var pump = require('pump')
var zlib = require('zlib')
var through = require('through2')
module.exports = RestHandler
function RestHandler(dat) {
if (!(this instanceof RestHandler)) return new RestHandler(dat)
this.dat = dat
this.auth = auth(dat.options)
this.router = this.createRoutes()
this.sleep = sleep(function(opts) {
opts.decode = true
if (opts.live === 'true') opts.live = true
if (opts.tail === 'true') opts.tail = true
return dat.createChangesReadStream(opts)
}, {style: 'newline'})
}
RestHandler.prototype.createRoutes = function() {
var router = Router()
router.addRoute("/", this.dataTable.bind(this))
router.addRoute("/api/session", this.session.bind(this))
router.addRoute("/api/login", this.login.bind(this))
router.addRoute("/api/logout", this.logout.bind(this))
router.addRoute("/api/pull", this.pull.bind(this))
router.addRoute("/api/push", this.push.bind(this))
router.addRoute("/api/changes", this.changes.bind(this))
router.addRoute("/api/stats", this.stats.bind(this))
router.addRoute("/api/bulk", this.bulk.bind(this))
router.addRoute("/api/metadata", this.package.bind(this))
router.addRoute("/api/manifest", this.manifest.bind(this))
router.addRoute("/api/rpc", this.rpc.bind(this))
router.addRoute("/api/csv", this.exportCsv.bind(this))
router.addRoute("/api", this.hello.bind(this))
router.addRoute("/api/rows", this.document.bind(this))
router.addRoute("/api/rows/:key", this.document.bind(this))
router.addRoute("/api/rows/:key/:filename", this.blob.bind(this))
router.addRoute("/api/blobs/:key", this.blobs.bind(this))
router.addRoute("*", this.notFound.bind(this))
return router
}
RestHandler.prototype.session = function(req, res) {
var self = this
this.auth.handle(req, res, function(err, session) {
debug('session', [err, session])
var data = {}
if (err) return self.auth.error(req, res)
if (session) data.session = session
else data.loggedOut = true
self.json(res, data)
})
}
RestHandler.prototype.login = function(req, res) {
var self = this
this.auth.handle(req, res, function(err, session) {
debug('login', [err, session])
if (err) {
res.setHeader("WWW-Authenticate", "Basic realm=\"Secure Area\"")
self.auth.error(req, res)
return
}
self.json(res, {session: session})
})
}
RestHandler.prototype.logout = function(req, res) {
return this.auth.error(req, res)
}
RestHandler.prototype.blob = function(req, res, opts) {
var self = this
if (req.method === 'GET') {
var key = opts.key
var blob = self.dat.createBlobReadStream(opts.key, opts.filename, opts)
blob.on('error', function(err) {
return self.error(res, 404, {"error": "Not Found"})
})
pump(blob, res)
return
}
if (req.method === "POST") {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
var doc = {
key: opts.key,
version: qs.version
}
self.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
var key = doc.key
self.dat.get(key, { version: doc.version }, function(err, existing) {
if (existing) {
doc = existing
}
var ws = self.dat.createBlobWriteStream(opts.filename, doc, function(err, updated) {
if (err) return self.error(res, 500, err)
self.json(res, updated)
})
pump(req, ws)
})
return
})
return
}
self.error(res, 405, {error: 'method not supported'})
}
RestHandler.prototype.blobs = function(req, res, opts) {
var self = this
if (req.method === 'HEAD') {
var key = opts.key
var blob = self.dat.blobs.backend.exists(opts, function(err, exists) {
res.statusCode = exists ? 200 : 404
res.setHeader('content-length', 0)
res.end()
})
return
}
if (req.method === 'GET') {
res.statusCode = 200
return pump(self.dat.blobs.backend.createReadStream(opts), res)
}
self.error(res, 405, {error: 'method not supported'})
}
var unzip = function(req) {
return req.headers['content-encoding'] === 'gzip' ? zlib.createGunzip() : through()
}
var zip = function(req, res) {
if (!/gzip/.test(req.headers['accept-encoding'] || '')) return through()
res.setHeader('Content-Encoding', 'gzip')
return zlib.createGzip()
}
RestHandler.prototype.push = function(req, res) {
var self = this
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
pump(req, unzip(req), self.dat.replicator.receive(), function(err) {
if (err) {
res.statusCode = err.status || 500
res.end(err.message)
return
}
res.end()
})
})
}
RestHandler.prototype.pull = function(req, res) {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
var send = this.dat.replicator.send({
since: parseInt(qs.since, 10) || 0,
blobs: qs.blobs !== 'false',
live: !!qs.live
})
pump(send, zip(req, res), res)
}
RestHandler.prototype.changes = function(req, res) {
this.sleep.httpHandler(req, res)
}
RestHandler.prototype.stats = function(req, res) {
var statsStream = this.dat.createStatsStream()
statsStream.on('error', function(err) {
var errObj = {
type: 'statsStreamError',
message: err.message
}
res.statusCode = 400
serializer.write(errObj)
serializer.end()
})
var serializer = ldj.serialize()
pump(statsStream, serializer, res)
}
RestHandler.prototype.package = function(req, res) {
var meta = {changes: this.dat.storage.change, liveBackup: this.dat.supportsLiveBackup()}
meta.columns = this.dat.schema.headers()
this.json(res, meta)
}
RestHandler.prototype.manifest = function(req, res) {
this.json(res, manifest(this.dat.storage))
}
RestHandler.prototype.rpc = function(req, res) {
var self = this
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
var mserver = multilevel.server(self.dat.storage)
pump(req, mserver, res)
})
}
RestHandler.prototype.exportCsv = function(req, res) {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
qs.csv = true
var readStream = this.dat.createReadStream(qs)
res.writeHead(200, {'content-type': 'text/csv'})
pump(readStream, res)
}
RestHandler.prototype.exportJson = function(req, res) {
var reqUrl = url.parse(req.url, true)
var qs = reqUrl.query
if (typeof qs.limit === 'undefined') qs.limit = 50
else qs.limit = +qs.limit
var readStream = this.dat.createReadStream(qs)
res.writeHead(200, {'content-type': 'application/json'})
pump(readStream, jsonStream.stringify('{"rows": [\n', '\n,\n', '\n]}\n'), res)
}
RestHandler.prototype.handle = function(req, res) {
debug(req.connection.remoteAddress + ' - ' + req.method + ' - ' + req.url + ' - ')
this.router(req, res)
}
RestHandler.prototype.error = function(res, status, message) {
if (!status) status = res.statusCode
if (message) {
if (message.status) status = message.status
if (typeof message === "object") message.status = status
if (typeof message === "string") message = {error: status, message: message}
}
res.statusCode = status || 500
this.json(res, message)
}
RestHandler.prototype.notFound = function(req, res) {
this.error(res, 404, {"error": "Not Found"})
}
RestHandler.prototype.hello = function(req, res) {
var self = this
var stats = {
"dat": "Hello",
"version": this.dat.version,
"changes": this.dat.storage.change,
"name": this.dat.options.name
}
this.dat.storage.stat(function(err, stat) {
if (err) return self.json(res, stats)
stats.rows = stat.rows
self.dat.storage.approximateSize(function(err, size) {
if (err) return self.json(res, stats)
stats.approximateSize = { rows: prettyBytes(size) }
self.json(res, stats)
})
})
}
RestHandler.prototype.dataTable = function(req, res) {
res.setHeader('content-type', 'text/html; charset=utf-8')
res.end(prebuiltEditor)
}
RestHandler.prototype.json = function(res, json) {
res.setHeader('content-type', 'application/json')
res.end(JSON.stringify(json) + '\n')
}
RestHandler.prototype.get = function(req, res, opts) {
var self = this
this.dat.get(opts.key, url.parse(req.url, true).query || {}, function(err, json) {
if (err && err.message === 'range not found') return self.error(res, 404, {error: "Not Found"})
if (err) return self.error(res, 500, err.message)
if (json === null) return self.error(res, 404, {error: "Not Found"})
self.json(res, json)
})
}
RestHandler.prototype.post = function(req, res) {
var self = this
self.bufferJSON(req, function(err, json) {
if (err) return self.error(res, 500, err)
if (!json) json = {}
self.dat.put(json, function(err, stored) {
if (err) {
if (err.conflict) return self.error(res, 409, {conflict: true, error: "Document update conflict. Invalid version"})
return self.error(res, 500, err)
}
res.statusCode = 201
self.json(res, stored)
})
})
}
RestHandler.prototype.delete = function(req, res, opts) {
var self = this
self.dat.delete(opts.key, function(err, stored) {
if (err) return self.error(res, 500, err)
self.json(res, {deleted: true})
})
}
RestHandler.prototype.bulk = function(req, res) {
var self = this
var opts = {}
var ct = req.headers['content-type']
if (ct === 'application/json') opts.json = true
else if (ct === 'text/csv') opts.csv = true
else return self.error(res, 400, {error: 'missing or unsupported content-type'})
opts.results = true
debug('/api/bulk', opts)
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
var writeStream = self.dat.createWriteStream(opts)
writeStream.on('error', function(writeErr) {
var errObj = {
type: 'writeStreamError',
message: writeErr.message
}
res.statusCode = 400
serializer.write(errObj)
serializer.end()
})
var serializer = ldj.serialize()
pump(req, writeStream, serializer, res)
})
}
RestHandler.prototype.document = function(req, res, opts) {
var self = this
if (req.method === "GET" || req.method === "HEAD") {
if (opts.key) return this.get(req, res, opts)
else return this.exportJson(req, res)
}
this.auth.handle(req, res, function(err) {
if (err) return self.auth.error(req, res)
if (req.method === "POST") return self.post(req, res, opts)
if (req.method === "DELETE") return self.delete(req, res, opts)
self.error(res, 405, {error: 'method not supported'})
})
}
RestHandler.prototype.bufferJSON = function(req, cb) {
var self = this
req.on('error', function(err) {
cb(err)
})
req.pipe(concat(function(buff) {
var json
if (buff && buff.length === 0) return cb()
if (buff) {
try {
json = JSON.parse(buff)
} catch(err) {
return cb(err)
}
}
if (!json) return cb(err)
cb(null, json)
}))
}
|
Java
|
/**
* The main application class. An instance of this class is created by app.js when it calls
* Ext.application(). This is the ideal place to handle application launch and initialization
* details.
*
*
*/
Ext.define('Sample.Application', {
extend: 'Devon.App',
name: 'Sample',
requires:[
'Sample.Simlets'
],
controllers: [
'Sample.controller.main.MainController',
'Sample.controller.table.TablesController',
'Sample.controller.cook.CookController'
],
launch: function() {
Devon.Log.trace('Sample.app launch');
console.log('Sample.app launch');
if (document.location.toString().indexOf('useSimlets')>=0){
Sample.Simlets.useSimlets();
}
this.callParent(arguments);
}
});
|
Java
|
package com.glob3mobile.vectorial.processing;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import com.glob3mobile.utils.Progress;
import com.glob3mobile.vectorial.lod.PointFeatureLODStorage;
import com.glob3mobile.vectorial.lod.mapdb.PointFeatureLODMapDBStorage;
import com.glob3mobile.vectorial.storage.PointFeature;
import com.glob3mobile.vectorial.storage.PointFeatureStorage;
import com.glob3mobile.vectorial.storage.mapdb.PointFeatureMapDBStorage;
public class LODPointFeaturesPreprocessor {
private static class LeafNodesImporter
implements
PointFeatureStorage.NodeVisitor {
private final long _nodesCount;
private final PointFeatureLODStorage _lodStorage;
private final boolean _verbose;
private Progress _progress;
private LeafNodesImporter(final long nodesCount,
final PointFeatureLODStorage lodStorage,
final boolean verbose) {
_nodesCount = nodesCount;
_lodStorage = lodStorage;
_verbose = verbose;
}
@Override
public void start() {
_progress = new Progress(_nodesCount) {
@Override
public void informProgress(final long stepsDone,
final double percent,
final long elapsed,
final long estimatedMsToFinish) {
if (_verbose) {
System.out.println(_lodStorage.getName() + ": 1/4 Importing leaf nodes: "
+ progressString(stepsDone, percent, elapsed, estimatedMsToFinish));
}
}
};
}
@Override
public void stop() {
_progress.finish();
_progress = null;
}
@Override
public boolean visit(final PointFeatureStorage.Node node) {
final List<PointFeature> features = new ArrayList<>(node.getFeatures());
_lodStorage.addLeafNode( //
node.getID(), //
node.getNodeSector(), //
node.getMinimumSector(), //
features //
);
_progress.stepDone();
return true;
}
}
public static void process(final File storageDir,
final String storageName,
final File lodDir,
final String lodName,
final int maxFeaturesPerNode,
final Comparator<PointFeature> featuresComparator,
final boolean createClusters,
final boolean verbose) throws IOException {
try (final PointFeatureStorage storage = PointFeatureMapDBStorage.openReadOnly(storageDir, storageName)) {
try (final PointFeatureLODStorage lodStorage = PointFeatureLODMapDBStorage.createEmpty(storage.getSector(), lodDir,
lodName, maxFeaturesPerNode, featuresComparator, createClusters)) {
final PointFeatureStorage.Statistics statistics = storage.getStatistics(verbose);
if (verbose) {
statistics.show();
System.out.println();
}
final int nodesCount = statistics.getNodesCount();
storage.acceptDepthFirstVisitor(new LeafNodesImporter(nodesCount, lodStorage, verbose));
lodStorage.createLOD(verbose);
if (verbose) {
System.out.println(lodStorage.getName() + ": 4/4 Optimizing storage...");
}
lodStorage.optimize();
if (verbose) {
System.out.println();
final PointFeatureLODStorage.Statistics lodStatistics = lodStorage.getStatistics(verbose);
lodStatistics.show();
}
}
}
}
private LODPointFeaturesPreprocessor() {
}
public static void main(final String[] args) throws IOException {
System.out.println("LODPointFeaturesPreprocessor 0.1");
System.out.println("--------------------------------\n");
final File sourceDir = new File("PointFeaturesStorage");
// final String sourceName = "Cities1000";
// final String sourceName = "AR";
// final String sourceName = "ES";
// final String sourceName = "GEONames-PopulatedPlaces";
// final String sourceName = "SpanishBars";
final String sourceName = "Tornados";
final File lodDir = new File("PointFeaturesLOD");
final String lodName = sourceName + "_LOD";
final int maxFeaturesPerNode = 64;
// final int maxFeaturesPerNode = 96;
final boolean createClusters = true;
final Comparator<PointFeature> featuresComparator = createClusters ? null : new GEONamesComparator();
final boolean verbose = true;
LODPointFeaturesPreprocessor.process( //
sourceDir, sourceName, //
lodDir, lodName, //
maxFeaturesPerNode, //
featuresComparator, //
createClusters, //
verbose);
System.out.println("\n- done!");
}
}
|
Java
|
// Copyright (C) 2018 Andrew Paprocki. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-date.parse
es6id: 20.3.3.2
description: >
Date.parse return value is limited to specified time value maximum range
info: |
Date.parse ( string )
parse interprets the resulting String as a date and time; it returns a
Number, the UTC time value corresponding to the date and time.
A Date object contains a Number indicating a particular instant in time to
within a millisecond. Such a Number is called a time value.
The actual range of times supported by ECMAScript Date objects is slightly
smaller: exactly -100,000,000 days to 100,000,000 days measured relative to
midnight at the beginning of 01 January, 1970 UTC. This gives a range of
8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
includes: [propertyHelper.js]
---*/
const minDateStr = "-271821-04-20T00:00:00.000Z";
const minDate = new Date(-8640000000000000);
assert.sameValue(minDate.toISOString(), minDateStr, "minDateStr");
assert.sameValue(Date.parse(minDateStr), minDate.valueOf(), "parse minDateStr");
const maxDateStr = "+275760-09-13T00:00:00.000Z";
const maxDate = new Date(8640000000000000);
assert.sameValue(maxDate.toISOString(), maxDateStr, "maxDateStr");
assert.sameValue(Date.parse(maxDateStr), maxDate.valueOf(), "parse maxDateStr");
const belowRange = "-271821-04-19T23:59:59.999Z";
const aboveRange = "+275760-09-13T00:00:00.001Z";
assert.sameValue(Date.parse(belowRange), NaN, "parse below minimum time value");
assert.sameValue(Date.parse(aboveRange), NaN, "parse above maximum time value");
|
Java
|
package ru.biocad.ig.alicont.conts.simple
import ru.biocad.ig.alicont.algorithms.simple.SemiglobalAlignment
import ru.biocad.ig.alicont.conts.SimpleAlicont
/**
* Created with IntelliJ IDEA.
* User: pavel
* Date: 27.11.13
* Time: 23:37
*/
class AlicontSemiglobal(maxheight : Int, query : String, gap : Double, score_matrix : Array[Array[Double]])
extends SimpleAlicont(maxheight : Int, query : String, gap : Double, score_matrix : Array[Array[Double]]) {
def push(s : String) : Unit = {
_strings.push(s)
SemiglobalAlignment.extendMatrix(s, _query, _gap, _score, _matrix)
}
def alignment() : (Double, (String, String)) = {
SemiglobalAlignment.traceback(target, _query, _gap, _score, _matrix)
}
}
|
Java
|
#include <catch.hpp>
#include <rapidcheck/catch.h>
using namespace rc;
TEST_CASE("scaleInteger") {
prop("for uint32_t, equal to naive way",
[] {
const auto x = *gen::arbitrary<uint32_t>();
const auto size = *gen::nonNegative<int>();
RC_ASSERT(gen::detail::scaleInteger(x, size) ==
((x * std::min<uint64_t>(kNominalSize, size) +
(kNominalSize / 2)) /
kNominalSize));
});
prop("result strictly increases with size",
[](uint64_t x) {
const auto sizeA = *gen::nonNegative<int>();
const auto sizeB = *gen::nonNegative<int>();
const auto small = std::min(sizeA, sizeB);
const auto large = std::max(sizeA, sizeB);
RC_ASSERT(gen::detail::scaleInteger(x, small) <=
gen::detail::scaleInteger(x, large));
});
prop("result strictly increases with value",
[](uint64_t a, uint64_t b){
const auto size = *gen::nonNegative<int>();
const auto small = std::min(a, b);
const auto large = std::max(a, b);
RC_ASSERT(gen::detail::scaleInteger(small, size) <=
gen::detail::scaleInteger(large, size));
});
prop("yields input for kNominalSize",
[](uint64_t x) {
RC_ASSERT(gen::detail::scaleInteger(x, kNominalSize) == x);
});
prop("yields 0 for 0",
[](uint64_t x) { RC_ASSERT(gen::detail::scaleInteger(x, 0) == 0U); });
}
|
Java
|
// ------------------------------------------------------------------------------
// <copyright from='2002' to='2002' company='Scott Hanselman'>
// Copyright (c) Scott Hanselman. All Rights Reserved.
// </copyright>
// ------------------------------------------------------------------------------
//
// Scott Hanselman's Tiny Academic Virtual CPU and OS
// Copyright (c) 2002, Scott Hanselman (scott@hanselman.com)
// All rights reserved.
//
// A BSD License
// 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 Scott Hanselman 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.
//
namespace Hanselman.CST352
{
using System;
using System.Collections;
/// <summary>
/// A collection that stores <see cref='Hanselman.CST352.Instruction'/> objects.
/// </summary>
/// <seealso cref='Hanselman.CST352.InstructionCollection'/>
[Serializable()]
public class InstructionCollection : CollectionBase {
/// <summary>
/// Initializes a new instance of <see cref='Hanselman.CST352.InstructionCollection'/>.
/// </summary>
public InstructionCollection() {
}
/// <summary>
/// Initializes a new instance of <see cref='Hanselman.CST352.InstructionCollection'/> based on another <see cref='Hanselman.CST352.InstructionCollection'/>.
/// </summary>
/// <param name='value'>
/// A <see cref='Hanselman.CST352.InstructionCollection'/> from which the contents are copied
/// </param>
public InstructionCollection(InstructionCollection value) {
this.AddRange(value);
}
/// <summary>
/// Initializes a new instance of <see cref='Hanselman.CST352.InstructionCollection'/> containing any array of <see cref='Hanselman.CST352.Instruction'/> objects.
/// </summary>
/// <param name='value'>
/// A array of <see cref='Hanselman.CST352.Instruction'/> objects with which to intialize the collection
/// </param>
public InstructionCollection(Instruction[] value) {
this.AddRange(value);
}
/// <summary>
/// Represents the entry at the specified index of the <see cref='Hanselman.CST352.Instruction'/>.
/// </summary>
/// <param name='index'>The zero-based index of the entry to locate in the collection.</param>
/// <value>
/// The entry at the specified index of the collection.
/// </value>
/// <exception cref='System.ArgumentOutOfRangeException'><paramref name='index'/> is outside the valid range of indexes for the collection.</exception>
public Instruction this[int index] {
get {
return ((Instruction)(List[index]));
}
set {
List[index] = value;
}
}
/// <summary>
/// Adds a <see cref='Hanselman.CST352.Instruction'/> with the specified value to the
/// <see cref='Hanselman.CST352.InstructionCollection'/> .
/// </summary>
/// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to add.</param>
/// <returns>
/// The index at which the new element was inserted.
/// </returns>
/// <seealso cref='Hanselman.CST352.InstructionCollection.AddRange(Instruction[])'/>
public int Add(Instruction value) {
return List.Add(value);
}
/// <summary>
/// Copies the elements of an array to the end of the <see cref='Hanselman.CST352.InstructionCollection'/>.
/// </summary>
/// <param name='value'>
/// An array of type <see cref='Hanselman.CST352.Instruction'/> containing the objects to add to the collection.
/// </param>
/// <returns>
/// None.
/// </returns>
/// <seealso cref='Hanselman.CST352.InstructionCollection.Add'/>
public void AddRange(Instruction[] value) {
for (int i = 0; (i < value.Length); i = (i + 1)) {
this.Add(value[i]);
}
}
/// <summary>
///
/// Adds the contents of another <see cref='Hanselman.CST352.InstructionCollection'/> to the end of the collection.
///
/// </summary>
/// <param name='value'>
/// A <see cref='Hanselman.CST352.InstructionCollection'/> containing the objects to add to the collection.
/// </param>
/// <returns>
/// None.
/// </returns>
/// <seealso cref='Hanselman.CST352.InstructionCollection.Add'/>
public void AddRange(InstructionCollection value) {
for (int i = 0; (i < value.Count); i = (i + 1)) {
this.Add(value[i]);
}
}
/// <summary>
/// Gets a value indicating whether the
/// <see cref='Hanselman.CST352.InstructionCollection'/> contains the specified <see cref='Hanselman.CST352.Instruction'/>.
/// </summary>
/// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to locate.</param>
/// <returns>
/// <see langword='true'/> if the <see cref='Hanselman.CST352.Instruction'/> is contained in the collection;
/// otherwise, <see langword='false'/>.
/// </returns>
/// <seealso cref='Hanselman.CST352.InstructionCollection.IndexOf'/>
public bool Contains(Instruction value) {
return List.Contains(value);
}
/// <summary>
/// Copies the <see cref='Hanselman.CST352.InstructionCollection'/> values to a one-dimensional <see cref='System.Array'/> instance at the
/// specified index.
/// </summary>
/// <param name='array'>The one-dimensional <see cref='System.Array'/> that is the destination of the values copied from <see cref='Hanselman.CST352.InstructionCollection'/> .</param>
/// <param name='index'>The index in <paramref name='array'/> where copying begins.</param>
/// <returns>
/// None.
/// </returns>
/// <exception cref='System.ArgumentException'><paramref name='array'/> is multidimensional. -or- The number of elements in the <see cref='Hanselman.CST352.InstructionCollection'/> is greater than the available space between <paramref name='index'/> and the end of <paramref name='array'/>.</exception>
/// <exception cref='System.ArgumentNullException'><paramref name='array'/> is <see langword='null'/>. </exception>
/// <exception cref='System.ArgumentOutOfRangeException'><paramref name='index'/> is less than <paramref name='array'/>'s lowbound. </exception>
/// <seealso cref='System.Array'/>
public void CopyTo(Instruction[] array, int index) {
List.CopyTo(array, index);
}
/// <summary>
/// Returns the index of a <see cref='Hanselman.CST352.Instruction'/> in
/// the <see cref='Hanselman.CST352.InstructionCollection'/> .
/// </summary>
/// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to locate.</param>
/// <returns>
/// The index of the <see cref='Hanselman.CST352.Instruction'/> of <paramref name='value'/> in the
/// <see cref='Hanselman.CST352.InstructionCollection'/>, if found; otherwise, -1.
/// </returns>
/// <seealso cref='Hanselman.CST352.InstructionCollection.Contains'/>
public int IndexOf(Instruction value) {
return List.IndexOf(value);
}
/// <summary>
/// Inserts a <see cref='Hanselman.CST352.Instruction'/> into the <see cref='Hanselman.CST352.InstructionCollection'/> at the specified index.
/// </summary>
/// <param name='index'>The zero-based index where <paramref name='value'/> should be inserted.</param>
/// <param name=' value'>The <see cref='Hanselman.CST352.Instruction'/> to insert.</param>
/// <returns>None.</returns>
/// <seealso cref='Hanselman.CST352.InstructionCollection.Add'/>
public void Insert(int index, Instruction value) {
List.Insert(index, value);
}
/// <summary>
/// Returns an enumerator that can iterate through
/// the <see cref='Hanselman.CST352.InstructionCollection'/> .
/// </summary>
/// <returns>None.</returns>
/// <seealso cref='System.Collections.IEnumerator'/>
public new InstructionEnumerator GetEnumerator() {
return new InstructionEnumerator(this);
}
/// <summary>
/// Removes a specific <see cref='Hanselman.CST352.Instruction'/> from the
/// <see cref='Hanselman.CST352.InstructionCollection'/> .
/// </summary>
/// <param name='value'>The <see cref='Hanselman.CST352.Instruction'/> to remove from the <see cref='Hanselman.CST352.InstructionCollection'/> .</param>
/// <returns>None.</returns>
/// <exception cref='System.ArgumentException'><paramref name='value'/> is not found in the Collection. </exception>
public void Remove(Instruction value) {
List.Remove(value);
}
/// <summary>
/// Provided for "foreach" support with this collection
/// </summary>
public class InstructionEnumerator : object, IEnumerator {
private IEnumerator baseEnumerator;
private IEnumerable temp;
/// <summary>
/// Public constructor for an InstructionEnumerator
/// </summary>
/// <param name="mappings">The <see cref="InstructionCollection"/>we are going to iterate over</param>
public InstructionEnumerator(InstructionCollection mappings) {
this.temp = ((IEnumerable)(mappings));
this.baseEnumerator = temp.GetEnumerator();
}
/// <summary>
/// The current <see cref="Instruction"/>
/// </summary>
public Instruction Current {
get {
return ((Instruction)(baseEnumerator.Current));
}
}
/// <summary>
/// The current IEnumerator interface
/// </summary>
object IEnumerator.Current {
get {
return baseEnumerator.Current;
}
}
/// <summary>
/// Move to the next Instruction
/// </summary>
/// <returns>true or false based on success</returns>
public bool MoveNext() {
return baseEnumerator.MoveNext();
}
/// <summary>
/// Move to the next Instruction
/// </summary>
/// <returns>true or false based on success</returns>
bool IEnumerator.MoveNext()
{
return baseEnumerator.MoveNext();
}
/// <summary>
/// Reset the cursor
/// </summary>
public void Reset()
{
baseEnumerator.Reset();
}
/// <summary>
/// Reset the cursor
/// </summary>
void IEnumerator.Reset()
{
baseEnumerator.Reset();
}
}
}
}
|
Java
|
#ifndef EXTRACTION_WAY_HPP
#define EXTRACTION_WAY_HPP
#include "extractor/guidance/road_classification.hpp"
#include "extractor/travel_mode.hpp"
#include "util/guidance/turn_lanes.hpp"
#include "util/typedefs.hpp"
#include <string>
#include <vector>
namespace osrm
{
namespace extractor
{
namespace detail
{
inline void maybeSetString(std::string &str, const char *value)
{
if (value == nullptr)
{
str.clear();
}
else
{
str = std::string(value);
}
}
}
/**
* This struct is the direct result of the call to ```way_function```
* in the lua based profile.
*
* It is split into multiple edge segments in the ExtractorCallback.
*/
struct ExtractionWay
{
ExtractionWay() { clear(); }
void clear()
{
forward_speed = -1;
backward_speed = -1;
forward_rate = -1;
backward_rate = -1;
duration = -1;
weight = -1;
name.clear();
ref.clear();
pronunciation.clear();
destinations.clear();
exits.clear();
turn_lanes_forward.clear();
turn_lanes_backward.clear();
road_classification = guidance::RoadClassification();
forward_travel_mode = TRAVEL_MODE_INACCESSIBLE;
backward_travel_mode = TRAVEL_MODE_INACCESSIBLE;
roundabout = false;
circular = false;
is_startpoint = true;
forward_restricted = false;
backward_restricted = false;
is_left_hand_driving = false;
}
// wrappers to allow assigning nil (nullptr) to string values
void SetName(const char *value) { detail::maybeSetString(name, value); }
const char *GetName() const { return name.c_str(); }
void SetRef(const char *value) { detail::maybeSetString(ref, value); }
const char *GetRef() const { return ref.c_str(); }
void SetDestinations(const char *value) { detail::maybeSetString(destinations, value); }
const char *GetDestinations() const { return destinations.c_str(); }
void SetExits(const char *value) { detail::maybeSetString(exits, value); }
const char *GetExits() const { return exits.c_str(); }
void SetPronunciation(const char *value) { detail::maybeSetString(pronunciation, value); }
const char *GetPronunciation() const { return pronunciation.c_str(); }
void SetTurnLanesForward(const char *value)
{
detail::maybeSetString(turn_lanes_forward, value);
}
const char *GetTurnLanesForward() const { return turn_lanes_forward.c_str(); }
void SetTurnLanesBackward(const char *value)
{
detail::maybeSetString(turn_lanes_backward, value);
}
const char *GetTurnLanesBackward() const { return turn_lanes_backward.c_str(); }
// markers for determining user-defined classes for each way
std::unordered_map<std::string, bool> forward_classes;
std::unordered_map<std::string, bool> backward_classes;
// speed in km/h
double forward_speed;
double backward_speed;
// weight per meter
double forward_rate;
double backward_rate;
// duration of the whole way in both directions
double duration;
// weight of the whole way in both directions
double weight;
std::string name;
std::string ref;
std::string pronunciation;
std::string destinations;
std::string exits;
std::string turn_lanes_forward;
std::string turn_lanes_backward;
guidance::RoadClassification road_classification;
TravelMode forward_travel_mode : 4;
TravelMode backward_travel_mode : 4;
// Boolean flags
bool roundabout : 1;
bool circular : 1;
bool is_startpoint : 1;
bool forward_restricted : 1;
bool backward_restricted : 1;
bool is_left_hand_driving : 1;
bool : 2;
};
}
}
#endif // EXTRACTION_WAY_HPP
|
Java
|
#include <math.h>
#include "evas_common.h"
#include "evas_blend_private.h"
typedef struct _RGBA_Span RGBA_Span;
typedef struct _RGBA_Edge RGBA_Edge;
typedef struct _RGBA_Vertex RGBA_Vertex;
struct _RGBA_Span
{
EINA_INLIST;
int x, y, w;
};
struct _RGBA_Edge
{
double x, dx;
int i;
};
struct _RGBA_Vertex
{
double x, y;
int i;
};
#define POLY_EDGE_DEL(_i) \
{ \
int _j; \
\
for (_j = 0; (_j < num_active_edges) && (edges[_j].i != _i); _j++); \
if (_j < num_active_edges) \
{ \
num_active_edges--; \
memmove(&(edges[_j]), &(edges[_j + 1]), \
(num_active_edges - _j) * sizeof(RGBA_Edge)); \
} \
}
#define POLY_EDGE_ADD(_i, _y) \
{ \
int _j; \
float _dx; \
RGBA_Vertex *_p, *_q; \
if (_i < (n - 1)) _j = _i + 1; \
else _j = 0; \
if (point[_i].y < point[_j].y) \
{ \
_p = &(point[_i]); \
_q = &(point[_j]); \
} \
else \
{ \
_p = &(point[_j]); \
_q = &(point[_i]); \
} \
edges[num_active_edges].dx = _dx = (_q->x - _p->x) / (_q->y - _p->y); \
edges[num_active_edges].x = (_dx * ((float)_y + 0.5 - _p->y)) + _p->x; \
edges[num_active_edges].i = _i; \
num_active_edges++; \
}
EAPI void
evas_common_polygon_init(void)
{
}
EAPI RGBA_Polygon_Point *
evas_common_polygon_point_add(RGBA_Polygon_Point *points, int x, int y)
{
RGBA_Polygon_Point *pt;
pt = malloc(sizeof(RGBA_Polygon_Point));
if (!pt) return points;
pt->x = x;
pt->y = y;
points = (RGBA_Polygon_Point *)eina_inlist_append(EINA_INLIST_GET(points), EINA_INLIST_GET(pt));
return points;
}
EAPI RGBA_Polygon_Point *
evas_common_polygon_points_clear(RGBA_Polygon_Point *points)
{
if (points)
{
while (points)
{
RGBA_Polygon_Point *old_p;
old_p = points;
points = (RGBA_Polygon_Point *)eina_inlist_remove(EINA_INLIST_GET(points), EINA_INLIST_GET(points));
free(old_p);
}
}
return NULL;
}
static int
polygon_point_sorter(const void *a, const void *b)
{
RGBA_Vertex *p, *q;
p = (RGBA_Vertex *)a;
q = (RGBA_Vertex *)b;
if (p->y <= q->y) return -1;
return 1;
}
static int
polygon_edge_sorter(const void *a, const void *b)
{
RGBA_Edge *p, *q;
p = (RGBA_Edge *)a;
q = (RGBA_Edge *)b;
if (p->x <= q->x) return -1;
return 1;
}
EAPI void
evas_common_polygon_draw(RGBA_Image *dst, RGBA_Draw_Context *dc, RGBA_Polygon_Point *points, int x, int y)
{
RGBA_Gfx_Func func;
RGBA_Polygon_Point *pt;
RGBA_Vertex *point;
RGBA_Edge *edges;
Eina_Inlist *spans;
int num_active_edges;
int n;
int i, j, k;
int y0, y1, yi;
int ext_x, ext_y, ext_w, ext_h;
int *sorted_index;
ext_x = 0;
ext_y = 0;
ext_w = dst->cache_entry.w;
ext_h = dst->cache_entry.h;
if (dc->clip.use)
{
if (dc->clip.x > ext_x)
{
ext_w += ext_x - dc->clip.x;
ext_x = dc->clip.x;
}
if ((ext_x + ext_w) > (dc->clip.x + dc->clip.w))
{
ext_w = (dc->clip.x + dc->clip.w) - ext_x;
}
if (dc->clip.y > ext_y)
{
ext_h += ext_y - dc->clip.y;
ext_y = dc->clip.y;
}
if ((ext_y + ext_h) > (dc->clip.y + dc->clip.h))
{
ext_h = (dc->clip.y + dc->clip.h) - ext_y;
}
}
if ((ext_w <= 0) || (ext_h <= 0)) return;
evas_common_cpu_end_opt();
n = 0; EINA_INLIST_FOREACH(points, pt) n++;
if (n < 3) return;
edges = malloc(sizeof(RGBA_Edge) * n);
if (!edges) return;
point = malloc(sizeof(RGBA_Vertex) * n);
if (!point)
{
free(edges);
return;
}
sorted_index = malloc(sizeof(int) * n);
if (!sorted_index)
{
free(edges);
free(point);
return;
}
k = 0;
EINA_INLIST_FOREACH(points, pt)
{
point[k].x = pt->x + x;
point[k].y = pt->y + y;
point[k].i = k;
k++;
}
qsort(point, n, sizeof(RGBA_Vertex), polygon_point_sorter);
for (k = 0; k < n; k++) sorted_index[k] = point[k].i;
k = 0;
EINA_INLIST_FOREACH(points, pt)
{
point[k].x = pt->x + x;
point[k].y = pt->y + y;
point[k].i = k;
k++;
}
y0 = MAX(ext_y, ceil(point[sorted_index[0]].y - 0.5));
y1 = MIN(ext_y + ext_h - 1, floor(point[sorted_index[n - 1]].y - 0.5));
k = 0;
num_active_edges = 0;
spans = NULL;
for (yi = y0; yi <= y1; yi++)
{
for (; (k < n) && (point[sorted_index[k]].y <= ((double)yi + 0.5)); k++)
{
i = sorted_index[k];
if (i > 0) j = i - 1;
else j = n - 1;
if (point[j].y <= ((double)yi - 0.5))
{
POLY_EDGE_DEL(j)
}
else if (point[j].y > ((double)yi + 0.5))
{
POLY_EDGE_ADD(j, yi)
}
if (i < (n - 1)) j = i + 1;
else j = 0;
if (point[j].y <= ((double)yi - 0.5))
{
POLY_EDGE_DEL(i)
}
else if (point[j].y > ((double)yi + 0.5))
{
POLY_EDGE_ADD(i, yi)
}
}
qsort(edges, num_active_edges, sizeof(RGBA_Edge), polygon_edge_sorter);
for (j = 0; j < num_active_edges; j += 2)
{
int x0, x1;
x0 = ceil(edges[j].x - 0.5);
if (j < (num_active_edges - 1))
x1 = floor(edges[j + 1].x - 0.5);
else
x1 = x0;
if ((x1 >= ext_x) && (x0 < (ext_x + ext_w)) && (x0 <= x1))
{
RGBA_Span *span;
if (x0 < ext_x) x0 = ext_x;
if (x1 >= (ext_x + ext_w)) x1 = ext_x + ext_w - 1;
span = malloc(sizeof(RGBA_Span));
spans = eina_inlist_append(spans, EINA_INLIST_GET(span));
span->y = yi;
span->x = x0;
span->w = (x1 - x0) + 1;
}
edges[j].x += edges[j].dx;
edges[j + 1].x += edges[j + 1].dx;
}
}
free(edges);
free(point);
free(sorted_index);
func = evas_common_gfx_func_composite_color_span_get(dc->col.col, dst, 1, dc->render_op);
if (spans)
{
RGBA_Span *span;
EINA_INLIST_FOREACH(spans, span)
{
DATA32 *ptr;
#ifdef EVAS_SLI
if (((span->y) % dc->sli.h) == dc->sli.y)
#endif
{
ptr = dst->image.data + (span->y * (dst->cache_entry.w)) + span->x;
func(NULL, NULL, dc->col.col, ptr, span->w);
}
}
while (spans)
{
span = (RGBA_Span *)spans;
spans = eina_inlist_remove(spans, spans);
free(span);
}
}
}
|
Java
|
/*
* Copyright (c) 2013 Ambroz Bizjak
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
*
* 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 AUTHOR 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.
*/
#ifndef AMBROLIB_STRUCT_IF_H
#define AMBROLIB_STRUCT_IF_H
namespace APrinter {
#define AMBRO_STRUCT_IF(name, condition) \
template <bool name##__IfEnable, typename name##__IfDummy = void> \
struct name##__impl {}; \
using name = name##__impl<(condition)>; \
template <typename name##__IfDummy> \
struct name##__impl <true, name##__IfDummy>
#define AMBRO_STRUCT_ELSE(name) \
; template <typename name##__IfDummy> \
struct name##__impl <false, name##__IfDummy>
#define APRINTER_STRUCT_IF_TEMPLATE(name) \
template <bool name##__IfEnable, typename name##__IfDummy = void> \
struct name {}; \
template <typename name##__IfDummy> \
struct name <true, name##__IfDummy>
}
#endif
|
Java
|
/* Copyright (c) Citrix Systems Inc.
* All rights reserved.
*
* 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.
*
* 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 HOLDER 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.
*/
#include <ntddk.h>
#include <xen.h>
#include <util.h>
#include "hypercall.h"
#include "dbg_print.h"
#include "assert.h"
#define MAXIMUM_HYPERCALL_PFN_COUNT 2
#pragma code_seg("hypercall")
__declspec(allocate("hypercall"))
static UCHAR __Section[(MAXIMUM_HYPERCALL_PFN_COUNT + 1) * PAGE_SIZE];
static ULONG XenBaseLeaf = 0x40000000;
static USHORT XenMajorVersion;
static USHORT XenMinorVersion;
static PFN_NUMBER HypercallPfn[MAXIMUM_HYPERCALL_PFN_COUNT];
static ULONG HypercallPfnCount;
typedef UCHAR HYPERCALL_GATE[32];
typedef HYPERCALL_GATE *PHYPERCALL_GATE;
PHYPERCALL_GATE Hypercall;
NTSTATUS
HypercallInitialize(
VOID
)
{
ULONG EAX = 'DEAD';
ULONG EBX = 'DEAD';
ULONG ECX = 'DEAD';
ULONG EDX = 'DEAD';
ULONG Index;
ULONG HypercallMsr;
NTSTATUS status;
status = STATUS_UNSUCCESSFUL;
for (;;) {
CHAR Signature[13] = {0};
__CpuId(XenBaseLeaf, &EAX, &EBX, &ECX, &EDX);
*((PULONG)(Signature + 0)) = EBX;
*((PULONG)(Signature + 4)) = ECX;
*((PULONG)(Signature + 8)) = EDX;
if (strcmp(Signature, "XenVMMXenVMM") == 0 &&
EAX >= XenBaseLeaf + 2)
break;
XenBaseLeaf += 0x100;
if (XenBaseLeaf > 0x40000100)
goto fail1;
}
__CpuId(XenBaseLeaf + 1, &EAX, NULL, NULL, NULL);
XenMajorVersion = (USHORT)(EAX >> 16);
XenMinorVersion = (USHORT)(EAX & 0xFFFF);
Info("XEN %d.%d\n", XenMajorVersion, XenMinorVersion);
Info("INTERFACE 0x%08x\n", __XEN_INTERFACE_VERSION__);
if ((ULONG_PTR)__Section & (PAGE_SIZE - 1))
Hypercall = (PVOID)(((ULONG_PTR)__Section + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1));
else
Hypercall = (PVOID)__Section;
ASSERT3U(((ULONG_PTR)Hypercall & (PAGE_SIZE - 1)), ==, 0);
for (Index = 0; Index < MAXIMUM_HYPERCALL_PFN_COUNT; Index++) {
PHYSICAL_ADDRESS PhysicalAddress;
PhysicalAddress = MmGetPhysicalAddress((PUCHAR)Hypercall + (Index << PAGE_SHIFT));
HypercallPfn[Index] = (PFN_NUMBER)(PhysicalAddress.QuadPart >> PAGE_SHIFT);
}
__CpuId(XenBaseLeaf + 2, &EAX, &EBX, NULL, NULL);
HypercallPfnCount = EAX;
ASSERT(HypercallPfnCount <= MAXIMUM_HYPERCALL_PFN_COUNT);
HypercallMsr = EBX;
for (Index = 0; Index < HypercallPfnCount; Index++) {
Info("HypercallPfn[%d]: %p\n", Index, (PVOID)HypercallPfn[Index]);
__writemsr(HypercallMsr, (ULONG64)HypercallPfn[Index] << PAGE_SHIFT);
}
return STATUS_SUCCESS;
fail1:
Error("fail1 (%08x)", status);
return status;
}
extern uintptr_t __stdcall hypercall_gate_2(uint32_t ord, uintptr_t arg1, uintptr_t arg2);
ULONG_PTR
__Hypercall2(
ULONG Ordinal,
ULONG_PTR Argument1,
ULONG_PTR Argument2
)
{
return hypercall_gate_2(Ordinal, Argument1, Argument2);
}
extern uintptr_t __stdcall hypercall_gate_3(uint32_t ord, uintptr_t arg1, uintptr_t arg2, uintptr_t arg3);
ULONG_PTR
__Hypercall3(
ULONG Ordinal,
ULONG_PTR Argument1,
ULONG_PTR Argument2,
ULONG_PTR Argument3
)
{
return hypercall_gate_3(Ordinal, Argument1, Argument2, Argument3);
}
VOID
HypercallTeardown(
VOID
)
{
ULONG Index;
Hypercall = NULL;
for (Index = 0; Index < MAXIMUM_HYPERCALL_PFN_COUNT; Index++)
HypercallPfn[Index] = 0;
HypercallPfnCount = 0;
}
|
Java
|
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# 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.
#
# 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 HOLDER 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.
# *****************************************************************************
import itertools
import numba
import numpy as np
import os
import pandas as pd
import pyarrow.parquet as pq
import random
import string
import unittest
from numba import types
import sdc
from sdc import hiframes
from sdc.str_arr_ext import StringArray
from sdc.tests.test_base import TestCase
from sdc.tests.test_utils import (count_array_OneDs,
count_array_REPs,
count_parfor_OneDs,
count_parfor_REPs,
dist_IR_contains,
get_start_end,
skip_numba_jit,
skip_sdc_jit)
class TestHiFrames(TestCase):
@skip_numba_jit
def test_column_list_select2(self):
# make sure SDC copies the columns like Pandas does
def test_impl(df):
df2 = df[['A']]
df2['A'] += 10
return df2.A, df.A
hpat_func = self.jit(test_impl)
n = 11
df = pd.DataFrame(
{'A': np.arange(n), 'B': np.ones(n), 'C': np.random.ranf(n)})
np.testing.assert_array_equal(hpat_func(df.copy())[1], test_impl(df)[1])
@skip_numba_jit
def test_pd_DataFrame_from_series_par(self):
def test_impl(n):
S1 = pd.Series(np.ones(n))
S2 = pd.Series(np.random.ranf(n))
df = pd.DataFrame({'A': S1, 'B': S2})
return df.A.sum()
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
self.assertEqual(count_parfor_OneDs(), 1)
@skip_numba_jit
def test_getitem_bool_series(self):
def test_impl(df):
return df['A'][df['B']].values
hpat_func = self.jit(test_impl)
df = pd.DataFrame({'A': [1, 2, 3], 'B': [True, False, True]})
np.testing.assert_array_equal(test_impl(df), hpat_func(df))
@skip_numba_jit
def test_fillna(self):
def test_impl():
A = np.array([1., 2., 3.])
A[0] = np.nan
df = pd.DataFrame({'A': A})
B = df.A.fillna(5.0)
return B.sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
@skip_numba_jit
def test_fillna_inplace(self):
def test_impl():
A = np.array([1., 2., 3.])
A[0] = np.nan
df = pd.DataFrame({'A': A})
df.A.fillna(5.0, inplace=True)
return df.A.sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
@skip_numba_jit
def test_column_mean(self):
def test_impl():
A = np.array([1., 2., 3.])
A[0] = np.nan
df = pd.DataFrame({'A': A})
return df.A.mean()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
@skip_numba_jit
def test_column_var(self):
def test_impl():
A = np.array([1., 2., 3.])
A[0] = 4.0
df = pd.DataFrame({'A': A})
return df.A.var()
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(), test_impl())
@skip_numba_jit
def test_column_std(self):
def test_impl():
A = np.array([1., 2., 3.])
A[0] = 4.0
df = pd.DataFrame({'A': A})
return df.A.std()
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(), test_impl())
@skip_numba_jit
def test_column_map(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n)})
df['B'] = df.A.map(lambda a: 2 * a)
return df.B.sum()
n = 121
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
@skip_numba_jit
def test_column_map_arg(self):
def test_impl(df):
df['B'] = df.A.map(lambda a: 2 * a)
return
n = 121
df1 = pd.DataFrame({'A': np.arange(n)})
df2 = pd.DataFrame({'A': np.arange(n)})
hpat_func = self.jit(test_impl)
hpat_func(df1)
self.assertTrue(hasattr(df1, 'B'))
test_impl(df2)
np.testing.assert_equal(df1.B.values, df2.B.values)
@skip_numba_jit
@skip_sdc_jit('Not implemented in sequential transport layer')
def test_cumsum(self):
def test_impl(n):
df = pd.DataFrame({'A': np.ones(n), 'B': np.random.ranf(n)})
Ac = df.A.cumsum()
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_array_OneDs(), 2)
self.assertEqual(count_parfor_REPs(), 0)
self.assertEqual(count_parfor_OneDs(), 2)
self.assertTrue(dist_IR_contains('dist_cumsum'))
@skip_numba_jit
@skip_sdc_jit('Not implemented in sequential transport layer')
def test_column_distribution(self):
# make sure all column calls are distributed
def test_impl(n):
df = pd.DataFrame({'A': np.ones(n), 'B': np.random.ranf(n)})
df.A.fillna(5.0, inplace=True)
DF = df.A.fillna(5.0)
s = DF.sum()
m = df.A.mean()
v = df.A.var()
t = df.A.std()
Ac = df.A.cumsum()
return Ac.sum() + s + m + v + t
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
self.assertTrue(dist_IR_contains('dist_cumsum'))
@skip_numba_jit
@skip_sdc_jit('Not implemented in sequential transport layer')
def test_quantile_parallel(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(0, n, 1, np.float64)})
return df.A.quantile(.25)
hpat_func = self.jit(test_impl)
n = 1001
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@unittest.skip('Error - fix needed\n'
'NUMA_PES=3 build')
def test_quantile_parallel_float_nan(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(0, n, 1, np.float32)})
df.A[0:100] = np.nan
df.A[200:331] = np.nan
return df.A.quantile(.25)
hpat_func = self.jit(test_impl)
n = 1001
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@unittest.skip('Error - fix needed\n'
'NUMA_PES=3 build')
def test_quantile_parallel_int(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(0, n, 1, np.int32)})
return df.A.quantile(.25)
hpat_func = self.jit(test_impl)
n = 1001
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@unittest.skip('Error - fix needed\n'
'NUMA_PES=3 build')
def test_quantile_sequential(self):
def test_impl(A):
df = pd.DataFrame({'A': A})
return df.A.quantile(.25)
hpat_func = self.jit(test_impl)
n = 1001
A = np.arange(0, n, 1, np.float64)
np.testing.assert_almost_equal(hpat_func(A), test_impl(A))
@skip_numba_jit
def test_nunique(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n)})
df.A[2] = 0
return df.A.nunique()
hpat_func = self.jit(test_impl)
n = 1001
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
# test compile again for overload related issues
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
@skip_numba_jit
def test_nunique_parallel(self):
# TODO: test without file
def test_impl():
df = pq.read_table('example.parquet').to_pandas()
return df.four.nunique()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
# test compile again for overload related issues
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
@skip_numba_jit
def test_nunique_str(self):
def test_impl(n):
df = pd.DataFrame({'A': ['aa', 'bb', 'aa', 'cc', 'cc']})
return df.A.nunique()
hpat_func = self.jit(test_impl)
n = 1001
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
# test compile again for overload related issues
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
@unittest.skip('AssertionError - fix needed\n'
'5 != 3\n')
def test_nunique_str_parallel(self):
# TODO: test without file
def test_impl():
df = pq.read_table('example.parquet').to_pandas()
return df.two.nunique()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
# test compile again for overload related issues
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
@skip_numba_jit
def test_unique_parallel(self):
# TODO: test without file
def test_impl():
df = pq.read_table('example.parquet').to_pandas()
return (df.four.unique() == 3.0).sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
@unittest.skip('AssertionError - fix needed\n'
'2 != 1\n')
def test_unique_str_parallel(self):
# TODO: test without file
def test_impl():
df = pq.read_table('example.parquet').to_pandas()
return (df.two.unique() == 'foo').sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
@skip_numba_jit
@skip_sdc_jit('Not implemented in sequential transport layer')
def test_describe(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(0, n, 1, np.float64)})
return df.A.describe()
hpat_func = self.jit(test_impl)
n = 1001
hpat_func(n)
# XXX: test actual output
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_str_contains_regex(self):
def test_impl():
A = StringArray(['ABC', 'BB', 'ADEF'])
df = pd.DataFrame({'A': A})
B = df.A.str.contains('AB*', regex=True)
return B.sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), 2)
@skip_numba_jit
def test_str_contains_noregex(self):
def test_impl():
A = StringArray(['ABC', 'BB', 'ADEF'])
df = pd.DataFrame({'A': A})
B = df.A.str.contains('BB', regex=False)
return B.sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), 1)
@skip_numba_jit
def test_str_replace_regex(self):
def test_impl(df):
return df.A.str.replace('AB*', 'EE', regex=True)
df = pd.DataFrame({'A': ['ABCC', 'CABBD']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_replace_noregex(self):
def test_impl(df):
return df.A.str.replace('AB', 'EE', regex=False)
df = pd.DataFrame({'A': ['ABCC', 'CABBD']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_replace_regex_parallel(self):
def test_impl(df):
B = df.A.str.replace('AB*', 'EE', regex=True)
return B
n = 5
A = ['ABCC', 'CABBD', 'CCD', 'CCDAABB', 'ED']
start, end = get_start_end(n)
df = pd.DataFrame({'A': A[start:end]})
hpat_func = self.jit(distributed={'df', 'B'})(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
self.assertEqual(count_array_REPs(), 3)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_str_split(self):
def test_impl(df):
return df.A.str.split(',')
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D', 'G', '', 'g,f']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_split_default(self):
def test_impl(df):
return df.A.str.split()
df = pd.DataFrame({'A': ['AB CC', 'C ABB D', 'G ', ' ', 'g\t f']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_split_filter(self):
def test_impl(df):
B = df.A.str.split(',')
df2 = pd.DataFrame({'B': B})
return df2[df2.B.str.len() > 1]
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D', 'G', '', 'g,f']})
hpat_func = self.jit(test_impl)
pd.testing.assert_frame_equal(
hpat_func(df), test_impl(df).reset_index(drop=True))
@skip_numba_jit
def test_str_split_box_df(self):
def test_impl(df):
return pd.DataFrame({'B': df.A.str.split(',')})
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df).B, test_impl(df).B, check_names=False)
@skip_numba_jit
def test_str_split_unbox_df(self):
def test_impl(df):
return df.A.iloc[0]
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D']})
df2 = pd.DataFrame({'A': df.A.str.split(',')})
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(df2), test_impl(df2))
@unittest.skip('Getitem Series with list values not implement')
def test_str_split_bool_index(self):
def test_impl(df):
C = df.A.str.split(',')
return C[df.B == 'aa']
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D'], 'B': ['aa', 'bb']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_split_parallel(self):
def test_impl(df):
B = df.A.str.split(',')
return B
n = 5
start, end = get_start_end(n)
A = ['AB,CC', 'C,ABB,D', 'CAD', 'CA,D', 'AA,,D']
df = pd.DataFrame({'A': A[start:end]})
hpat_func = self.jit(distributed={'df', 'B'})(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
self.assertEqual(count_array_REPs(), 3)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_str_get(self):
def test_impl(df):
B = df.A.str.split(',')
return B.str.get(1)
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_split(self):
def test_impl(df):
return df.A.str.split(',')
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_get_parallel(self):
def test_impl(df):
A = df.A.str.split(',')
B = A.str.get(1)
return B
n = 5
start, end = get_start_end(n)
A = ['AB,CC', 'C,ABB,D', 'CAD,F', 'CA,D', 'AA,,D']
df = pd.DataFrame({'A': A[start:end]})
hpat_func = self.jit(distributed={'df', 'B'})(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
self.assertEqual(count_array_REPs(), 3)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_str_get_to_numeric(self):
def test_impl(df):
B = df.A.str.split(',')
C = pd.to_numeric(B.str.get(1), errors='coerce')
return C
df = pd.DataFrame({'A': ['AB,12', 'C,321,D']})
hpat_func = self.jit(locals={'C': types.int64[:]})(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_flatten(self):
def test_impl(df):
A = df.A.str.split(',')
return pd.Series(list(itertools.chain(*A)))
df = pd.DataFrame({'A': ['AB,CC', 'C,ABB,D']})
hpat_func = self.jit(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_str_flatten_parallel(self):
def test_impl(df):
A = df.A.str.split(',')
B = pd.Series(list(itertools.chain(*A)))
return B
n = 5
start, end = get_start_end(n)
A = ['AB,CC', 'C,ABB,D', 'CAD', 'CA,D', 'AA,,D']
df = pd.DataFrame({'A': A[start:end]})
hpat_func = self.jit(distributed={'df', 'B'})(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
self.assertEqual(count_array_REPs(), 3)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_to_numeric(self):
def test_impl(df):
B = pd.to_numeric(df.A, errors='coerce')
return B
df = pd.DataFrame({'A': ['123.1', '331.2']})
hpat_func = self.jit(locals={'B': types.float64[:]})(test_impl)
pd.testing.assert_series_equal(
hpat_func(df), test_impl(df), check_names=False)
@skip_numba_jit
def test_1D_Var_len(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n), 'B': np.arange(n) + 1.0})
df1 = df[df.A > 5]
return len(df1.B)
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_rolling1(self):
# size 3 without unroll
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n), 'B': np.random.ranf(n)})
Ac = df.A.rolling(3).sum()
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 121
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
# size 7 with unroll
def test_impl_2(n):
df = pd.DataFrame({'A': np.arange(n) + 1.0, 'B': np.random.ranf(n)})
Ac = df.A.rolling(7).sum()
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 121
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_rolling2(self):
def test_impl(n):
df = pd.DataFrame({'A': np.ones(n), 'B': np.random.ranf(n)})
df['moving average'] = df.A.rolling(window=5, center=True).mean()
return df['moving average'].sum()
hpat_func = self.jit(test_impl)
n = 121
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_rolling3(self):
def test_impl(n):
df = pd.DataFrame({'A': np.ones(n), 'B': np.random.ranf(n)})
Ac = df.A.rolling(3, center=True).apply(lambda a: a[0] + 2 * a[1] + a[2])
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 121
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@unittest.skip('Error - fix needed\n'
'NUMA_PES=3 build')
def test_shift1(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n) + 1.0, 'B': np.random.ranf(n)})
Ac = df.A.shift(1)
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@unittest.skip('Error - fix needed\n'
'NUMA_PES=3 build')
def test_shift2(self):
def test_impl(n):
df = pd.DataFrame({'A': np.arange(n) + 1.0, 'B': np.random.ranf(n)})
Ac = df.A.pct_change(1)
return Ac.sum()
hpat_func = self.jit(test_impl)
n = 11
np.testing.assert_almost_equal(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_df_input(self):
def test_impl(df):
return df.B.sum()
n = 121
df = pd.DataFrame({'A': np.ones(n), 'B': np.random.ranf(n)})
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(df), test_impl(df))
@skip_numba_jit
def test_df_input2(self):
def test_impl(df):
C = df.B == 'two'
return C.sum()
n = 11
df = pd.DataFrame({'A': np.random.ranf(3 * n), 'B': ['one', 'two', 'three'] * n})
hpat_func = self.jit(test_impl)
np.testing.assert_almost_equal(hpat_func(df), test_impl(df))
@skip_numba_jit
def test_df_input_dist1(self):
def test_impl(df):
return df.B.sum()
n = 121
A = [3, 4, 5, 6, 1]
B = [5, 6, 2, 1, 3]
n = 5
start, end = get_start_end(n)
df = pd.DataFrame({'A': A, 'B': B})
df_h = pd.DataFrame({'A': A[start:end], 'B': B[start:end]})
hpat_func = self.jit(distributed={'df'})(test_impl)
np.testing.assert_almost_equal(hpat_func(df_h), test_impl(df))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_concat(self):
def test_impl(n):
df1 = pd.DataFrame({'key1': np.arange(n), 'A': np.arange(n) + 1.0})
df2 = pd.DataFrame({'key2': n - np.arange(n), 'A': n + np.arange(n) + 1.0})
df3 = pd.concat([df1, df2])
return df3.A.sum() + df3.key2.sum()
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
n = 11111
self.assertEqual(hpat_func(n), test_impl(n))
@skip_numba_jit
def test_concat_str(self):
def test_impl():
df1 = pq.read_table('example.parquet').to_pandas()
df2 = pq.read_table('example.parquet').to_pandas()
A3 = pd.concat([df1, df2])
return (A3.two == 'foo').sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
def test_concat_series(self):
def test_impl(n):
df1 = pd.DataFrame({'key1': np.arange(n), 'A': np.arange(n) + 1.0})
df2 = pd.DataFrame({'key2': n - np.arange(n), 'A': n + np.arange(n) + 1.0})
A3 = pd.concat([df1.A, df2.A])
return A3.sum()
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
n = 11111
self.assertEqual(hpat_func(n), test_impl(n))
@skip_numba_jit
def test_concat_series_str(self):
def test_impl():
df1 = pq.read_table('example.parquet').to_pandas()
df2 = pq.read_table('example.parquet').to_pandas()
A3 = pd.concat([df1.two, df2.two])
return (A3 == 'foo').sum()
hpat_func = self.jit(test_impl)
self.assertEqual(hpat_func(), test_impl())
self.assertEqual(count_array_REPs(), 0)
self.assertEqual(count_parfor_REPs(), 0)
@skip_numba_jit
@unittest.skipIf(int(os.getenv('SDC_NP_MPI', '0')) > 1, 'Test hangs on NP=2 and NP=3 on all platforms')
def test_intraday(self):
def test_impl(nsyms):
max_num_days = 100
all_res = 0.0
for i in sdc.prange(nsyms):
s_open = 20 * np.ones(max_num_days)
s_low = 28 * np.ones(max_num_days)
s_close = 19 * np.ones(max_num_days)
df = pd.DataFrame({'Open': s_open, 'Low': s_low, 'Close': s_close})
df['Stdev'] = df['Close'].rolling(window=90).std()
df['Moving Average'] = df['Close'].rolling(window=20).mean()
df['Criteria1'] = (df['Open'] - df['Low'].shift(1)) < -df['Stdev']
df['Criteria2'] = df['Open'] > df['Moving Average']
df['BUY'] = df['Criteria1'] & df['Criteria2']
df['Pct Change'] = (df['Close'] - df['Open']) / df['Open']
df['Rets'] = df['Pct Change'][df['BUY']]
all_res += df['Rets'].mean()
return all_res
hpat_func = self.jit(test_impl)
n = 11
self.assertEqual(hpat_func(n), test_impl(n))
self.assertEqual(count_array_OneDs(), 0)
self.assertEqual(count_parfor_OneDs(), 1)
@skip_numba_jit
def test_var_dist1(self):
def test_impl(A, B):
df = pd.DataFrame({'A': A, 'B': B})
df2 = df.groupby('A', as_index=False)['B'].sum()
# TODO: fix handling of df setitem to force match of array dists
# probably with a new node that is appended to the end of basic block
# df2['C'] = np.full(len(df2.B), 3, np.int8)
# TODO: full_like for Series
df2['C'] = np.full_like(df2.B.values, 3, np.int8)
return df2
A = np.array([1, 1, 2, 3])
B = np.array([3, 4, 5, 6])
hpat_func = self.jit(locals={'A:input': 'distributed',
'B:input': 'distributed', 'df2:return': 'distributed'})(test_impl)
start, end = get_start_end(len(A))
df2 = hpat_func(A[start:end], B[start:end])
# TODO:
# pd.testing.assert_frame_equal(
# hpat_func(A[start:end], B[start:end]), test_impl(A, B))
if __name__ == "__main__":
unittest.main()
|
Java
|
---@module fimbul.v35.material_template
local material_template = {}
function material_template:new(y)
local neu = y or {}
-- Do a deep resolve
if neu.material then
neu = neu.material
end
setmetatable(neu, self)
self.__index = self
neu.templatetype = "material"
-- TODO: Check if everything is here and in proper order
-- neu:check()
return neu
end
return material_template
|
Java
|
var crypto = require('crypto');
var Canvas = require('canvas');
var _ = require('lodash');
var bu = require('./bufutil');
var fmt = require('util').format;
var unpack = require('./unpack');
var bright = require('./bright');
function fprint(buf, len) {
if (len > 64)
throw new Error(fmt("sha512 can only generate 64B of data: %dB requested", len));
return _(crypto.createHash('sha512').update(buf).digest())
.groupBy(function (x, k) { return Math.floor(k/len); })
.reduce(bu.xor);
}
function idhash(str, n, minFill, maxFill) {
var buf = new Buffer(str.length + 1);
buf.write(str);
for (var i=0; i<0x100; i++) {
buf[buf.length - 1] = i;
var f = fprint(buf, Math.ceil(n/8)+6);
var pixels = _(f.slice(6))
.map(function (x) { return unpack(x); })
.flatten().take(n);
var setPixels = pixels.filter().size();
var c = [ f.slice(0, 3), f.slice(3, 6)];
c.sort(bright.cmp);
if (setPixels > (minFill * n) && setPixels < (maxFill * n))
return {
colors: c.map(function (x) { return x.toString('hex'); }),
pixels: pixels.value()
};
}
throw new Error(fmt("String '''%s''' unhashable in single-byte search space.", str));
}
function reflect(id, dimension) {
var mid = Math.ceil(dimension / 2);
var odd = Boolean(dimension % 2);
var pic = [];
for (var row=0; row<dimension; row++) {
pic[row] = [];
for (var col=0; col<dimension; col++) {
var p = (row * mid) + col;
if (col>=mid) {
var d = mid - (odd ? 1 : 0) - col;
var ad = Math.abs(d);
p = (row * mid) + mid - 1 - ad;
}
pic[row][col] = id.pixels[p];
// console.error(fmt("looking for %d, of %d for %d,%d", p, id.pixels.length, row, col))
}
}
return pic;
}
function retricon(str, opts) {
opts = _.merge({}, retricon.defaults, opts);
var dimension = opts.tiles;
var pixelSize = opts.pixelSize;
var border = opts.pixelPadding;
var mid = Math.ceil(dimension / 2);
var id = idhash(str, mid * dimension, opts.minFill, opts.maxFill);
var pic = reflect(id, dimension);
var csize = (pixelSize * dimension) + (opts.imagePadding * 2);
var c = Canvas.createCanvas(csize, csize);
var ctx = c.getContext('2d');
if (_.isString(opts.bgColor)) {
ctx.fillStyle = opts.bgColor;
} else if (_.isNumber(opts.bgColor)) {
ctx.fillStyle = '#' + id.colors[opts.bgColor];
}
if (! _.isNull(opts.bgColor))
ctx.fillRect(0, 0, csize, csize);
var drawOp = ctx.fillRect.bind(ctx);
if (_.isString(opts.pixelColor)) {
ctx.fillStyle = opts.pixelColor;
} else if (_.isNumber(opts.pixelColor)) {
ctx.fillStyle = '#' + id.colors[opts.pixelColor];
} else {
drawOp = ctx.clearRect.bind(ctx);
}
for (var x=0; x<dimension; x++)
for (var y=0; y<dimension; y++)
if (pic[y][x])
drawOp((x*pixelSize) + border + opts.imagePadding,
(y*pixelSize) + border + opts.imagePadding,
pixelSize - (border * 2),
pixelSize - (border * 2));
return c;
}
retricon.defaults = {
pixelSize: 10,
bgColor: null,
pixelPadding: 0,
imagePadding: 0,
tiles: 5,
minFill: 0.3,
maxFill: 0.90,
pixelColor: 0
};
retricon.style = {
github: {
pixelSize: 70,
bgColor: '#F0F0F0',
pixelPadding: -1,
imagePadding: 35,
tiles: 5
},
gravatar: {
tiles: 8,
bgColor: 1
},
mono: {
bgColor: '#F0F0F0',
pixelColor: '#000000',
tiles: 6,
pixelSize: 12,
pixelPadding: -1,
imagePadding: 6
},
mosaic: {
imagePadding: 2,
pixelPadding: 1,
pixelSize: 16,
bgColor: '#F0F0F0'
},
mini: {
pixelSize: 10,
pixelPadding: 1,
tiles: 3,
bgColor: 0,
pixelColor: 1
},
window: {
pixelColor: null,
bgColor: 0,
imagePadding: 2,
pixelPadding: 1,
pixelSize: 16
}
};
module.exports = retricon;
|
Java
|
<?php
namespace AppZap\PHPFramework\Tests\Functional\Testapp\Controller;
use AppZap\PHPFramework\Mvc\AbstractController;
class IndexController extends AbstractController {
/**
* @return string
*/
public function cli() {
return '';
}
}
|
Java
|
#include <mscorlib/System/Runtime/Serialization/mscorlib_System_Runtime_Serialization_SerializationObjectManager.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/mscorlib_System_String.h>
namespace mscorlib
{
namespace System
{
namespace Runtime
{
namespace Serialization
{
//Public Methods
void SerializationObjectManager::RegisterObject(mscorlib::System::Object obj)
{
MonoType *__parameter_types__[1];
void *__parameters__[1];
__parameter_types__[0] = Global::GetType(typeid(obj).name());
__parameters__[0] = (MonoObject*)obj;
Global::InvokeMethod("mscorlib", "System.Runtime.Serialization", "SerializationObjectManager", 0, NULL, "RegisterObject", __native_object__, 1, __parameter_types__, __parameters__, NULL);
}
void SerializationObjectManager::RaiseOnSerializedEvent()
{
Global::InvokeMethod("mscorlib", "System.Runtime.Serialization", "SerializationObjectManager", 0, NULL, "RaiseOnSerializedEvent", __native_object__, 0, NULL, NULL, NULL);
}
}
}
}
}
|
Java
|
/*
This file is a part of libcds - Concurrent Data Structures library
Version: 2.0.0
(C) Copyright Maxim Khizhinsky (libcds.dev@gmail.com) 2006-2014
Distributed under the BSD license (see accompanying file license.txt)
Source code repo: http://github.com/khizmax/libcds/
Download: http://sourceforge.net/projects/libcds/files/
*/
#include "hdr_intrusive_msqueue.h"
#include <cds/intrusive/msqueue.h>
#include <cds/gc/dhp.h>
namespace queue {
#define TEST(X) void IntrusiveQueueHeaderTest::test_##X() { test<X>(); }
namespace {
typedef IntrusiveQueueHeaderTest::base_hook_item< ci::msqueue::node<cds::gc::DHP > > base_item_type;
typedef IntrusiveQueueHeaderTest::member_hook_item< ci::msqueue::node<cds::gc::DHP > > member_item_type;
// DHP base hook
typedef ci::MSQueue< cds::gc::DHP, base_item_type,
typename ci::msqueue::make_traits<
ci::opt::hook<
ci::msqueue::base_hook< ci::opt::gc<cds::gc::DHP> >
>
, ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
>::type
> MSQueue_DHP_base;
// DHP member hook
typedef ci::MSQueue< cds::gc::DHP, member_item_type,
typename ci::msqueue::make_traits<
ci::opt::hook<
ci::msqueue::member_hook<
offsetof( member_item_type, hMember ),
ci::opt::gc<cds::gc::DHP>
>
>
, ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
>::type
> MSQueue_DHP_member;
/// DHP base hook + item counter
typedef ci::MSQueue< cds::gc::DHP, base_item_type,
typename ci::msqueue::make_traits<
ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
, ci::opt::hook<
ci::msqueue::base_hook< ci::opt::gc<cds::gc::DHP> >
>
, co::item_counter< cds::atomicity::item_counter >
, co::memory_model< co::v::relaxed_ordering >
>::type
> MSQueue_DHP_base_ic;
// DHP member hook + item counter
typedef ci::MSQueue< cds::gc::DHP, member_item_type,
typename ci::msqueue::make_traits<
ci::opt::hook<
ci::msqueue::member_hook<
offsetof( member_item_type, hMember ),
ci::opt::gc<cds::gc::DHP>
>
>
, ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
, co::item_counter< cds::atomicity::item_counter >
>::type
> MSQueue_DHP_member_ic;
// DHP base hook + stat
typedef ci::MSQueue< cds::gc::DHP, base_item_type,
typename ci::msqueue::make_traits<
ci::opt::hook<
ci::msqueue::base_hook< ci::opt::gc<cds::gc::DHP> >
>
, ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
, co::stat< ci::msqueue::stat<> >
>::type
> MSQueue_DHP_base_stat;
// DHP member hook + stat
typedef ci::MSQueue< cds::gc::DHP, member_item_type,
typename ci::msqueue::make_traits<
ci::opt::hook<
ci::msqueue::member_hook<
offsetof( member_item_type, hMember ),
ci::opt::gc<cds::gc::DHP>
>
>
, ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
, co::stat< ci::msqueue::stat<> >
>::type
> MSQueue_DHP_member_stat;
// DHP base hook + alignment
typedef ci::MSQueue< cds::gc::DHP, base_item_type,
typename ci::msqueue::make_traits<
ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
, ci::opt::hook<
ci::msqueue::base_hook< ci::opt::gc<cds::gc::DHP> >
>
, co::alignment< 32 >
>::type
> MSQueue_DHP_base_align;
// DHP member hook + alignment
typedef ci::MSQueue< cds::gc::DHP, member_item_type,
typename ci::msqueue::make_traits<
ci::opt::hook<
ci::msqueue::member_hook<
offsetof( member_item_type, hMember ),
ci::opt::gc<cds::gc::DHP>
>
>
, co::alignment< 32 >
, ci::opt::disposer< IntrusiveQueueHeaderTest::faked_disposer >
>::type
> MSQueue_DHP_member_align;
// DHP base hook + no alignment
struct traits_MSQueue_DHP_base_noalign : public ci::msqueue::traits {
typedef ci::msqueue::base_hook< ci::opt::gc<cds::gc::DHP> > hook;
typedef IntrusiveQueueHeaderTest::faked_disposer disposer;
enum { alignment = co::no_special_alignment };
};
typedef ci::MSQueue< cds::gc::DHP, base_item_type, traits_MSQueue_DHP_base_noalign > MSQueue_DHP_base_noalign;
// DHP member hook + no alignment
struct traits_MSQueue_DHP_member_noalign : public ci::msqueue::traits {
typedef ci::msqueue::member_hook <
offsetof( member_item_type, hMember ),
ci::opt::gc < cds::gc::DHP >
> hook;
typedef IntrusiveQueueHeaderTest::faked_disposer disposer;
enum { alignment = co::no_special_alignment };
};
typedef ci::MSQueue< cds::gc::DHP, member_item_type, traits_MSQueue_DHP_member_noalign > MSQueue_DHP_member_noalign;
// DHP base hook + cache alignment
struct traits_MSQueue_DHP_base_cachealign : public traits_MSQueue_DHP_base_noalign
{
enum { alignment = co::cache_line_alignment };
};
typedef ci::MSQueue< cds::gc::DHP, base_item_type, traits_MSQueue_DHP_base_cachealign > MSQueue_DHP_base_cachealign;
// DHP member hook + cache alignment
struct traits_MSQueue_DHP_member_cachealign : public traits_MSQueue_DHP_member_noalign
{
enum { alignment = co::cache_line_alignment };
};
typedef ci::MSQueue< cds::gc::DHP, member_item_type, traits_MSQueue_DHP_member_cachealign > MSQueue_DHP_member_cachealign;
} // namespace
TEST(MSQueue_DHP_base)
TEST(MSQueue_DHP_member)
TEST(MSQueue_DHP_base_ic)
TEST(MSQueue_DHP_member_ic)
TEST(MSQueue_DHP_base_stat)
TEST(MSQueue_DHP_member_stat)
TEST(MSQueue_DHP_base_align)
TEST(MSQueue_DHP_member_align)
TEST(MSQueue_DHP_base_noalign)
TEST(MSQueue_DHP_member_noalign)
TEST(MSQueue_DHP_base_cachealign)
TEST(MSQueue_DHP_member_cachealign)
} // namespace queue
|
Java
|
var compilerSupport=require('../../src/compilerSupport');var main = function () {
var __builder = new compilerSupport.TaskBuilder(), __state = 0, __continue = __builder.CONT, __ex;
var data;
return __builder.run(function () {
switch (__state) {
case 0: {
data = 12345;
console.log("data: " + data);
__state = -1;
__builder.ret(data);
break;
}
default:
throw 'Internal error: encountered wrong state';
}
});
};
main().then(function(x) {
console.log("returned: " + x);
}, function(y) {
console.log("failed: " + y);
});
|
Java
|
package test
import (
"github.com/tidepool-org/platform/config"
"github.com/tidepool-org/platform/log"
"github.com/tidepool-org/platform/version"
)
type Provider struct {
VersionReporterInvocations int
VersionReporterStub func() version.Reporter
VersionReporterOutputs []version.Reporter
VersionReporterOutput *version.Reporter
ConfigReporterInvocations int
ConfigReporterStub func() config.Reporter
ConfigReporterOutputs []config.Reporter
ConfigReporterOutput *config.Reporter
LoggerInvocations int
LoggerStub func() log.Logger
LoggerOutputs []log.Logger
LoggerOutput *log.Logger
PrefixInvocations int
PrefixStub func() string
PrefixOutputs []string
PrefixOutput *string
NameInvocations int
NameStub func() string
NameOutputs []string
NameOutput *string
UserAgentInvocations int
UserAgentStub func() string
UserAgentOutputs []string
UserAgentOutput *string
}
func NewProvider() *Provider {
return &Provider{}
}
func (p *Provider) VersionReporter() version.Reporter {
p.VersionReporterInvocations++
if p.VersionReporterStub != nil {
return p.VersionReporterStub()
}
if len(p.VersionReporterOutputs) > 0 {
output := p.VersionReporterOutputs[0]
p.VersionReporterOutputs = p.VersionReporterOutputs[1:]
return output
}
if p.VersionReporterOutput != nil {
return *p.VersionReporterOutput
}
panic("VersionReporter has no output")
}
func (p *Provider) ConfigReporter() config.Reporter {
p.ConfigReporterInvocations++
if p.ConfigReporterStub != nil {
return p.ConfigReporterStub()
}
if len(p.ConfigReporterOutputs) > 0 {
output := p.ConfigReporterOutputs[0]
p.ConfigReporterOutputs = p.ConfigReporterOutputs[1:]
return output
}
if p.ConfigReporterOutput != nil {
return *p.ConfigReporterOutput
}
panic("ConfigReporter has no output")
}
func (p *Provider) Logger() log.Logger {
p.LoggerInvocations++
if p.LoggerStub != nil {
return p.LoggerStub()
}
if len(p.LoggerOutputs) > 0 {
output := p.LoggerOutputs[0]
p.LoggerOutputs = p.LoggerOutputs[1:]
return output
}
if p.LoggerOutput != nil {
return *p.LoggerOutput
}
panic("Logger has no output")
}
func (p *Provider) Prefix() string {
p.PrefixInvocations++
if p.PrefixStub != nil {
return p.PrefixStub()
}
if len(p.PrefixOutputs) > 0 {
output := p.PrefixOutputs[0]
p.PrefixOutputs = p.PrefixOutputs[1:]
return output
}
if p.PrefixOutput != nil {
return *p.PrefixOutput
}
panic("Prefix has no output")
}
func (p *Provider) Name() string {
p.NameInvocations++
if p.NameStub != nil {
return p.NameStub()
}
if len(p.NameOutputs) > 0 {
output := p.NameOutputs[0]
p.NameOutputs = p.NameOutputs[1:]
return output
}
if p.NameOutput != nil {
return *p.NameOutput
}
panic("Name has no output")
}
func (p *Provider) UserAgent() string {
p.UserAgentInvocations++
if p.UserAgentStub != nil {
return p.UserAgentStub()
}
if len(p.UserAgentOutputs) > 0 {
output := p.UserAgentOutputs[0]
p.UserAgentOutputs = p.UserAgentOutputs[1:]
return output
}
if p.UserAgentOutput != nil {
return *p.UserAgentOutput
}
panic("UserAgent has no output")
}
func (p *Provider) AssertOutputsEmpty() {
if len(p.VersionReporterOutputs) > 0 {
panic("VersionReporterOutputs is not empty")
}
if len(p.ConfigReporterOutputs) > 0 {
panic("ConfigReporterOutputs is not empty")
}
if len(p.LoggerOutputs) > 0 {
panic("LoggerOutputs is not empty")
}
if len(p.PrefixOutputs) > 0 {
panic("PrefixOutputs is not empty")
}
if len(p.NameOutputs) > 0 {
panic("NameOutputs is not empty")
}
if len(p.UserAgentOutputs) > 0 {
panic("UserAgentOutputs is not empty")
}
}
|
Java
|
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/epoll.h>
#include <arpa/inet.h>
#define BUFF_SIZE 1024
int main(int argc, const char *argv[])
{
int i = 0;
char buff[BUFF_SIZE];
ssize_t msg_len = 0;
int srv_fd = -1;
int cli_fd = -1;
int epoll_fd = -1;
struct sockaddr_in srv_addr;
struct sockaddr_in cli_addr;
socklen_t cli_addr_len;
struct epoll_event e, es[2];
memset(&srv_addr, 0, sizeof(srv_addr));
memset(&cli_addr, 0, sizeof(cli_addr));
memset(&e, 0, sizeof(e));
srv_fd = socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
if (srv_fd < 0) {
printf("Cannot create socket\n");
return 1;
}
srv_addr.sin_family = AF_INET;
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
srv_addr.sin_port = htons(5555);
if (bind(srv_fd, (struct sockaddr*) &srv_addr, sizeof(srv_addr)) < 0) {
printf("Cannot bind socket\n");
close(srv_fd);
return 1;
}
if (listen(srv_fd, 1) < 0) {
printf("Cannot listen\n");
close(srv_fd);
return 1;
}
epoll_fd = epoll_create(2);
if (epoll_fd < 0) {
printf("Cannot create epoll\n");
close(srv_fd);
return 1;
}
e.events = EPOLLIN;
e.data.fd = srv_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, srv_fd, &e) < 0) {
printf("Cannot add server socket to epoll\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
for(;;) {
i = epoll_wait(epoll_fd, es, 2, -1);
if (i < 0) {
printf("Cannot wait for events\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
for (--i; i > -1; --i) {
if (es[i].data.fd == srv_fd) {
cli_fd = accept(srv_fd, (struct sockaddr*) &cli_addr, &cli_addr_len);
if (cli_fd < 0) {
printf("Cannot accept client\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
e.data.fd = cli_fd;
if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, cli_fd, &e) < 0) {
printf("Cannot accept client\n");
close(epoll_fd);
close(srv_fd);
return 1;
}
}
if (es[i].data.fd == cli_fd) {
if (es[i].events & EPOLLIN) {
msg_len = read(cli_fd, buff, BUFF_SIZE);
if (msg_len > 0) {
write(cli_fd, buff, msg_len);
}
close(cli_fd);
epoll_ctl(epoll_fd, EPOLL_CTL_DEL, cli_fd, &e);
cli_fd = -1;
}
}
}
}
return 0;
}
|
Java
|
// (c) 2010-2014 IndiegameGarden.com. Distributed under the FreeBSD license in LICENSE.txt
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TTengine")]
[assembly: AssemblyProduct("TTengine")]
[assembly: AssemblyDescription("2D game engine for C# XNA 4.0")]
[assembly: AssemblyCompany("IndiegameGarden.com")]
[assembly: AssemblyCopyright("Copyright © IndiegameGarden.com 2010-2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type. Only Windows
// assemblies support COM.
[assembly: ComVisible(false)]
// On Windows, the following GUID is for the ID of the typelib if this
// project is exposed to COM. On other platforms, it unique identifies the
// title storage container when deploying this assembly to the device.
[assembly: Guid("0de778ef-fe76-4a50-d0e9-cabba1a02517")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
[assembly: AssemblyVersion("5.0.0.1")]
|
Java
|
/*
* The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.
*
* Find the sum of all the primes below two million.
*/
#include <stdio.h>
#include <stdint.h>
#include "euler.h"
#define PROBLEM 10
int
main(int argc, char **argv)
{
uint64_t sum = 0, number = 0;
do {
number++;
if(is_prime(number)) {
sum += number;
}
} while(number != 2000000);
printf("%llu\n", sum);
return(0);
}
|
Java
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
namespace Mkko.Configuration
{
[ConfigurationCollection(typeof(ExecutionEnvironmentSettings), AddItemName = "executionEnvironment", CollectionType = ConfigurationElementCollectionType.BasicMap)]
public class ExecutionEnvironmentCollection : ConfigurationElementCollection
{
public override ConfigurationElementCollectionType CollectionType
{
get { return ConfigurationElementCollectionType.BasicMap; }
}
protected override string ElementName
{
get { return "executionEnvironment"; }
}
protected override ConfigurationElement CreateNewElement()
{
return new ExecutionEnvironmentSettings();
}
protected override object GetElementKey(ConfigurationElement element)
{
return (element as ExecutionEnvironmentSettings).Id;
}
}
}
|
Java
|
import pytest
import urllib.error
from urlpathlib import UrlPath
def test_scheme():
# does not raise NotImplementedError
UrlPath('/dev/null').touch()
def test_scheme_not_supported():
with pytest.raises(NotImplementedError):
UrlPath('http:///tmp/test').touch()
def test_scheme_not_listed():
with pytest.raises(NotImplementedError):
UrlPath('test:///tmp/test').touch()
def test_file_additional():
assert UrlPath('.').resolve() == UrlPath.cwd()
def test_scheme_alias():
# does not raise NotImplementedError
with pytest.raises(urllib.error.URLError):
UrlPath('https://localhost/test').exists()
|
Java
|
#region Copyright notice
/**
* Copyright (c) 2018 Samsung Electronics, Inc.,
* All rights reserved.
*
* 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.
*
* 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 HOLDER 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.
*/
#endregion
using System.Collections.Generic;
namespace DexterCS
{
public class ProjectAnalysisConfiguration
{
public string ProjectName { get; set; }
public string ProjectFullPath { get; set; }
private List<string> sourceDirs;
public List<string> SourceDirs
{
get { return sourceDirs ?? new List<string>(); }
set { sourceDirs = value; }
}
private List<string> headerDirs;
public List<string> HeaderDirs
{
get { return headerDirs ?? new List<string>(); }
set { headerDirs = value; }
}
private List<string> targetDir;
public List<string> TargetDirs
{
get
{
return targetDir ?? new List<string>();
}
set { targetDir = value; }
}
public string Type { get; set; }
}
}
|
Java
|
require "language/node"
class HttpServer < Formula
desc "Simple zero-configuration command-line HTTP server"
homepage "https://github.com/http-party/http-server"
url "https://registry.npmjs.org/http-server/-/http-server-13.0.1.tgz"
sha256 "35e08960062d766ad4c1e098f65b6e8bfb44f12516da90fd2df9974729652f03"
license "MIT"
head "https://github.com/http-party/http-server.git"
bottle do
sha256 cellar: :any_skip_relocation, all: "27f327beb2f485c4885636bbede7d6096a69659ee595b10621cf0a59d8797d32"
end
depends_on "node"
def install
system "npm", "install", *Language::Node.std_npm_install_args(libexec)
bin.install_symlink Dir["#{libexec}/bin/*"]
end
test do
port = free_port
pid = fork do
exec "#{bin}/http-server", "-p#{port}"
end
sleep 3
output = shell_output("curl -sI http://localhost:#{port}")
assert_match "200 OK", output
ensure
Process.kill("HUP", pid)
end
end
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Ocronet.Dynamic.Recognizers;
using Ocronet.Dynamic.OcroFST;
using Ocronet.Dynamic;
using Ocronet.Dynamic.ImgLib;
using Ocronet.Dynamic.Interfaces;
using Ocronet.Dynamic.Utils;
using Ocronet.Dynamic.IOData;
using System.IO;
using Ocronet.Dynamic.Segmentation;
using Ocronet.Dynamic.Recognizers.Lenet;
namespace Ocronet.DynamicConsole
{
public class TestLinerec
{
public void TestSimple()
{
Global.SetEnv("debug", Global.GetEnv("debug") + "");
// image file name to recognize
string imgFileName = "line.png";
string imgCsegFileName = "line.cseg.png";
string imgTranscriptFileName = "line.txt";
// line recognizer
Linerec lrec = (Linerec)Linerec.LoadLinerec("default.model");
//Linerec lrec = (Linerec)Linerec.LoadLinerec("2m2-reject.cmodel");
//Linerec lrec = (Linerec)Linerec.LoadLinerec("multi3.cmodel");
//Linerec lrec = (Linerec)Linerec.LoadLinerec("latin-ascii.model");
lrec.Info();
// language model
OcroFST default_lmodel = OcroFST.MakeOcroFst();
default_lmodel.Load("default.fst");
OcroFST lmodel = default_lmodel;
// read image
Bytearray image = new Bytearray(1, 1);
ImgIo.read_image_gray(image, imgFileName);
// recognize!
OcroFST fst = OcroFST.MakeOcroFst();
Intarray rseg = new Intarray();
lrec.RecognizeLine(rseg, fst, image);
// show result 1
string resStr;
fst.BestPath(out resStr);
Console.WriteLine("Fst BestPath: {0}", resStr);
// find result 2
Intarray v1 = new Intarray();
Intarray v2 = new Intarray();
Intarray inp = new Intarray();
Intarray outp = new Intarray();
Floatarray c = new Floatarray();
BeamSearch.beam_search(v1, v2, inp, outp, c, fst, lmodel, 100);
FstUtil.remove_epsilons(out resStr, outp);
Console.WriteLine("Fst BeamSearch: {0}", resStr);
Intarray cseg = new Intarray();
SegmRoutine.rseg_to_cseg(cseg, rseg, inp);
SegmRoutine.make_line_segmentation_white(cseg);
ImgLabels.simple_recolor(cseg); // for human readable
ImgIo.write_image_packed(imgCsegFileName, cseg);
File.WriteAllText(imgTranscriptFileName, resStr.Replace(" ", ""));
}
public void TestTrainLenetCseg()
{
string bookPath = "data\\0000\\";
string netFileName = "latin-lenet.model";
Linerec.GDef("linerec", "use_reject", 1);
Linerec.GDef("lenet", "junk", 1);
Linerec.GDef("lenet", "epochs", 4);
// create Linerec
Linerec linerec;
if (File.Exists(netFileName))
linerec = Linerec.LoadLinerec(netFileName);
else
{
linerec = new Linerec("lenet");
LenetClassifier classifier = linerec.GetClassifier() as LenetClassifier;
if (classifier != null)
classifier.InitNumSymbLatinAlphabet();
}
// temporary disable junk
//linerec.DisableJunk = true;
linerec.StartTraining();
int nepochs = 10;
LineSource lines = new LineSource();
lines.Init(new string[] { "data2" });
//linerec.GetClassifier().Set("epochs", 1);
for (int epoch = 1; epoch <= nepochs; epoch++)
{
linerec.Epoch(epoch);
// load cseg samples
while (!lines.Done())
{
lines.MoveNext();
Intarray cseg = new Intarray();
//Bytearray image = new Bytearray();
string transcript = lines.GetTranscript();
//lines.GetImage(image);
if (!lines.GetCharSegmentation(cseg) && cseg.Length() == 0)
{
Global.Debugf("warn", "skipping book {0} page {1} line {2} (no or bad cseg)",
lines.CurrentBook, lines.CurrentPage, lines.Current);
continue;
}
SegmRoutine.make_line_segmentation_black(cseg);
linerec.AddTrainingLine(cseg, transcript);
}
lines.Reset();
lines.Shuffle();
// do Train and clear Dataset
linerec.FinishTraining();
// do save
if (epoch % 1 == 0)
linerec.Save(netFileName);
// recognize test line
bool bakDisJunk = linerec.DisableJunk;
linerec.DisableJunk = false;
DoTestLinerecRecognize(linerec, "data2\\", "test1.png");
linerec.DisableJunk = bakDisJunk;
}
// finnaly save
linerec.Save(netFileName);
}
public void TestTrainLatinCseg()
{
string bookPath = "data\\0000\\";
string netFileName = "latin-amlp.model";
Linerec.GDef("linerec", "use_reject", 1);
Linerec.GDef("lenet", "junk", 1);
// create Linerec
Linerec linerec;
if (File.Exists(netFileName))
linerec = Linerec.LoadLinerec(netFileName);
else
{
linerec = new Linerec("latin");
}
// temporary disable junk
//linerec.DisableJunk = true;
linerec.StartTraining();
int nepochs = 1;
LineSource lines = new LineSource();
lines.Init(new string[] { "data2" });
for (int epoch = 1; epoch <= nepochs; epoch++)
{
linerec.Epoch(epoch);
// load cseg samples
while (lines.MoveNext())
{
Intarray cseg = new Intarray();
//Bytearray image = new Bytearray();
string transcript = lines.GetTranscript();
//lines.GetImage(image);
if (!lines.GetCharSegmentation(cseg) && cseg.Length() == 0)
{
Global.Debugf("warn", "skipping book {0} page {1} line {2} (no or bad cseg)",
lines.CurrentBook, lines.CurrentPage, lines.CurrentLine);
continue;
}
SegmRoutine.make_line_segmentation_black(cseg);
linerec.AddTrainingLine(cseg, transcript);
}
lines.Reset();
lines.Shuffle();
// do Train and clear Dataset
linerec.FinishTraining();
// do save
if (epoch % 1 == 0)
linerec.Save(netFileName);
// recognize test line
bool bakDisJunk = linerec.DisableJunk;
linerec.DisableJunk = false;
DoTestLinerecRecognize(linerec, bookPath, "000010.png");
linerec.DisableJunk = bakDisJunk;
}
// finnaly save
linerec.Save(netFileName);
}
private void DoTestLinerecRecognize(Linerec linerec, string bookPath, string filename)
{
Bytearray image = new Bytearray();
ImgIo.read_image_gray(image, bookPath + filename);
// recognize!
OcroFST fst = OcroFST.MakeOcroFst();
linerec.RecognizeLine(fst, image);
// show result
string resStr;
fst.BestPath(out resStr);
Console.WriteLine("Fst BestPath: {0}", resStr);
}
public void TestRecognizeCseg()
{
string book1Path = "data2\\0001\\";
string book2Path = "data\\0000\\";
//Linerec.GDef("linerec", "use_reject", 0);
//Linerec.GDef("lenet", "junk", 0);
Linerec linerec = Linerec.LoadLinerec("latin-amlp.model");
//Linerec linerec = Linerec.LoadLinerec("latin-lenet.model");
//Linerec linerec = Linerec.LoadLinerec("latin-ascii2.model");
//Linerec linerec = Linerec.LoadLinerec("default.model");
//linerec.Set("maxcost", 20);
DoTestLinerecRecognize(linerec, book1Path, "0010.png");
DoTestLinerecRecognize(linerec, book1Path, "0001.png");
DoTestLinerecRecognize(linerec, book1Path, "0089.png");
DoTestLinerecRecognize(linerec, book1Path, "0026.png");
DoTestLinerecRecognize(linerec, book2Path, "000001.png");
}
public void TestComputeMissingCseg()
{
//ComputeMissingCsegForBookStore("data", "default.model", "");
//ComputeMissingCsegForBookStore("data2", "latin-ascii.model", "gt");
ComputeMissingCsegForBookStore("data", "latin-lenet.model", "");
}
/// <summary>
/// Create char segmentation (cseg) files if missing
/// </summary>
/// <param name="bookPath">path to bookstore</param>
/// <param name="modelFilename">Linerec model file</param>
/// <param name="langModel">language model file</param>
/// <param name="suffix">e.g., 'gt'</param>
public void ComputeMissingCsegForBookStore(string bookPath, string model = "default.model",
string suffix = "", bool saveRseg = false, string langModel = "default.fst")
{
// create line recognizer
Linerec linerec = Linerec.LoadLinerec(model);
// create IBookStore
IBookStore bookstore = new SmartBookStore();
bookstore.SetPrefix(bookPath);
bookstore.Info();
// language model
OcroFST lmodel = OcroFST.MakeOcroFst();
lmodel.Load(langModel);
// iterate lines of pages
for (int page = 0; page < bookstore.NumberOfPages(); page++)
{
int nlines = bookstore.LinesOnPage(page);
Console.WriteLine("Page {0} has {1} lines", page, nlines);
for (int j = 0; j < nlines; j++)
{
int line = bookstore.GetLineId(page, j);
Bytearray image = new Bytearray();
bookstore.GetLine(image, page, line);
Intarray cseg = new Intarray();
bookstore.GetCharSegmentation(cseg, page, line, suffix);
// check missing cseg file
if (cseg.Length() <= 0 && image.Length() > 0)
{
// recognize line
OcroFST fst = OcroFST.MakeOcroFst();
Intarray rseg = new Intarray();
linerec.RecognizeLine(rseg, fst, image);
// find best results
string resText;
Intarray inp = new Intarray();
Floatarray costs = new Floatarray();
double totalCost = BeamSearch.beam_search(out resText, inp, costs, fst, lmodel, 100);
Console.WriteLine(bookstore.PathFile(page, line, suffix));
Console.Write(" beam_search score: {0}", totalCost);
/*string resText2;
fst.BestPath(out resText2);*/
// write cseg to bookstore
string trans;
bookstore.GetLine(out trans, page, line, suffix);
resText = resText.Replace(" ", "");
if (String.IsNullOrEmpty(trans))
{
bookstore.PutLine(resText, page, line, suffix);
Console.Write("; transcript saved");
}
else if (trans == resText)
{
// convert inputs and rseg to cseg
SegmRoutine.rseg_to_cseg(cseg, rseg, inp);
bookstore.PutCharSegmentation(cseg, page, line, suffix);
Console.Write("; cseg saved");
}
else if (saveRseg)
{
// convert inputs and rseg to cseg
SegmRoutine.rseg_to_cseg(cseg, rseg, inp);
//SegmRoutine.remove_small_components(cseg, 4);
/*bookstore.PutCharSegmentation(cseg, page, line, suffix);
Console.Write("; cseg saved");*/
SegmRoutine.make_line_segmentation_white(cseg);
ImgLabels.simple_recolor(cseg);
string v = "rseg";
if (!String.IsNullOrEmpty(suffix)) { v += "."; v += suffix; }
string rsegpath = bookstore.PathFile(page, line, v, "png");
ImgIo.write_image_packed(rsegpath, cseg);
Console.Write("; rseg saved");
}
Console.WriteLine();
}
}
}
}
}
}
|
Java
|
class Opusfile < Formula
desc "API for decoding and seeking in .opus files"
homepage "https://www.opus-codec.org/"
url "https://archive.mozilla.org/pub/opus/opusfile-0.11.tar.gz"
sha256 "74ce9b6cf4da103133e7b5c95df810ceb7195471e1162ed57af415fabf5603bf"
revision 1
bottle do
cellar :any
rebuild 1
sha256 "acd200760db74feb30ea28bdb14cdf8b3ebdeb5a65759e1095fad3f9583c3ef3" => :catalina
sha256 "44e1c4d26cac791ff40de7b15fb2718c6aaa99856a128c23a3c542a3132e2053" => :mojave
sha256 "7f83ce800aaa0dedb44b18332e1628e307bf83d693586ed6359b02e6ea21737e" => :high_sierra
end
head do
url "https://gitlab.xiph.org/xiph/opusfile.git"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
end
depends_on "pkg-config" => :build
depends_on "libogg"
depends_on "openssl@1.1"
depends_on "opus"
resource "music_48kbps.opus" do
url "https://www.opus-codec.org/static/examples/samples/music_48kbps.opus"
sha256 "64571f56bb973c078ec784472944aff0b88ba0c88456c95ff3eb86f5e0c1357d"
end
def install
system "./autogen.sh" if build.head?
system "./configure", "--disable-dependency-tracking",
"--prefix=#{prefix}"
system "make", "install"
end
test do
testpath.install resource("music_48kbps.opus")
(testpath/"test.c").write <<~EOS
#include <opus/opusfile.h>
#include <stdlib.h>
int main(int argc, const char **argv) {
int ret;
OggOpusFile *of;
of = op_open_file(argv[1], &ret);
if (of == NULL) {
fprintf(stderr, "Failed to open file '%s': %i\\n", argv[1], ret);
return EXIT_FAILURE;
}
op_free(of);
return EXIT_SUCCESS;
}
EOS
system ENV.cc, "test.c", "-I#{Formula["opus"].include}/opus",
"-L#{lib}",
"-lopusfile",
"-o", "test"
system "./test", "music_48kbps.opus"
end
end
|
Java
|
cask 'opera-beta' do
version '50.0.2762.42'
sha256 '0ae6866beb0047a2aebd22df7d2638f2d95ad8c08227879905d0e96e1add2235'
url "https://get.geo.opera.com/pub/opera-beta/#{version}/mac/Opera_beta_#{version}_Setup.dmg"
name 'Opera Beta'
homepage 'https://www.opera.com/computer/beta'
auto_updates true
app 'Opera Beta.app'
end
|
Java
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2016 Inviwo Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* 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.
*
*********************************************************************************/
#ifndef IVW_GLFWEXCEPTION_H
#define IVW_GLFWEXCEPTION_H
#include <modules/glfw/glfwmoduledefine.h>
#include <inviwo/core/common/inviwo.h>
#include <inviwo/core/util/exception.h>
namespace inviwo {
/**
* \class GLFWException
*/
class IVW_MODULE_GLFW_API GLFWException : public Exception {
public:
GLFWException(const std::string& message = "", ExceptionContext context = ExceptionContext());
virtual ~GLFWException() throw() {}
};
class IVW_MODULE_GLFW_API GLFWInitException : public ModuleInitException {
public:
GLFWInitException(const std::string& message = "",
ExceptionContext context = ExceptionContext());
virtual ~GLFWInitException() throw() {}
};
} // namespace
#endif // IVW_GLFWEXCEPTION_H
|
Java
|
# coding: utf8
from __future__ import unicode_literals
from flask import abort, make_response, request
from flask_api.decorators import set_renderers
from flask_api import exceptions, renderers, status, FlaskAPI
import json
import unittest
app = FlaskAPI(__name__)
app.config['TESTING'] = True
class JSONVersion1(renderers.JSONRenderer):
media_type = 'application/json; api-version="1.0"'
class JSONVersion2(renderers.JSONRenderer):
media_type = 'application/json; api-version="2.0"'
@app.route('/set_status_and_headers/')
def set_status_and_headers():
headers = {'Location': 'http://example.com/456'}
return {'example': 'content'}, status.HTTP_201_CREATED, headers
@app.route('/set_headers/')
def set_headers():
headers = {'Location': 'http://example.com/456'}
return {'example': 'content'}, headers
@app.route('/make_response_view/')
def make_response_view():
response = make_response({'example': 'content'})
response.headers['Location'] = 'http://example.com/456'
return response
@app.route('/api_exception/')
def api_exception():
raise exceptions.PermissionDenied()
@app.route('/abort_view/')
def abort_view():
abort(status.HTTP_403_FORBIDDEN)
@app.route('/options/')
def options_view():
return {}
@app.route('/accepted_media_type/')
@set_renderers([JSONVersion2, JSONVersion1])
def accepted_media_type():
return {'accepted_media_type': str(request.accepted_media_type)}
class AppTests(unittest.TestCase):
def test_set_status_and_headers(self):
with app.test_client() as client:
response = client.get('/set_status_and_headers/')
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(response.headers['Location'], 'http://example.com/456')
self.assertEqual(response.content_type, 'application/json')
expected = '{"example": "content"}'
self.assertEqual(response.get_data().decode('utf8'), expected)
def test_set_headers(self):
with app.test_client() as client:
response = client.get('/set_headers/')
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.headers['Location'], 'http://example.com/456')
self.assertEqual(response.content_type, 'application/json')
expected = '{"example": "content"}'
self.assertEqual(response.get_data().decode('utf8'), expected)
def test_make_response(self):
with app.test_client() as client:
response = client.get('/make_response_view/')
self.assertEqual(response.content_type, 'application/json')
self.assertEqual(response.headers['Location'], 'http://example.com/456')
self.assertEqual(response.content_type, 'application/json')
expected = '{"example": "content"}'
self.assertEqual(response.get_data().decode('utf8'), expected)
def test_api_exception(self):
with app.test_client() as client:
response = client.get('/api_exception/')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
self.assertEqual(response.content_type, 'application/json')
expected = '{"message": "You do not have permission to perform this action."}'
self.assertEqual(response.get_data().decode('utf8'), expected)
def test_abort_view(self):
with app.test_client() as client:
response = client.get('/abort_view/')
self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_options_view(self):
with app.test_client() as client:
response = client.options('/options/')
# Errors if `response.response` is `None`
response.get_data()
def test_accepted_media_type_property(self):
with app.test_client() as client:
# Explicitly request the "api-version 1.0" renderer.
headers = {'Accept': 'application/json; api-version="1.0"'}
response = client.get('/accepted_media_type/', headers=headers)
data = json.loads(response.get_data().decode('utf8'))
expected = {'accepted_media_type': 'application/json; api-version="1.0"'}
self.assertEqual(data, expected)
# Request the default renderer, which is "api-version 2.0".
headers = {'Accept': '*/*'}
response = client.get('/accepted_media_type/', headers=headers)
data = json.loads(response.get_data().decode('utf8'))
expected = {'accepted_media_type': 'application/json; api-version="2.0"'}
self.assertEqual(data, expected)
|
Java
|
/*
* Copyright 2016 Skynav, Inc. All rights reserved.
* Portions Copyright 2009 Extensible Formatting Systems, Inc (XFSI).
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* THIS SOFTWARE IS PROVIDED BY SKYNAV, INC. AND ITS 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 SKYNAV, INC. OR ITS 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.
*/
package com.xfsi.xav.validation.images.jpeg;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
/**
* Handles JPEG input stream. Tracks total bytes read and allows putting back of read data.
*/
class JpegInputStream {
private int readByteCount = 0;
private final DataInputStream inputStream;
private LinkedList<Byte> putBack = new LinkedList<Byte>();
JpegInputStream(InputStream is)
{
this.inputStream = new DataInputStream(is);
}
byte readByte() throws EOFException, IOException
{
if (this.putBack.size() == 0)
{
byte b = this.inputStream.readByte();
this.readByteCount++;
return b;
}
return this.putBack.remove();
}
short readShort() throws EOFException, IOException
{
if (this.putBack.size() == 0)
{
short s = this.inputStream.readShort();
this.readByteCount += 2;
return s;
}
short msb = readByte();
short lsb = readByte();
return (short) ((msb << 8) | (lsb & 0xff));
}
int readInt() throws EOFException, IOException
{
if (this.putBack.size() == 0)
{
int i = this.inputStream.readInt();
this.readByteCount += 4;
return i;
}
int mss = readShort();
int lss = readShort();
return (mss << 16) | (lss & 0xffff);
}
void skipBytes(int count) throws EOFException, IOException
{
// DataInputStream skipBytes() in jpegInputStream does not throw EOFException() if EOF reached,
// which we are interested in, so read the bytes to skip them which WILL generate an EOFException().
for (int i = 0; i < count; i++)
readByte();
}
void putBack(byte b)
{
this.putBack.add(b);
}
int getTotalBytesRead()
{
return this.readByteCount;
}
}
|
Java
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CLI - bossing Varnish around — Varnish version 4.0.0 documentation</title>
<link rel="stylesheet" href="../_static/default.css" type="text/css" />
<link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
<script type="text/javascript">
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '../',
VERSION: '4.0.0',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true
};
</script>
<script type="text/javascript" src="../_static/jquery.js"></script>
<script type="text/javascript" src="../_static/underscore.js"></script>
<script type="text/javascript" src="../_static/doctools.js"></script>
<link rel="top" title="Varnish version 4.0.0 documentation" href="../index.html" />
<link rel="up" title="Starting and running Varnish" href="running.html" />
<link rel="next" title="Storage backends" href="storage-backends.html" />
<link rel="prev" title="Important command line arguments" href="command-line.html" />
</head>
<body>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
accesskey="I">index</a></li>
<li class="right" >
<a href="storage-backends.html" title="Storage backends"
accesskey="N">next</a> |</li>
<li class="right" >
<a href="command-line.html" title="Important command line arguments"
accesskey="P">previous</a> |</li>
<li><a href="../index.html">Varnish version 4.0.0 documentation</a> »</li>
<li><a href="index.html" >The Varnish Users Guide</a> »</li>
<li><a href="running.html" accesskey="U">Starting and running Varnish</a> »</li>
</ul>
</div>
<div class="document">
<div class="documentwrapper">
<div class="bodywrapper">
<div class="body">
<div class="section" id="cli-bossing-varnish-around">
<span id="run-cli"></span><h1>CLI - bossing Varnish around<a class="headerlink" href="#cli-bossing-varnish-around" title="Permalink to this headline">¶</a></h1>
<p>Once <cite>varnishd</cite> is started, you can control it using the command line
interface.</p>
<p>The easiest way to do this, is using <cite>varnishadm</cite> on the
same machine as <cite>varnishd</cite> is running:</p>
<div class="highlight-python"><pre>varnishadm help</pre>
</div>
<p>If you want to run <cite>varnishadm</cite> from a remote system, you can do it
two ways.</p>
<p>You can SSH into the <cite>varnishd</cite> computer and run <cite>varnishadm</cite>:</p>
<div class="highlight-python"><pre>ssh $http_front_end varnishadm help</pre>
</div>
<p>But you can also configure <cite>varnishd</cite> to accept remote CLI connections
(using the '-T' and '-S' arguments):</p>
<div class="highlight-python"><pre>varnishd -T :6082 -S /etc/varnish_secret</pre>
</div>
<p>And then on the remote system run <cite>varnishadm</cite>:</p>
<div class="highlight-python"><pre>varnishadm -T $http_front_end -S /etc/copy_of_varnish_secret help</pre>
</div>
<p>but as you can see, SSH is much more convenient.</p>
<p>If you run <cite>varnishadm</cite> without arguments, it will read CLI commands from
<cite>stdin</cite>, if you give it arguments, it will treat those as the single
CLI command to execute.</p>
<p>The CLI always returns a status code to tell how it went: '200'
means OK, anything else means there were some kind of trouble.</p>
<p><cite>varnishadm</cite> will exit with status 1 and print the status code on
standard error if it is not 200.</p>
<div class="section" id="what-can-you-do-with-the-cli">
<h2>What can you do with the CLI<a class="headerlink" href="#what-can-you-do-with-the-cli" title="Permalink to this headline">¶</a></h2>
<p>The CLI gives you almost total control over <cite>varnishd</cite> some of the more important tasks you can perform are:</p>
<ul class="simple">
<li>load/use/discard VCL programs</li>
<li>ban (invalidate) cache content</li>
<li>change parameters</li>
<li>start/stop worker process</li>
</ul>
<p>We will discuss each of these briefly below.</p>
<div class="section" id="load-use-and-discard-vcl-programs">
<h3>Load, use and discard VCL programs<a class="headerlink" href="#load-use-and-discard-vcl-programs" title="Permalink to this headline">¶</a></h3>
<p>All caching and policy decisions are made by VCL programs.</p>
<p>You can have multiple VCL programs loaded, but one of them
is designated the "active" VCL program, and this is where
all new requests start out.</p>
<p>To load new VCL program:</p>
<div class="highlight-python"><pre>varnish> vcl.load some_name some_filename</pre>
</div>
<p>Loading will read the VCL program from the file, and compile it. If
the compilation fails, you will get an error messages:</p>
<div class="highlight-python"><pre>.../mask is not numeric.
('input' Line 4 Pos 17)
"192.168.2.0/24x",
----------------#################-
Running VCC-compiler failed, exit 1
VCL compilation failed</pre>
</div>
<p>If compilation succeeds, the VCL program is loaded, and you can
now make it the active VCL, whenever you feel like it:</p>
<div class="highlight-python"><pre>varnish> vcl.use some_name</pre>
</div>
<p>If you find out that was a really bad idea, you can switch back
to the previous VCL program again:</p>
<div class="highlight-python"><pre>varnish> vcl.use old_name</pre>
</div>
<p>The switch is instantaneous, all new requests will start using the
VCL you activated right away. The requests currently being processed complete
using whatever VCL they started with.</p>
<p>It is good idea to design an emergency-VCL before you need it,
and always have it loaded, so you can switch to it with a single
vcl.use command.</p>
</div>
<div class="section" id="ban-cache-content">
<h3>Ban cache content<a class="headerlink" href="#ban-cache-content" title="Permalink to this headline">¶</a></h3>
<p>Varnish offers "purges" to remove things from cache, provided that
you know exactly what they are.</p>
<p>But sometimes it is useful to be able to throw things out of cache
without having an exact list of what to throw out.</p>
<p>Imagine for instance that the company logo changed and now you need
Varnish to stop serving the old logo out of the cache:</p>
<div class="highlight-python"><pre>varnish> ban req.url ~ "logo.*[.]png"</pre>
</div>
<p>should do that, and yes, that is a regular expression.</p>
<p>We call this "banning" because the objects are still in the cache,
but they are banned from delivery.</p>
<p>Instead of checking each and every cached object right away, we
test each object against the regular expression only if and when
an HTTP request asks for it.</p>
<p>Banning stuff is much cheaper than restarting Varnish to get rid
of wronly cached content.</p>
</div>
<div class="section" id="change-parameters">
<h3>Change parameters<a class="headerlink" href="#change-parameters" title="Permalink to this headline">¶</a></h3>
<p>Parameters can be set on the command line with the '-p' argument,
but they can also be examined and changed on the fly from the CLI:</p>
<div class="highlight-python"><pre>varnish> param.show prefer_ipv6
200
prefer_ipv6 off [bool]
Default is off
Prefer IPv6 address when connecting to backends
which have both IPv4 and IPv6 addresses.
varnish> param.set prefer_ipv6 true
200</pre>
</div>
<p>In general it is not a good idea to modify parameters unless you
have a good reason, such as performance tuning or security configuration.</p>
<p>Most parameters will take effect instantly, or with a natural delay
of some duration,</p>
<p>but a few of them requires you to restart the
child process before they take effect. This is always noted in the
description of the parameter.</p>
</div>
<div class="section" id="starting-and-stopping-the-worker-process">
<h3>Starting and stopping the worker process<a class="headerlink" href="#starting-and-stopping-the-worker-process" title="Permalink to this headline">¶</a></h3>
<p>In general you should just leave the worker process running, but
if you need to stop and/or start it, the obvious commands work:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">varnish</span><span class="o">></span> <span class="n">stop</span>
</pre></div>
</div>
<p>and:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="n">varnish</span><span class="o">></span> <span class="n">start</span>
</pre></div>
</div>
<p>If you start <cite>varnishd</cite> with the '-d' (debugging) argument, you will
always need to start the child process explicitly.</p>
<p>Should the child process die, the master process will automatically
restart it, but you can disable that with the 'auto_restart' parameter.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="sphinxsidebar">
<div class="sphinxsidebarwrapper">
<h3><a href="../index.html">Table Of Contents</a></h3>
<ul>
<li><a class="reference internal" href="#">CLI - bossing Varnish around</a><ul>
<li><a class="reference internal" href="#what-can-you-do-with-the-cli">What can you do with the CLI</a><ul>
<li><a class="reference internal" href="#load-use-and-discard-vcl-programs">Load, use and discard VCL programs</a></li>
<li><a class="reference internal" href="#ban-cache-content">Ban cache content</a></li>
<li><a class="reference internal" href="#change-parameters">Change parameters</a></li>
<li><a class="reference internal" href="#starting-and-stopping-the-worker-process">Starting and stopping the worker process</a></li>
</ul>
</li>
</ul>
</li>
</ul>
<h4>Previous topic</h4>
<p class="topless"><a href="command-line.html"
title="previous chapter">Important command line arguments</a></p>
<h4>Next topic</h4>
<p class="topless"><a href="storage-backends.html"
title="next chapter">Storage backends</a></p>
<h3>This Page</h3>
<ul class="this-page-menu">
<li><a href="../_sources/users-guide/run_cli.txt"
rel="nofollow">Show Source</a></li>
</ul>
<div id="searchbox" style="display: none">
<h3>Quick search</h3>
<form class="search" action="../search.html" method="get">
<input type="text" name="q" />
<input type="submit" value="Go" />
<input type="hidden" name="check_keywords" value="yes" />
<input type="hidden" name="area" value="default" />
</form>
<p class="searchtip" style="font-size: 90%">
Enter search terms or a module, class or function name.
</p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
</div>
</div>
<div class="clearer"></div>
</div>
<div class="related">
<h3>Navigation</h3>
<ul>
<li class="right" style="margin-right: 10px">
<a href="../genindex.html" title="General Index"
>index</a></li>
<li class="right" >
<a href="storage-backends.html" title="Storage backends"
>next</a> |</li>
<li class="right" >
<a href="command-line.html" title="Important command line arguments"
>previous</a> |</li>
<li><a href="../index.html">Varnish version 4.0.0 documentation</a> »</li>
<li><a href="index.html" >The Varnish Users Guide</a> »</li>
<li><a href="running.html" >Starting and running Varnish</a> »</li>
</ul>
</div>
<div class="footer">
© Copyright 2010-2014, Varnish Software AS.
Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3.
</div>
</body>
</html>
|
Java
|
// EarthShape.java
// See copyright.txt for license and terms of use.
package earthshape;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeSet;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import com.jogamp.opengl.GLCapabilities;
import util.FloatUtil;
import util.Vector3d;
import util.Vector3f;
import util.swing.ModalDialog;
import util.swing.MyJFrame;
import util.swing.MySwingWorker;
import util.swing.ProgressDialog;
import static util.swing.SwingUtil.log;
/** This application demonstrates a procedure for inferring the shape
* of a surface (such as the Earth) based on the observed locations of
* stars from various locations at a fixed point in time.
*
* This class, EarthShape, manages UI components external to the 3D
* display, such as the menu and status bars. It also contains all of
* the code to construct the virtual 3D map using various algorithms.
* The 3D display, along with its camera controls, is in EarthMapCanvas. */
public class EarthShape extends MyJFrame {
// --------- Constants ----------
/** AWT boilerplate generated serial ID. */
private static final long serialVersionUID = 3903955302894393226L;
/** Size of the first constructed square, in kilometers. The
* displayed size is then determined by the map scale, which
* is normally 1 unit per 1000 km. */
private static final float INITIAL_SQUARE_SIZE_KM = 1000;
/** Initial value of 'adjustOrientationDegrees', and the value to
* which it is reset when a new square is created. */
private static final float DEFAULT_ADJUST_ORIENTATION_DEGREES = 1.0f;
/** Do not let 'adjustOrientationDegrees' go below this value. Below
* this value is pointless because the precision of the variance is
* not high enough to discriminate among the choices. */
private static final float MINIMUM_ADJUST_ORIENTATION_DEGREES = 1e-7f;
// ---------- Instance variables ----------
// ---- Observation Information ----
/** The observations that will drive surface reconstruction.
* By default, this will be data from the real world, but it
* can be swapped out at the user's option. */
public WorldObservations worldObservations = new RealWorldObservations();
/** Set of stars that are enabled. */
private LinkedHashMap<String, Boolean> enabledStars = new LinkedHashMap<String, Boolean>();
// ---- Interactive surface construction state ----
/** The square we will build upon when the next square is added.
* This may be null. */
private SurfaceSquare activeSquare;
/** When adjusting the orientation of the active square, this
* is how many degrees to rotate at once. */
private float adjustOrientationDegrees = DEFAULT_ADJUST_ORIENTATION_DEGREES;
// ---- Options ----
/** When true, star observations are only compared by their
* direction. When false, we also consider the location of the
* observer, which allows us to handle nearby objects. */
public boolean assumeInfiniteStarDistance = false;
/** When true, star observations are only compared by their
* direction, and furthermore, only the elevation, ignoring
* azimuth. This is potentially interesting because, in
* practice, it is difficult to accurately measure azimuth
* with just a hand-held sextant. */
public boolean onlyCompareElevations = false;
/** When analyzing the solution space, use this many points of
* rotation on each side of 0, for each axis. Note that the
* algorithm is cubic in this parameter. */
private int solutionAnalysisPointsPerSide = 20;
/** If the Sun's elevation is higher than this value, then
* we cannot see any stars. */
private float maximumSunElevation = -5;
/** When true, take the Sun's elevation into account. */
private boolean useSunElevation = true;
/** When true, use the "new" orientation algorithm that
* repeatedly applies the recommended command. Otherwise,
* use the older one based on average deviation. The old
* algorithm is faster, but slightly less accurate, and
* does not mimic the process a user would use to manually
* adjust a square's orientation. */
private boolean newAutomaticOrientationAlgorithm = true;
// ---- Widgets ----
/** Canvas showing the Earth surface built so far. */
private EarthMapCanvas emCanvas;
/** Widget to show various state variables such as camera position. */
private JLabel statusLabel;
/** Selected square info panel on right side. */
private InfoPanel infoPanel;
// Menu items to toggle various options.
private JCheckBoxMenuItem drawCoordinateAxesCBItem;
private JCheckBoxMenuItem drawCrosshairCBItem;
private JCheckBoxMenuItem drawWireframeSquaresCBItem;
private JCheckBoxMenuItem drawCompassesCBItem;
private JCheckBoxMenuItem drawSurfaceNormalsCBItem;
private JCheckBoxMenuItem drawCelestialNorthCBItem;
private JCheckBoxMenuItem drawStarRaysCBItem;
private JCheckBoxMenuItem drawUnitStarRaysCBItem;
private JCheckBoxMenuItem drawBaseSquareStarRaysCBItem;
private JCheckBoxMenuItem drawTravelPathCBItem;
private JCheckBoxMenuItem drawActiveSquareAtOriginCBItem;
private JCheckBoxMenuItem useSunElevationCBItem;
private JCheckBoxMenuItem invertHorizontalCameraMovementCBItem;
private JCheckBoxMenuItem invertVerticalCameraMovementCBItem;
private JCheckBoxMenuItem newAutomaticOrientationAlgorithmCBItem;
private JCheckBoxMenuItem assumeInfiniteStarDistanceCBItem;
private JCheckBoxMenuItem onlyCompareElevationsCBItem;
private JCheckBoxMenuItem drawWorldWireframeCBItem;
private JCheckBoxMenuItem drawWorldStarsCBItem;
private JCheckBoxMenuItem drawSkyboxCBItem;
// ---------- Methods ----------
public EarthShape()
{
super("EarthShape");
this.setName("EarthShape (JFrame)");
this.setLayout(new BorderLayout());
this.setIcon();
for (String starName : this.worldObservations.getAllStars()) {
// Initially all stars are enabled.
this.enabledStars.put(starName, true);
}
this.setSize(1150, 800);
this.setLocationByPlatform(true);
this.setupJOGL();
this.buildMenuBar();
// Status bar on bottom.
this.statusLabel = new JLabel();
this.statusLabel.setName("statusLabel");
this.add(this.statusLabel, BorderLayout.SOUTH);
// Info panel on right.
this.add(this.infoPanel = new InfoPanel(), BorderLayout.EAST);
this.updateUIState();
}
/** Initialize the JOGL library, then create a GL canvas and
* associate it with this window. */
private void setupJOGL()
{
log("creating GLCapabilities");
// This call takes about one second to complete, which is
// pretty slow...
GLCapabilities caps = new GLCapabilities(null /*profile*/);
log("caps: "+caps);
caps.setDoubleBuffered(true);
caps.setHardwareAccelerated(true);
// Build the object that will show the surface.
this.emCanvas = new EarthMapCanvas(this, caps);
// Associate the canvas with 'this' window.
this.add(this.emCanvas, BorderLayout.CENTER);
}
/** Set the window icon to my application's icon. */
private void setIcon()
{
try {
URL url = this.getClass().getResource("globe-icon.png");
Image img = Toolkit.getDefaultToolkit().createImage(url);
this.setIconImage(img);
}
catch (Exception e) {
System.err.println("Failed to set app icon: "+e.getMessage());
}
}
private void showAboutBox()
{
String about =
"EarthShape\n"+
"Copyright 2017 Scott McPeak\n"+
"\n"+
"Published under the 2-clause BSD license.\n"+
"See copyright.txt for details.\n";
JOptionPane.showMessageDialog(this, about, "About", JOptionPane.INFORMATION_MESSAGE);
}
private void showKeyBindings()
{
String bindings =
"Left click in 3D view to enter FPS controls mode.\n"+
"Esc - Leave FPS mode.\n"+
"W/A/S/D - Move camera horizontally when in FPS mode.\n"+
"Space/Z - Move camera up or down in FPS mode.\n"+
"Left click on square in FPS mode to make it active.\n"+
"\n"+
"T - Reconstruct Earth from star data.\n"+
"\n"+
"C - Toggle compass or Earth texture.\n"+
"P - Toggle star rays for active square.\n"+
"G - Move camera to active square's center.\n"+
"H - Build complete Earth using assumed sphere.\n"+
"R - Build Earth using assumed sphere and random walk.\n"+
"\n"+
"U/O - Roll active square left or right.\n"+
"I/K - Pitch active square down or up.\n"+
"J/L - Yaw active square left or right.\n"+
"1 - Reset adjustment amount to 1 degree.\n"+
"-/= - Decrease or increase adjustment amount.\n"+
"; (semicolon) - Make recommended active square adjustment.\n"+
"/ (slash) - Automatically orient active square.\n"+
"\' (apostrophe) - Analyze rotation solution space for active square.\n"+
"\n"+
"N - Start a new surface.\n"+
"M - Add a square adjacent to the active square.\n"+
"Ctrl+N/S/E/W - Add a square to the N/S/E/W and automatically adjust it.\n"+
", (comma) - Move to previous active square.\n"+
". (period) - Move to next active square.\n"+
"Delete - Delete active square.\n"+
"\n"+
"0/PgUp/PgDn - Change animation state (not for general use)\n"+
"";
JOptionPane.showMessageDialog(this, bindings, "Bindings", JOptionPane.INFORMATION_MESSAGE);
}
/** Build the menu bar and attach it to 'this'. */
private void buildMenuBar()
{
// This ensures that the menu items do not appear underneath
// the GL canvas. Strangely, this problem appeared suddenly,
// after I made a seemingly irrelevant change (putting a
// scroll bar on the info panel). But this call solves it,
// so whatever.
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
JMenuBar menuBar = new JMenuBar();
this.setJMenuBar(menuBar);
// Used keys:
// a - Move camera left
// b
// c - Toggle compass
// d - Move camera right
// e
// f
// g - Go to selected square's center
// h - Build spherical Earth
// i - Pitch active square down
// j - Yaw active square left
// k - Pitch active square up
// l - Yaw active square right
// m - Add adjacent square to surface
// n - Build new surface
// o - Roll active square right
// p - Toggle star rays for active square
// q
// r - Build with random walk
// s - Move camera backward
// t - Build full Earth with star data
// u - Roll active square left
// v
// w - Move camera forward
// x
// y
// z - Move camera down
// 0 - Reset animation state to 0
// 1 - Reset adjustment amount to 1
// - - Decrease adjustment amount
// = - Increase adjustment amount
// ; - One recommended rotation adjustment
// ' - Analyze solution space
// , - Select previous square
// . - Select next square
// / - Automatically orient active square
// Space - Move camera up
// Delete - Delete active square
// Enter - enter FPS mode
// Esc - leave FPS mode
// Ins - canned commands
// PgUp - Decrement animation state
// PgDn - Increment animation state
// Ctrl+E - build and orient to the East
// Ctrl+W - build and orient to the West
// Ctrl+N - build and orient to the North
// Ctrl+S - build and orient to the South
menuBar.add(this.buildFileMenu());
menuBar.add(this.buildDrawMenu());
menuBar.add(this.buildBuildMenu());
menuBar.add(this.buildSelectMenu());
menuBar.add(this.buildEditMenu());
menuBar.add(this.buildNavigateMenu());
menuBar.add(this.buildAnimateMenu());
menuBar.add(this.buildOptionsMenu());
menuBar.add(this.buildHelpMenu());
}
private JMenu buildFileMenu()
{
JMenu menu = new JMenu("File");
addMenuItem(menu, "Use real world astronomical observations", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new RealWorldObservations());
}
});
menu.addSeparator();
addMenuItem(menu, "Use model: spherical Earth with nearby stars", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new CloseStarObservations());
}
});
addMenuItem(menu, "Use model: azimuthal equidistant projection flat Earth", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new AzimuthalEquidistantObservations());
}
});
addMenuItem(menu, "Use model: bowl-shaped Earth", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new BowlObservations());
}
});
addMenuItem(menu, "Use model: saddle-shaped Earth", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeObservations(new SaddleObservations());
}
});
menu.addSeparator();
addMenuItem(menu, "Exit", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.dispose();
}
});
return menu;
}
private JMenu buildDrawMenu()
{
JMenu drawMenu = new JMenu("Draw");
this.drawCoordinateAxesCBItem =
addCBMenuItem(drawMenu, "Draw X/Y/Z coordinate axes", null,
this.emCanvas.drawAxes,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawAxes();
}
});
this.drawCrosshairCBItem =
addCBMenuItem(drawMenu, "Draw crosshair when in FPS camera mode", null,
this.emCanvas.drawCrosshair,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawCrosshair();
}
});
this.drawWireframeSquaresCBItem =
addCBMenuItem(drawMenu, "Draw squares as wireframes with translucent squares", null,
this.emCanvas.drawWireframeSquares,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawWireframeSquares();
}
});
this.drawCompassesCBItem =
addCBMenuItem(drawMenu, "Draw squares with compass texture (vs. world map)",
KeyStroke.getKeyStroke('c'),
this.emCanvas.drawCompasses,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawCompasses();
}
});
this.drawSurfaceNormalsCBItem =
addCBMenuItem(drawMenu, "Draw surface normals", null, this.emCanvas.drawSurfaceNormals,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawSurfaceNormals();
}
});
this.drawCelestialNorthCBItem =
addCBMenuItem(drawMenu, "Draw celestial North", null, this.emCanvas.drawCelestialNorth,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawCelestialNorth();
}
});
this.drawStarRaysCBItem =
addCBMenuItem(drawMenu, "Draw star rays for active square",
KeyStroke.getKeyStroke('p'),
this.activeSquareDrawsStarRays(),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawStarRays();
}
});
this.drawUnitStarRaysCBItem =
addCBMenuItem(drawMenu, "Draw star rays as unit vectors", null,
this.emCanvas.drawUnitStarRays,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawUnitStarRays();
}
});
this.drawBaseSquareStarRaysCBItem =
addCBMenuItem(drawMenu, "Draw star rays for the base square too, on the active square", null,
this.emCanvas.drawBaseSquareStarRays,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawBaseSquareStarRays();
}
});
this.drawTravelPathCBItem =
addCBMenuItem(drawMenu, "Draw the travel path from base square to active square", null,
this.emCanvas.drawTravelPath,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawTravelPath();
}
});
this.drawActiveSquareAtOriginCBItem =
addCBMenuItem(drawMenu, "Draw the active square at the 3D coordinate origin", null,
this.emCanvas.drawActiveSquareAtOrigin,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawActiveSquareAtOrigin();
}
});
this.drawWorldWireframeCBItem =
addCBMenuItem(drawMenu, "Draw world wireframe (if one is in use)", null,
this.emCanvas.drawWorldWireframe,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawWorldWireframe();
}
});
this.drawWorldStarsCBItem =
addCBMenuItem(drawMenu, "Draw world stars (if in use)", null,
this.emCanvas.drawWorldStars,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawWorldStars();
}
});
this.drawSkyboxCBItem =
addCBMenuItem(drawMenu, "Draw skybox", null,
this.emCanvas.drawSkybox,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.toggleDrawSkybox();
}
});
addMenuItem(drawMenu, "Set skybox distance...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setSkyboxDistance();
}
});
addMenuItem(drawMenu, "Turn off all star rays", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.turnOffAllStarRays();
}
});
return drawMenu;
}
private JMenu buildBuildMenu()
{
JMenu buildMenu = new JMenu("Build");
addMenuItem(buildMenu, "Build Earth using active observational data or model",
KeyStroke.getKeyStroke('t'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildEarthSurfaceFromStarData();
}
});
addMenuItem(buildMenu, "Build complete Earth using assumed sphere",
KeyStroke.getKeyStroke('h'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildSphericalEarthSurfaceWithLatLong();
}
});
addMenuItem(buildMenu, "Build partial Earth using assumed sphere and random walk",
KeyStroke.getKeyStroke('r'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildSphericalEarthWithRandomWalk();
}
});
addMenuItem(buildMenu, "Start a new surface using star data",
KeyStroke.getKeyStroke('n'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.startNewSurface();
}
});
addMenuItem(buildMenu, "Add another square to the surface",
KeyStroke.getKeyStroke('m'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.buildNextSquare();
}
});
buildMenu.addSeparator();
addMenuItem(buildMenu, "Create new square 9 degrees to the East and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_E, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
0 /*deltLatitude*/, +9 /*deltaLongitude*/);
}
});
addMenuItem(buildMenu, "Create new square 9 degrees to the West and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_W, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
0 /*deltLatitude*/, -9 /*deltaLongitude*/);
}
});
addMenuItem(buildMenu, "Create new square 9 degrees to the North and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_N, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
+9 /*deltLatitude*/, 0 /*deltaLongitude*/);
}
});
addMenuItem(buildMenu, "Create new square 9 degrees to the South and orient it automatically",
KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_DOWN_MASK),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.createAndAutomaticallyOrientActiveSquare(
-9 /*deltLatitude*/, 0 /*deltaLongitude*/);
}
});
buildMenu.addSeparator();
addMenuItem(buildMenu, "Do some canned setup for debugging",
KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.doCannedSetup();
}
});
return buildMenu;
}
private JMenu buildSelectMenu()
{
JMenu selectMenu = new JMenu("Select");
addMenuItem(selectMenu, "Select previous square",
KeyStroke.getKeyStroke(','),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.selectNextSquare(false /*forward*/);
}
});
addMenuItem(selectMenu, "Select next square",
KeyStroke.getKeyStroke('.'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.selectNextSquare(true /*forward*/);
}
});
return selectMenu;
}
private JMenu buildEditMenu()
{
JMenu editMenu = new JMenu("Edit");
for (RotationCommand rc : RotationCommand.values()) {
this.addAdjustOrientationMenuItem(editMenu,
rc.description, rc.key, rc.axis);
}
editMenu.addSeparator();
addMenuItem(editMenu, "Double active square adjustment angle",
KeyStroke.getKeyStroke('='),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeAdjustOrientationDegrees(2.0f);
}
});
addMenuItem(editMenu, "Halve active square adjustment angle",
KeyStroke.getKeyStroke('-'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.changeAdjustOrientationDegrees(0.5f);
}
});
addMenuItem(editMenu, "Reset active square adjustment angle to 1 degree",
KeyStroke.getKeyStroke('1'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.adjustOrientationDegrees = 1;
EarthShape.this.updateUIState();
}
});
editMenu.addSeparator();
addMenuItem(editMenu, "Analyze solution space",
KeyStroke.getKeyStroke('\''),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.analyzeSolutionSpace();
}
});
addMenuItem(editMenu, "Set solution analysis resolution...",
null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setSolutionAnalysisResolution();
}
});
editMenu.addSeparator();
addMenuItem(editMenu, "Do one recommended rotation adjustment",
KeyStroke.getKeyStroke(';'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.applyRecommendedRotationCommand();
}
});
addMenuItem(editMenu, "Automatically orient active square",
KeyStroke.getKeyStroke('/'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.automaticallyOrientActiveSquare();
}
});
addMenuItem(editMenu, "Delete active square",
KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.deleteActiveSquare();
}
});
return editMenu;
}
private JMenu buildNavigateMenu()
{
JMenu menu = new JMenu("Navigate");
addMenuItem(menu, "Control camera like a first-person shooter",
KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.enterFPSMode();
}
});
addMenuItem(menu, "Leave first-person shooter mode",
KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.exitFPSMode();
}
});
addMenuItem(menu, "Go to active square's center",
KeyStroke.getKeyStroke('g'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.goToActiveSquareCenter();
}
});
addMenuItem(menu, "Go to origin", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.moveCamera(new Vector3f(0,0,0));
}
});
menu.addSeparator();
addMenuItem(menu, "Curvature calculator...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.showCurvatureDialog();
}
});
return menu;
}
private JMenu buildAnimateMenu()
{
JMenu menu = new JMenu("Animate");
addMenuItem(menu, "Reset to animation state 0",
KeyStroke.getKeyStroke('0'),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setAnimationState(0);
}
});
addMenuItem(menu, "Increment animation state",
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setAnimationState(+1);
}
});
addMenuItem(menu, "Decrement animation state",
KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setAnimationState(-1);
}
});
return menu;
}
private JMenu buildOptionsMenu()
{
JMenu menu = new JMenu("Options");
addMenuItem(menu, "Choose enabled stars...", null, new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.chooseEnabledStars();
}
});
addMenuItem(menu, "Set maximum Sun elevation...",
null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.setMaximumSunElevation();
}
});
this.useSunElevationCBItem =
addCBMenuItem(menu, "Take Sun elevation into account", null,
this.useSunElevation,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.useSunElevation =
!EarthShape.this.useSunElevation;
EarthShape.this.updateUIState();
}
});
menu.addSeparator();
this.invertHorizontalCameraMovementCBItem =
addCBMenuItem(menu, "Invert horizontal camera movement", null,
this.emCanvas.invertHorizontalCameraMovement,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.invertHorizontalCameraMovement =
!EarthShape.this.emCanvas.invertHorizontalCameraMovement;
EarthShape.this.updateUIState();
}
});
this.invertVerticalCameraMovementCBItem =
addCBMenuItem(menu, "Invert vertical camera movement", null,
this.emCanvas.invertVerticalCameraMovement,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.emCanvas.invertVerticalCameraMovement =
!EarthShape.this.emCanvas.invertVerticalCameraMovement;
EarthShape.this.updateUIState();
}
});
menu.addSeparator();
this.newAutomaticOrientationAlgorithmCBItem =
addCBMenuItem(menu, "Use new automatic orientation algorithm", null,
this.newAutomaticOrientationAlgorithm,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.newAutomaticOrientationAlgorithm =
!EarthShape.this.newAutomaticOrientationAlgorithm;
EarthShape.this.updateUIState();
}
});
this.assumeInfiniteStarDistanceCBItem =
addCBMenuItem(menu, "Assume stars are infinitely far away", null,
this.assumeInfiniteStarDistance,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.assumeInfiniteStarDistance =
!EarthShape.this.assumeInfiniteStarDistance;
EarthShape.this.updateAndRedraw();
}
});
this.onlyCompareElevationsCBItem =
addCBMenuItem(menu, "Only compare star elevations", null,
this.onlyCompareElevations,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.onlyCompareElevations =
!EarthShape.this.onlyCompareElevations;
EarthShape.this.updateAndRedraw();
}
});
return menu;
}
private JMenu buildHelpMenu()
{
JMenu helpMenu = new JMenu("Help");
addMenuItem(helpMenu, "Show all key bindings...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.showKeyBindings();
}
});
addMenuItem(helpMenu, "About...", null,
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.showAboutBox();
}
});
return helpMenu;
}
/** Add a menu item to adjust the orientation of the active square. */
private void addAdjustOrientationMenuItem(
JMenu menu, String description, char key, Vector3f axis)
{
addMenuItem(menu, description,
KeyStroke.getKeyStroke(key),
new ActionListener() {
public void actionPerformed(ActionEvent e) {
EarthShape.this.adjustActiveSquareOrientation(axis);
}
});
}
/** Make a new menu item and add it to 'menu' with the given
* label and listener. */
private static void addMenuItem(JMenu menu, String itemLabel, KeyStroke accelerator,
ActionListener listener)
{
JMenuItem item = new JMenuItem(itemLabel);
item.addActionListener(listener);
if (accelerator != null) {
item.setAccelerator(accelerator);
}
menu.add(item);
}
private static JCheckBoxMenuItem addCBMenuItem(JMenu menu, String itemLabel, KeyStroke accelerator,
boolean initState, ActionListener listener)
{
JCheckBoxMenuItem cbItem =
new JCheckBoxMenuItem(itemLabel, initState);
cbItem.addActionListener(listener);
if (accelerator != null) {
cbItem.setAccelerator(accelerator);
}
menu.add(cbItem);
return cbItem;
}
/** Choose the set of stars to use. This only affects new
* squares. */
private void chooseEnabledStars()
{
StarListDialog d = new StarListDialog(this, this.enabledStars);
if (d.exec()) {
this.enabledStars = d.stars;
this.updateAndRedraw();
}
}
/** Clear out the virtual map and any dependent state. */
private void clearSurfaceSquares()
{
this.emCanvas.clearSurfaceSquares();
this.activeSquare = null;
}
/** Build a portion of the Earth's surface. Adds squares to
* 'surfaceSquares'. This works by iterating over latitude
* and longitude pairs and assuming a spherical Earth. It
* assumes the Earth is a sphere. */
public void buildSphericalEarthSurfaceWithLatLong()
{
log("building spherical Earth");
this.clearSurfaceSquares();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start with an arbitrary square centered at the origin
// the 3D space, and at SF, CA in the real world.
float startLatitude = 38; // 38N
float startLongitude = -122; // 122W
SurfaceSquare startSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
sizeKm,
startLatitude,
startLongitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0));
this.emCanvas.addSurfaceSquare(startSquare);
// Outer loop 1: Walk North as far as we can.
SurfaceSquare outer = startSquare;
for (float latitude = startLatitude;
latitude < 90;
latitude += 9)
{
// Go North another step.
outer = this.addSphericallyAdjacentSquare(outer, latitude, startLongitude);
// Inner loop: Walk East until we get back to
// the same longitude.
float longitude = startLongitude;
float prevLongitude = longitude;
SurfaceSquare inner = outer;
while (true) {
inner = this.addSphericallyAdjacentSquare(inner, latitude, longitude);
if (prevLongitude < outer.longitude &&
outer.longitude <= longitude) {
break;
}
prevLongitude = longitude;
longitude = FloatUtil.modulus2f(longitude+9, -180, 180);
}
}
// Outer loop 2: Walk South as far as we can.
outer = startSquare;
for (float latitude = startLatitude - 9;
latitude > -90;
latitude -= 9)
{
// Go North another step.
outer = this.addSphericallyAdjacentSquare(outer, latitude, startLongitude);
// Inner loop: Walk East until we get back to
// the same longitude.
float longitude = startLongitude;
float prevLongitude = longitude;
SurfaceSquare inner = outer;
while (true) {
inner = this.addSphericallyAdjacentSquare(inner, latitude, longitude);
if (prevLongitude < outer.longitude &&
outer.longitude <= longitude) {
break;
}
prevLongitude = longitude;
longitude = FloatUtil.modulus2f(longitude+9, -180, 180);
}
}
this.emCanvas.redrawCanvas();
log("finished building Earth; nsquares="+this.emCanvas.numSurfaceSquares());
}
/** Build the surface by walking randomly from a starting location,
* assuming a Earth is a sphere. */
public void buildSphericalEarthWithRandomWalk()
{
log("building spherical Earth by random walk");
this.clearSurfaceSquares();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start with an arbitrary square centered at the origin
// the 3D space, and at SF, CA in the real world.
float startLatitude = 38; // 38N
float startLongitude = -122; // 122W
SurfaceSquare startSquare = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
sizeKm,
startLatitude,
startLongitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0));
this.emCanvas.addSurfaceSquare(startSquare);
SurfaceSquare square = startSquare;
for (int i=0; i < 1000; i++) {
// Select a random change in latitude and longitude
// of about 10 degrees.
float deltaLatitude = (float)(Math.random() * 12 - 6);
float deltaLongitude = (float)(Math.random() * 12 - 6);
// Walk in that direction, keeping latitude and longitude
// within their usual ranges. Also stay away from the poles
// since the rounding errors cause problems there.
square = this.addSphericallyAdjacentSquare(square,
FloatUtil.clampf(square.latitude + deltaLatitude, -80, 80),
FloatUtil.modulus2f(square.longitude + deltaLongitude, -180, 180));
}
this.emCanvas.redrawCanvas();
log("finished building Earth; nsquares="+this.emCanvas.numSurfaceSquares());
}
/** Given square 'old', add an adjacent square at the given
* latitude and longitude. The relative orientation of the
* new square will determined using the latitude and longitude,
* assuming a spherical shape for the Earth.
*
* This is used by the routines that build the surface using
* the sphere assumption, not those that use star observation
* data. */
private SurfaceSquare addSphericallyAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude)
{
// Calculate local East for 'old'.
Vector3f oldEast = old.north.cross(old.up).normalize();
// Calculate celestial North for 'old', which is given by
// the latitude plus geographic North.
Vector3f celestialNorth =
old.north.rotateDeg(old.latitude, oldEast);
// Get lat/long deltas.
float deltaLatitude = newLatitude - old.latitude;
float deltaLongitude = FloatUtil.modulus2f(
newLongitude - old.longitude, -180, 180);
// If we didn't move, just return the old square.
if (deltaLongitude == 0 && deltaLatitude == 0) {
return old;
}
// What we want now is to first rotate Northward
// around local East to account for change in latitude, then
// Eastward around celestial North for change in longitude.
Vector3f firstRotation = oldEast.times(-deltaLatitude);
Vector3f secondRotation = celestialNorth.times(deltaLongitude);
// But then we want to express the composition of those as a
// single rotation vector in order to call the general routine.
Vector3f combined = Vector3f.composeRotations(firstRotation, secondRotation);
// Now call into the general procedure for adding a square
// given the proper relative orientation rotation.
return addRotatedAdjacentSquare(old, newLatitude, newLongitude, combined);
}
/** Build a surface using star data rather than any presumed
* size and shape. */
public void buildEarthSurfaceFromStarData()
{
Cursor oldCursor = this.getCursor();
this.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
ProgressDialog<Void, Void> pd =
new ProgressDialog<Void, Void>(this,
"Building Surface with model: "+this.worldObservations.getDescription(),
new BuildSurfaceTask(EarthShape.this));
pd.exec();
}
finally {
this.setCursor(oldCursor);
}
this.emCanvas.redrawCanvas();
}
/** Task to manage construction of surface.
*
* I have to use a class rather than a simple closure so I have
* something to pass to the build routines so they can set the
* status and progress as the algorithm runs. */
private static class BuildSurfaceTask extends MySwingWorker<Void, Void>
{
private EarthShape earthShape;
public BuildSurfaceTask(EarthShape earthShape_)
{
this.earthShape = earthShape_;
}
protected Void doTask() throws Exception
{
this.earthShape.buildEarthSurfaceFromStarDataInner(this);
return null;
}
}
/** Core of 'buildEarthSurfaceFromStarData', so I can more easily
* wrap computation around it. */
public void buildEarthSurfaceFromStarDataInner(BuildSurfaceTask task)
{
log("building Earth using star data: "+this.worldObservations.getDescription());
this.clearSurfaceSquares();
// Size of squares to build, in km.
float sizeKm = 1000;
// Start at approximately my location in SF, CA. This is one of
// the locations for which I have manual data, and when we build
// the first latitude strip, that will pick up the other manual
// data points.
float latitude = 38;
float longitude = -122;
SurfaceSquare square = null;
log("buildEarth: building first square at lat="+latitude+" long="+longitude);
// First square will be placed at the 3D origin with
// its North pointed along the -Z axis.
square = new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
sizeKm,
latitude,
longitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0));
this.emCanvas.addSurfaceSquare(square);
this.addMatchingData(square);
// Go East and West.
task.setStatus("Initial latitude strip at "+square.latitude);
this.buildLatitudeStrip(square, +9);
this.buildLatitudeStrip(square, -9);
// Explore in all directions until all points on
// the surface have been explored (to within 9 degrees).
this.buildLongitudeStrip(square, +9, task);
this.buildLongitudeStrip(square, -9, task);
// Reset the adjustment angle.
this.adjustOrientationDegrees = EarthShape.DEFAULT_ADJUST_ORIENTATION_DEGREES;
log("buildEarth: finished using star data; nSquares="+this.emCanvas.numSurfaceSquares());
}
/** Build squares by going North or South from a starting square
* until we add 20 or we can't add any more. At each spot, also
* build latitude strips in both directions. */
private void buildLongitudeStrip(SurfaceSquare startSquare, float deltaLatitude,
BuildSurfaceTask task)
{
float curLatitude = startSquare.latitude;
float curLongitude = startSquare.longitude;
SurfaceSquare curSquare = startSquare;
if (task.isCancelled()) {
// Bail now, rather than repeat the cancellation log message.
return;
}
while (!task.isCancelled()) {
float newLatitude = curLatitude + deltaLatitude;
if (!( -90 < newLatitude && newLatitude < 90 )) {
// Do not go past the poles.
break;
}
float newLongitude = curLongitude;
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
// Report progress.
task.setStatus("Latitude strip at "+newLatitude);
{
// +1 since we did one strip before the first call to
// buildLongitudeStrip.
float totalStrips = 180 / (float)Math.abs(deltaLatitude) + 1;
float completedStrips;
if (deltaLatitude > 0) {
completedStrips = (newLatitude - startSquare.latitude) / deltaLatitude + 1;
}
else {
completedStrips = (90 - newLatitude) / -deltaLatitude + 1;
}
float fraction = completedStrips / totalStrips;
log("progress fraction: "+fraction);
task.setProgressFraction(fraction);
}
curSquare = this.createAndAutomaticallyOrientSquare(curSquare,
newLatitude, newLongitude);
if (curSquare == null) {
log("buildEarth: could not place next square!");
break;
}
curLatitude = newLatitude;
curLongitude = newLongitude;
// Also build strips in each direction.
this.buildLatitudeStrip(curSquare, +9);
this.buildLatitudeStrip(curSquare, -9);
}
if (task.isCancelled()) {
log("surface construction canceled");
}
}
/** Build squares by going East or West from a starting square
* until we add 20 or we can't add any more. */
private void buildLatitudeStrip(SurfaceSquare startSquare, float deltaLongitude)
{
float curLatitude = startSquare.latitude;
float curLongitude = startSquare.longitude;
SurfaceSquare curSquare = startSquare;
for (int i=0; i < 20; i++) {
float newLatitude = curLatitude;
float newLongitude = FloatUtil.modulus2f(curLongitude + deltaLongitude, -180, 180);
log("buildEarth: building lat="+newLatitude+" long="+newLongitude);
curSquare = this.createAndAutomaticallyOrientSquare(curSquare,
newLatitude, newLongitude);
if (curSquare == null) {
log("buildEarth: could not place next square!");
break;
}
curLatitude = newLatitude;
curLongitude = newLongitude;
}
}
/** Create a square adjacent to 'old', positioned at the given latitude
* and longitude, with orientation changed by 'rotation'. If there is
* no change, return null. Even if not, do not add the square yet,
* just return it. */
private SurfaceSquare createRotatedAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude,
Vector3f rotation)
{
// Normalize latitude and longitude.
newLatitude = FloatUtil.clampf(newLatitude, -90, 90);
newLongitude = FloatUtil.modulus2f(newLongitude, -180, 180);
// If we didn't move, return null.
if (old.latitude == newLatitude && old.longitude == newLongitude) {
return null;
}
// Compute the new orientation vectors by rotating
// the old ones by the given amount.
Vector3f newNorth = old.north.rotateAADeg(rotation);
Vector3f newUp = old.up.rotateAADeg(rotation);
// Get observed travel details going to the new location.
TravelObservation tobs = this.worldObservations.getTravelObservation(
old.latitude, old.longitude, newLatitude, newLongitude);
// For both old and new, calculate a unit vector for the
// travel direction. Both headings are negated due to the
// right hand rule for rotation. The new to old heading is
// then flipped 180 since I want both to indicate the local
// direction from old to new.
Vector3f oldTravel = old.north.rotateDeg(-tobs.startToEndHeading, old.up);
Vector3f newTravel = newNorth.rotateDeg(-tobs.endToStartHeading + 180, newUp);
// Calculate the new square's center by going half the distance
// according to the old orientation and then half the distance
// according to the new orientation, in world coordinates.
float halfDistWorld = tobs.distanceKm / 2.0f * EarthMapCanvas.SPACE_UNITS_PER_KM;
Vector3f midPoint = old.center.plus(oldTravel.times(halfDistWorld));
Vector3f newCenter = midPoint.plus(newTravel.times(halfDistWorld));
// Make the new square and add it to the list.
SurfaceSquare ret = new SurfaceSquare(
newCenter, newNorth, newUp,
old.sizeKm,
newLatitude,
newLongitude,
old /*base*/,
midPoint,
rotation);
return ret;
}
/** Add a square adjacent to 'old', positioned at the given latitude
* and longitude, with orientation changed by 'rotation'. If we
* did not move, this returns the old square. */
private SurfaceSquare addRotatedAdjacentSquare(
SurfaceSquare old,
float newLatitude,
float newLongitude,
Vector3f rotation)
{
SurfaceSquare ret = this.createRotatedAdjacentSquare(
old, newLatitude, newLongitude, rotation);
if (ret == null) {
return old; // Did not move.
}
else {
this.emCanvas.addSurfaceSquare(ret);
}
return ret;
}
/** Get star observations for the given location, at the particular
* point in time that I am using for everything. */
private List<StarObservation> getStarObservationsFor(
float latitude, float longitude)
{
return this.worldObservations.getStarObservations(
StarObservation.unixTimeOfManualData, latitude, longitude);
}
/** Add to 'square.starObs' all entries of 'starObs' that have
* the same latitude and longitude, and also are at least
* 20 degrees above the horizon. */
private void addMatchingData(SurfaceSquare square)
{
for (StarObservation so :
this.getStarObservationsFor(square.latitude, square.longitude)) {
if (this.qualifyingStarObservation(so)) {
square.addObservation(so);
}
}
}
/** Compare star data for 'startSquare' and for the given new
* latitude and longitude. Return a rotation vector that will
* transform the orientation of 'startSquare' to match the
* best surface for a new square at the new location. The
* vector's length is the amount of rotation in degrees.
*
* Returns null if there are not enough stars in common. */
private Vector3f calcRequiredRotation(
SurfaceSquare startSquare,
float newLatitude,
float newLongitude)
{
// Set of stars visible at the start and end squares and
// above 20 degrees above the horizon.
HashMap<String, Vector3f> startStars =
getVisibleStars(startSquare.latitude, startSquare.longitude);
HashMap<String, Vector3f> endStars =
getVisibleStars(newLatitude, newLongitude);
// Current best rotation and average difference.
Vector3f currentRotation = new Vector3f(0,0,0);
// Iteratively refine the current rotation by computing the
// average correction rotation and applying it until that
// correction drops below a certain threshold.
for (int iterationCount = 0; iterationCount < 1000; iterationCount++) {
// Accumulate the vector sum of all the rotation difference
// vectors as well as the max length.
Vector3f diffSum = new Vector3f(0,0,0);
float maxDiffLength = 0;
int diffCount = 0;
for (HashMap.Entry<String, Vector3f> e : startStars.entrySet()) {
String starName = e.getKey();
Vector3f startVector = e.getValue();
Vector3f endVector = endStars.get(starName);
if (endVector == null) {
continue;
}
// Both vectors must first be rotated the way the start
// surface was rotated since its creation so that when
// we compute the final required rotation, it can be
// applied to the start surface in its existing orientation,
// not the nominal orientation that the star vectors have
// before I do this.
startVector = startVector.rotateAADeg(startSquare.rotationFromNominal);
endVector = endVector.rotateAADeg(startSquare.rotationFromNominal);
// Calculate a difference rotation vector from the
// rotated end vector to the start vector. Rotating
// the end star in one direction is like rotating
// the start terrain in the opposite direction.
Vector3f rot = endVector.rotateAADeg(currentRotation)
.rotationToBecome(startVector);
// Accumulate it.
diffSum = diffSum.plus(rot);
maxDiffLength = (float)Math.max(maxDiffLength, rot.length());
diffCount++;
}
if (diffCount < 2) {
log("reqRot: not enough stars");
return null;
}
// Calculate the average correction rotation.
Vector3f avgDiff = diffSum.times(1.0f / diffCount);
// If the correction angle is small enough, stop. For any set
// of observations, we should be able to drive the average
// difference arbitrarily close to zero (this is like finding
// the centroid, except in spherical rather than flat space).
// The real question is whether the *maximum* difference is
// large enough to indicate that the data is inconsistent.
if (avgDiff.length() < 0.001) {
log("reqRot finished: iters="+iterationCount+
" avgDiffLen="+avgDiff.length()+
" maxDiffLength="+maxDiffLength+
" diffCount="+diffCount);
if (maxDiffLength > 0.2) {
// For the data I am working with, I estimate it is
// accurate to within 0.2 degrees. Consequently,
// there should not be a max difference that large.
log("reqRot: WARNING: maxDiffLength greater than 0.2");
}
return currentRotation;
}
// Otherwise, apply it to the current rotation and
// iterate again.
currentRotation = currentRotation.plus(avgDiff);
}
log("reqRot: hit iteration limit!");
return currentRotation;
}
/** True if the given observation is available for use, meaning
* it is high enough in the sky, is enabled, and not obscured
* by light from the Sun. */
private boolean qualifyingStarObservation(StarObservation so)
{
if (this.sunIsTooHigh(so.latitude, so.longitude)) {
return false;
}
return so.elevation >= 20.0f &&
this.enabledStars.containsKey(so.name) &&
this.enabledStars.get(so.name) == true;
}
/** Return true if, at StarObservation.unixTimeOfManualData, the
* Sun is too high in the sky to see stars. This depends on
* the configurable parameter 'maximumSunElevation'. */
private boolean sunIsTooHigh(float latitude, float longitude)
{
if (!this.useSunElevation) {
return false;
}
StarObservation sun = this.worldObservations.getSunObservation(
StarObservation.unixTimeOfManualData, latitude, longitude);
if (sun == null) {
return false;
}
return sun.elevation > this.maximumSunElevation;
}
/** For every visible star vislble at the specified coordinate
* that has an elevation of at least 20 degrees,
* add it to a map from star name to azEl vector. */
private HashMap<String, Vector3f> getVisibleStars(
float latitude,
float longitude)
{
HashMap<String, Vector3f> ret = new HashMap<String, Vector3f>();
for (StarObservation so :
this.getStarObservationsFor(latitude, longitude)) {
if (this.qualifyingStarObservation(so)) {
ret.put(so.name,
Vector3f.azimuthElevationToVector(so.azimuth, so.elevation));
}
}
return ret;
}
/** Get the unit ray, in world coordinates, from the center of 'square' to
* the star recorded in 'so', which was observed at this square. */
public static Vector3f rayToStar(SurfaceSquare square, StarObservation so)
{
// Ray to star in nominal, -Z facing, coordinates.
Vector3f nominalRay =
Vector3f.azimuthElevationToVector(so.azimuth, so.elevation);
// Ray to star in world coordinates, taking into account
// how the surface is rotated.
Vector3f worldRay = nominalRay.rotateAADeg(square.rotationFromNominal);
return worldRay;
}
/** Hold results of call to 'fitOfObservations'. */
private static class ObservationStats {
/** The total variance in star observation locations from the
* indicated square to the observations of its base square as the
* average square of the deviation angles.
*
* The reason for using a sum of squares approach is to penalize large
* deviations and to ensure there is a unique "least deviated" point
* (which need not exist when using a simple sum). The reason for using
* the average is to make it easier to judge "good" or "bad" fits,
* regardless of the number of star observations in common.
*
* I use the term "variance" here because it is similar to the idea in
* statistics, except here we are measuring differences between pairs of
* observations, rather than between individual observations and the mean
* of the set. I'll then reserve "deviation", if I use it, to refer to
* the square root of the variance, by analogy with "standard deviation".
* */
public double variance;
/** Maximum separation between observations, in degrees. */
public double maxSeparation;
/** Number of pairs of stars used in comparison. */
public int numSamples;
}
/** Calculate variance and maximum separation for 'square'. Returns
* null if there is no base or there are no observations in common. */
private ObservationStats fitOfObservations(SurfaceSquare square)
{
if (square.baseSquare == null) {
return null;
}
double sumOfSquares = 0;
int numSamples = 0;
double maxSeparation = 0;
for (Map.Entry<String, StarObservation> entry : square.starObs.entrySet()) {
StarObservation so = entry.getValue();
// Ray to star in world coordinates.
Vector3f starRay = EarthShape.rayToStar(square, so);
// Calculate the deviation of this observation from that of
// the base square.
StarObservation baseObservation = square.baseSquare.findObservation(so.name);
if (baseObservation != null) {
// Get ray from base square to the base observation star
// in world coordinates.
Vector3f baseStarRay = EarthShape.rayToStar(square.baseSquare, baseObservation);
// Visual separation angle between these rays.
double sep;
if (this.assumeInfiniteStarDistance) {
sep = this.getStarRayDifference(
square.up, starRay, baseStarRay);
}
else {
sep = EarthShape.getModifiedClosestApproach(
square.center, starRay,
square.baseSquare.center, baseStarRay).separationAngleDegrees;
}
if (sep > maxSeparation) {
maxSeparation = sep;
}
// Accumulate its square.
sumOfSquares += sep * sep;
numSamples++;
}
}
if (numSamples == 0) {
return null;
}
else {
ObservationStats ret = new ObservationStats();
ret.variance = sumOfSquares / numSamples;
ret.maxSeparation = maxSeparation;
ret.numSamples = numSamples;
return ret;
}
}
/** Get closest approach, except with a modification to
* smooth out the search space. */
public static Vector3d.ClosestApproach getModifiedClosestApproach(
Vector3f p1f, Vector3f u1f,
Vector3f p2f, Vector3f u2f)
{
Vector3d p1 = new Vector3d(p1f);
Vector3d u1 = new Vector3d(u1f);
Vector3d p2 = new Vector3d(p2f);
Vector3d u2 = new Vector3d(u2f);
Vector3d.ClosestApproach ca = Vector3d.getClosestApproach(p1, u1, p2, u2);
if (ca.line1Closest != null) {
// Now, there is a problem if the closest approach is behind
// either observer. Not only does that not make logical sense,
// but naively using the calculation will cause the search
// space to be very lumpy, which creates local minima that my
// hill-climbing algorithm gets trapped in. So, we require
// that the points on each observation line be at least one
// unit away, which currently means 1000 km. That smooths out
// the search space so the hill climber will find its way to
// the optimal solution more reliably.
// How far along u1 is the closest approach?
double m1 = ca.line1Closest.minus(p1).dot(u1);
if (m1 < 1.0) {
// That is unreasonably close. Push the approach point
// out to one unit away along u1.
ca.line1Closest = p1.plus(u1);
// Find the closest point on (p2,u2) to that point.
ca.line2Closest = ca.line1Closest.closestPointOnLine(p2, u2);
// Recalculate the separation angle to that point.
ca.separationAngleDegrees = u1.separationAngleDegrees(ca.line2Closest.minus(p1));
}
// How far along u2?
double m2 = ca.line2Closest.minus(p2).dot(u2);
if (m2 < 1.0) {
// Too close; push it.
ca.line2Closest = p2.plus(u2);
// What is closest on (p1,u1) to that?
ca.line1Closest = ca.line2Closest.closestPointOnLine(p1, u1);
// Re-check if that is too close to p1.
if (ca.line1Closest.minus(p1).dot(u1) < 1.0) {
// Push it without changing line2Closest.
ca.line1Closest = p1.plus(u1);
}
// Recalculate the separation angle to that point.
ca.separationAngleDegrees = u1.separationAngleDegrees(ca.line2Closest.minus(p1));
}
}
return ca;
}
/** Get the difference between the two star rays, for a location
* with given unit 'up' vector, in degrees. This depends on the
* option setting 'onlyCompareElevations'. */
public double getStarRayDifference(
Vector3f up,
Vector3f ray1,
Vector3f ray2)
{
if (this.onlyCompareElevations) {
return EarthShape.getElevationDifference(up, ray1, ray2);
}
else {
return ray1.separationAngleDegrees(ray2);
}
}
/** Given two star observation rays at a location with the given
* 'up' unit vector, return the difference in elevation between
* them, ignoring azimuth, in degrees. */
private static double getElevationDifference(
Vector3f up,
Vector3f ray1,
Vector3f ray2)
{
double e1 = getElevation(up, ray1);
double e2 = getElevation(up, ray2);
return Math.abs(e1-e2);
}
/** Return the elevation of 'ray' at a location with unit 'up'
* vector, in degrees. */
private static double getElevation(Vector3f up, Vector3f ray)
{
// Decompose into vertical and horizontal components.
Vector3f v = ray.projectOntoUnitVector(up);
Vector3f h = ray.minus(v);
// Get lengths, with vertical possibly negative if below
// horizon.
double vLen = ray.dot(up);
double hLen = h.length();
// Calculate corresponding angle.
return FloatUtil.atan2Deg(vLen, hLen);
}
/** Begin constructing a new surface using star data. This just
* places down the initial square to represent a user-specified
* latitude and longitude. The square is placed into 3D space
* at a fixed location. */
public void startNewSurface()
{
LatLongDialog d = new LatLongDialog(this, 38, -122);
if (d.exec()) {
this.startNewSurfaceAt(d.finalLatitude, d.finalLongitude);
}
}
/** Same as 'startNewSurface' but at a specified location. */
public void startNewSurfaceAt(float latitude, float longitude)
{
log("starting new surface at lat="+latitude+", lng="+longitude);
this.clearSurfaceSquares();
this.setActiveSquare(new SurfaceSquare(
new Vector3f(0,0,0), // center
new Vector3f(0,0,-1), // north
new Vector3f(0,1,0), // up
INITIAL_SQUARE_SIZE_KM,
latitude,
longitude,
null /*base*/, null /*midpoint*/,
new Vector3f(0,0,0)));
this.addMatchingData(this.activeSquare);
this.emCanvas.addSurfaceSquare(this.activeSquare);
this.emCanvas.redrawCanvas();
}
/** Get the active square, or null if none. */
public SurfaceSquare getActiveSquare()
{
return this.activeSquare;
}
/** Change which square is active, but do not trigger a redraw. */
public void setActiveSquareNoRedraw(SurfaceSquare sq)
{
if (this.activeSquare != null) {
this.activeSquare.showAsActive = false;
}
this.activeSquare = sq;
if (this.activeSquare != null) {
this.activeSquare.showAsActive = true;
}
}
/** Change which square is active. */
public void setActiveSquare(SurfaceSquare sq)
{
this.setActiveSquareNoRedraw(sq);
this.updateAndRedraw();
}
/** Add another square to the surface by building one adjacent
* to the active square. */
private void buildNextSquare()
{
if (this.activeSquare == null) {
this.errorBox("No square is active.");
return;
}
LatLongDialog d = new LatLongDialog(this,
this.activeSquare.latitude, this.activeSquare.longitude + 9);
if (d.exec()) {
this.buildNextSquareAt(d.finalLatitude, d.finalLongitude);
}
}
/** Same as 'buildNextSquare' except at a specified location. */
private void buildNextSquareAt(float latitude, float longitude)
{
// The new square should draw star rays if the old did.
boolean drawStarRays = this.activeSquare.drawStarRays;
// Add it initially with no rotation. My plan is to add
// the rotation interactively afterward.
this.setActiveSquare(
this.addRotatedAdjacentSquare(this.activeSquare,
latitude, longitude, new Vector3f(0,0,0)));
this.activeSquare.drawStarRays = drawStarRays;
// Reset the rotation angle after adding a square.
this.adjustOrientationDegrees = DEFAULT_ADJUST_ORIENTATION_DEGREES;
this.addMatchingData(this.activeSquare);
this.emCanvas.redrawCanvas();
}
/** If there is an active square, assume we just built it, and now
* we want to adjust its orientation. 'axis' indicates the axis
* about which to rotate, relative to the square's current orientation,
* where -Z is North, +Y is up, and +X is east, and the angle is given
* by 'this.adjustOrientationDegrees'. */
private void adjustActiveSquareOrientation(Vector3f axis)
{
SurfaceSquare derived = this.activeSquare;
if (derived == null) {
this.errorBox("No active square.");
return;
}
SurfaceSquare base = derived.baseSquare;
if (base == null) {
this.errorBox("The active square has no base square.");
return;
}
// Replace the active square.
this.setActiveSquare(
this.adjustDerivedSquareOrientation(axis, derived, this.adjustOrientationDegrees));
this.emCanvas.redrawCanvas();
}
/** Adjust the orientation of 'derived' by 'adjustDegrees' around
* 'axis', where 'axis' is relative to the square's current
* orientation. */
private SurfaceSquare adjustDerivedSquareOrientation(Vector3f axis,
SurfaceSquare derived, float adjustDegrees)
{
SurfaceSquare base = derived.baseSquare;
// Rotate by 'adjustOrientationDegrees'.
Vector3f angleAxis = axis.times(adjustDegrees);
// Rotate the axis to align it with the square.
angleAxis = angleAxis.rotateAADeg(derived.rotationFromNominal);
// Now add that to the square's existing rotation relative
// to its base square.
angleAxis = Vector3f.composeRotations(derived.rotationFromBase, angleAxis);
// Now, replace it.
return this.replaceWithNewRotation(base, derived, angleAxis);
}
/** Replace the square 'derived', with a new square that
* is computed from 'base' by applying 'newRotation'.
* Return the new square. */
public SurfaceSquare replaceWithNewRotation(
SurfaceSquare base, SurfaceSquare derived, Vector3f newRotation)
{
// Replace the derived square with a new one created by
// rotating from the same base by this new amount.
this.emCanvas.removeSurfaceSquare(derived);
SurfaceSquare ret =
this.addRotatedAdjacentSquare(base,
derived.latitude, derived.longitude, newRotation);
// Copy some other data from the derived square that we
// are in the process of discarding.
ret.drawStarRays = derived.drawStarRays;
ret.starObs = derived.starObs;
return ret;
}
/** Calculate what the variation of observations would be for
* 'derived' if its orientation were adjusted by
* 'angleAxis.degrees()' around 'angleAxis'. Returns null if
* the calculation cannot be done because of missing information. */
private ObservationStats fitOfAdjustedSquare(
SurfaceSquare derived, Vector3f angleAxis)
{
// This part mirrors 'adjustActiveSquareOrientation'.
SurfaceSquare base = derived.baseSquare;
if (base == null) {
return null;
}
angleAxis = angleAxis.rotateAADeg(derived.rotationFromNominal);
angleAxis = Vector3f.composeRotations(derived.rotationFromBase, angleAxis);
// Now, create a new square with this new rotation.
SurfaceSquare newSquare =
this.createRotatedAdjacentSquare(base,
derived.latitude, derived.longitude, angleAxis);
if (newSquare == null) {
// If we do not move, use the original square's data.
return this.fitOfObservations(derived);
}
// Copy the observation data since that is needed to calculate
// the deviation.
newSquare.starObs = derived.starObs;
// Now calculate the new variance.
return this.fitOfObservations(newSquare);
}
/** Like 'fitOfAdjustedSquare' except only retrieves the
* variance. This returns 40000 if the data is unavailable. */
private double varianceOfAdjustedSquare(
SurfaceSquare derived, Vector3f angleAxis)
{
ObservationStats os = this.fitOfAdjustedSquare(derived, angleAxis);
if (os == null) {
// The variance should never be greater than 180 squared,
// since that would be the worst possible fit for a star.
return 40000;
}
else {
return os.variance;
}
}
/** Change 'adjustOrientationDegrees' by the given multiplier. */
private void changeAdjustOrientationDegrees(float multiplier)
{
this.adjustOrientationDegrees *= multiplier;
if (this.adjustOrientationDegrees < MINIMUM_ADJUST_ORIENTATION_DEGREES) {
this.adjustOrientationDegrees = MINIMUM_ADJUST_ORIENTATION_DEGREES;
}
this.updateUIState();
}
/** Compute and apply a single step rotation command to improve
* the variance of the active square. */
private void applyRecommendedRotationCommand()
{
SurfaceSquare s = this.activeSquare;
if (s == null) {
this.errorBox("No active square.");
return;
}
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
this.errorBox("Not enough observational data available.");
return;
}
if (ostats.variance == 0) {
this.errorBox("Orientation is already optimal.");
return;
}
// Get the recommended rotation.
VarianceAfterRotations var = this.getVarianceAfterRotations(s,
this.adjustOrientationDegrees);
if (var.bestRC == null) {
if (this.adjustOrientationDegrees <= MINIMUM_ADJUST_ORIENTATION_DEGREES) {
this.errorBox("Cannot further improve orientation.");
return;
}
else {
this.changeAdjustOrientationDegrees(0.5f);
}
}
else {
this.adjustActiveSquareOrientation(var.bestRC.axis);
}
this.updateAndRedraw();
}
/** Apply the recommended rotation to 's' until convergence. Return
* the improved square, or null if that is not possible due to
* insufficient constraints. */
private SurfaceSquare repeatedlyApplyRecommendedRotationCommand(SurfaceSquare s)
{
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null || ostats.numSamples < 2) {
return null; // Underconstrained.
}
if (ostats.variance == 0) {
return s; // Already optimal.
}
// Rotation amount. This will be gradually reduced.
float adjustDegrees = 1.0f;
// Iteration cap for safety.
int iters = 0;
// Iterate until the adjust amount is too small.
while (adjustDegrees > MINIMUM_ADJUST_ORIENTATION_DEGREES) {
// Get the recommended rotation.
VarianceAfterRotations var = this.getVarianceAfterRotations(s, adjustDegrees);
if (var == null) {
return null;
}
if (var.underconstrained) {
log("repeatedlyApply: solution is underconstrained, adjustDegrees="+ adjustDegrees);
return s;
}
if (var.bestRC == null) {
adjustDegrees = adjustDegrees * 0.5f;
// Set the UI adjust degrees to what we came up with here so I
// can easily see where it ended up.
this.adjustOrientationDegrees = adjustDegrees;
}
else {
s = this.adjustDerivedSquareOrientation(var.bestRC.axis, s, adjustDegrees);
}
if (++iters > 1000) {
log("repeatedlyApply: exceeded iteration cap!");
break;
}
}
// Get the final variance.
String finalVariance = "null";
ostats = this.fitOfObservations(s);
if (ostats != null) {
finalVariance = ""+ostats.variance;
}
log("repeatedlyApply done: iters="+iters+" adj="+ adjustDegrees+
" var="+finalVariance);
return s;
}
/** Delete the active square. */
private void deleteActiveSquare()
{
if (this.activeSquare == null) {
this.errorBox("No active square.");
return;
}
this.emCanvas.removeSurfaceSquare(this.activeSquare);
this.setActiveSquare(null);
}
/** Calculate and apply the optimal orientation for the active square;
* make its replacement active if we do replace it.. */
private void automaticallyOrientActiveSquare()
{
SurfaceSquare derived = this.activeSquare;
if (derived == null) {
this.errorBox("No active square.");
return;
}
SurfaceSquare base = derived.baseSquare;
if (base == null) {
this.errorBox("The active square has no base square.");
return;
}
SurfaceSquare newDerived = automaticallyOrientSquare(derived);
if (newDerived == null) {
this.errorBox("Insufficient observations to determine proper orientation.");
}
else {
this.setActiveSquare(newDerived);
}
this.updateAndRedraw();
}
/** Given a square 'derived' that is known to have a base square,
* adjust and/or replace it with one with a better orientation,
* and return the improved square. Returns null if improvement
* is not possible due to insufficient observational data. */
private SurfaceSquare automaticallyOrientSquare(SurfaceSquare derived)
{
if (this.newAutomaticOrientationAlgorithm) {
return this.repeatedlyApplyRecommendedRotationCommand(derived);
}
else {
// Calculate the best rotation.
Vector3f rot = calcRequiredRotation(derived.baseSquare,
derived.latitude, derived.longitude);
if (rot == null) {
return null;
}
// Now, replace the active square.
return this.replaceWithNewRotation(derived.baseSquare, derived, rot);
}
}
/** Make the next square in 'emCanvas.surfaceSquares' active. */
private void selectNextSquare(boolean forward)
{
this.setActiveSquare(this.emCanvas.getNextSquare(this.activeSquare, forward));
}
/** Build a square offset from the active square, set its orientation,
* and make it active. If we cannot make a new square, report that as
* an error and leave the active square alone. */
private void createAndAutomaticallyOrientActiveSquare(
float deltaLatitude, float deltaLongitude)
{
SurfaceSquare base = this.activeSquare;
if (base == null) {
this.errorBox("There is no active square.");
return;
}
SurfaceSquare newSquare = this.createAndAutomaticallyOrientSquare(
base, base.latitude + deltaLatitude, base.longitude + deltaLongitude);
if (newSquare == null) {
ModalDialog.errorBox(this,
"Cannot place new square since observational data does not uniquely determine its orientation.");
}
else {
newSquare.drawStarRays = base.drawStarRays;
this.setActiveSquare(newSquare);
}
}
/** Build a square adjacent to the base square, set its orientation,
* and return it. Returns null and adds nothing if such a square
* cannot be uniquely oriented. */
private SurfaceSquare createAndAutomaticallyOrientSquare(SurfaceSquare base,
float newLatitude, float newLongitude)
{
// Make a new adjacent square, initially with the same orientation
// as the base square.
SurfaceSquare newSquare =
this.addRotatedAdjacentSquare(base,
newLatitude,
newLongitude,
new Vector3f(0,0,0));
if (base == newSquare) {
return base; // Did not move, no new square created.
}
this.addMatchingData(newSquare);
// Now try to set its orientation to match observations.
SurfaceSquare adjustedSquare = this.automaticallyOrientSquare(newSquare);
if (adjustedSquare == null) {
// No unique solution; remove the new square too.
this.emCanvas.removeSurfaceSquare(newSquare);
}
return adjustedSquare;
}
/** Show the user what the local rotation space looks like by.
* considering the effect of rotating various amounts on each axis. */
private void analyzeSolutionSpace()
{
if (this.activeSquare == null) {
this.errorBox("No active square.");
return;
}
SurfaceSquare s = this.activeSquare;
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
this.errorBox("No observation fitness stats for the active square.");
return;
}
// Prepare a task object in which to run the analysis.
AnalysisTask task = new AnalysisTask(this, s);
// Show a progress dialog while this run.
ProgressDialog<PlotData3D, Void> progressDialog =
new ProgressDialog<PlotData3D, Void>(this,
"Analyzing rotations of active square...", task);
// Run the dialog and the task.
if (progressDialog.exec()) {
// Retrieve the computed data.
PlotData3D rollPitchYawPlotData;
try {
rollPitchYawPlotData = task.get();
}
catch (Exception e) {
String msg = "Internal error: solution space analysis failed: "+e.getMessage();
log(msg);
e.printStackTrace();
this.errorBox(msg);
return;
}
// Plot results.
RotationCubeDialog d = new RotationCubeDialog(this,
(float)ostats.variance,
rollPitchYawPlotData);
d.exec();
}
else {
log("Analysis canceled.");
}
}
/** Task to analyze the solution space near a square, which can take a
* while if 'solutionAnalysisPointsPerSide' is high. */
private static class AnalysisTask extends MySwingWorker<PlotData3D, Void> {
/** Enclosing EarthShape instance. */
private EarthShape earthShape;
/** Square whose solution will be analyzed. */
private SurfaceSquare square;
public AnalysisTask(
EarthShape earthShape_,
SurfaceSquare square_)
{
this.earthShape = earthShape_;
this.square = square_;
}
@Override
protected PlotData3D doTask() throws Exception
{
return this.earthShape.getThreeRotationAxisPlotData(this.square, this);
}
}
/** Get data for various rotation angles of all three axes.
*
* This runs in a worker thread. However, I haven't bothered
* to synchronize access since the user shouldn't be able to
* do anything while this is happening (although they can...),
* and most of the shared data is immutable. */
private PlotData3D getThreeRotationAxisPlotData(SurfaceSquare s, AnalysisTask task)
{
// Number of data points on each side of 0.
int pointsPerSide = this.solutionAnalysisPointsPerSide;
// Total number of data points per axis, including 0.
int pointsPerAxis = pointsPerSide * 2 + 1;
// Complete search space cube.
float[] wData = new float[pointsPerAxis * pointsPerAxis * pointsPerAxis];
Vector3f xAxis = new Vector3f(0, 0, -1); // Roll
Vector3f yAxis = new Vector3f(1, 0, 0); // Pitch
Vector3f zAxis = new Vector3f(0, -1, 0); // Yaw
float xFirst = -pointsPerSide * this.adjustOrientationDegrees;
float xLast = pointsPerSide * this.adjustOrientationDegrees;
float yFirst = -pointsPerSide * this.adjustOrientationDegrees;
float yLast = pointsPerSide * this.adjustOrientationDegrees;
float zFirst = -pointsPerSide * this.adjustOrientationDegrees;
float zLast = pointsPerSide * this.adjustOrientationDegrees;
for (int zIndex=0; zIndex < pointsPerAxis; zIndex++) {
if (task.isCancelled()) {
log("analysis canceled");
return null; // Bail out.
}
task.setProgressFraction(zIndex / (float)pointsPerAxis);
task.setStatus("Analyzing plane "+(zIndex+1)+" of "+pointsPerAxis);
for (int yIndex=0; yIndex < pointsPerAxis; yIndex++) {
for (int xIndex=0; xIndex < pointsPerAxis; xIndex++) {
// Compose rotations about each axis: X then Y then Z.
//
// Note: Rotations don't commute, so the axes are not
// being treated perfectly symmetrically here, but this
// is still good for showing overall shape, and when
// we zoom in to small angles, the non-commutativity
// becomes insignificant.
Vector3f rotX = xAxis.times(this.adjustOrientationDegrees * (xIndex - pointsPerSide));
Vector3f rotY = yAxis.times(this.adjustOrientationDegrees * (yIndex - pointsPerSide));
Vector3f rotZ = zAxis.times(this.adjustOrientationDegrees * (zIndex - pointsPerSide));
Vector3f rot = Vector3f.composeRotations(
Vector3f.composeRotations(rotX, rotY), rotZ);
// Get variance after that adjustment.
wData[xIndex + pointsPerAxis * yIndex + pointsPerAxis * pointsPerAxis * zIndex] =
(float)this.varianceOfAdjustedSquare(s, rot);
}
}
}
return new PlotData3D(
xFirst, xLast,
yFirst, yLast,
zFirst, zLast,
pointsPerAxis /*xValuesPerRow*/,
pointsPerAxis /*yValuesPerColumn*/,
wData);
}
/** Show a dialog to let the user change
* 'solutionAnalysisPointsPerSide'. */
private void setSolutionAnalysisResolution()
{
String choice = JOptionPane.showInputDialog(this,
"Specify number of data points on each side of 0 to sample "+
"when performing a solution analysis",
(Integer)this.solutionAnalysisPointsPerSide);
if (choice != null) {
try {
int c = Integer.valueOf(choice);
if (c < 1) {
this.errorBox("The minimum number of points is 1.");
}
else if (c > 100) {
// At 100, it will take about a minute to complete.
this.errorBox("The maximum number of points is 100.");
}
else {
this.solutionAnalysisPointsPerSide = c;
}
}
catch (NumberFormatException e) {
this.errorBox("Invalid integer syntax: "+e.getMessage());
}
}
}
/** Prompt the user for a floating-point value. Returns null if the
* user cancels or enters an invalid value. In the latter case, an
* error box has already been shown. */
private Float floatInputDialog(String label, float curValue)
{
String choice = JOptionPane.showInputDialog(this, label, (Float)curValue);
if (choice != null) {
try {
return Float.valueOf(choice);
}
catch (NumberFormatException e) {
this.errorBox("Invalid float syntax: "+e.getMessage());
return null;
}
}
else {
return null;
}
}
/** Let the user specify a new maximum Sun elevation. */
private void setMaximumSunElevation()
{
Float newValue = this.floatInputDialog(
"Specify maximum elevation of the Sun in degrees "+
"above the horizon (otherwise, stars are not visible)",
this.maximumSunElevation);
if (newValue != null) {
this.maximumSunElevation = newValue;
}
}
/** Let the user specify the distance to the skybox. */
private void setSkyboxDistance()
{
Float newValue = this.floatInputDialog(
"Specify distance in 3D space units (each of which usually "+
"represents 1000km of surface) to the skybox.\n"+
"A value of 0 means the skybox is infinitely far away.",
this.emCanvas.skyboxDistance);
if (newValue != null) {
if (newValue < 0) {
this.errorBox("The skybox distance must be non-negative.");
}
else {
this.emCanvas.skyboxDistance = newValue;
this.updateAndRedraw();
}
}
}
/** Make this window visible. */
public void makeVisible()
{
this.setVisible(true);
// It seems I can only set the focus once the window is
// visible. There is an example in the focus tutorial of
// calling pack() first, but that resizes the window and
// I don't want that.
this.emCanvas.setFocusOnCanvas();
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable() {
public void run() {
(new EarthShape()).makeVisible();
}
});
}
public void toggleDrawAxes()
{
this.emCanvas.drawAxes = !this.emCanvas.drawAxes;
this.updateAndRedraw();
}
public void toggleDrawCrosshair()
{
this.emCanvas.drawCrosshair = !this.emCanvas.drawCrosshair;
this.updateAndRedraw();
}
/** Toggle the 'drawWireframeSquares' flag. */
public void toggleDrawWireframeSquares()
{
this.emCanvas.drawWireframeSquares = !this.emCanvas.drawWireframeSquares;
this.updateAndRedraw();
}
/** Toggle the 'drawCompasses' flag, then update state and redraw. */
public void toggleDrawCompasses()
{
log("toggleDrawCompasses");
// The compass flag is ignored when wireframe is true, so if
// we are toggling compass, also clear wireframe.
this.emCanvas.drawWireframeSquares = false;
this.emCanvas.drawCompasses = !this.emCanvas.drawCompasses;
this.updateAndRedraw();
}
/** Toggle the 'drawSurfaceNormals' flag. */
public void toggleDrawSurfaceNormals()
{
this.emCanvas.drawSurfaceNormals = !this.emCanvas.drawSurfaceNormals;
this.updateAndRedraw();
}
/** Toggle the 'drawCelestialNorth' flag. */
public void toggleDrawCelestialNorth()
{
this.emCanvas.drawCelestialNorth = !this.emCanvas.drawCelestialNorth;
this.updateAndRedraw();
}
/** Toggle the 'drawStarRays' flag. */
public void toggleDrawStarRays()
{
if (this.activeSquare == null) {
this.errorBox("No square is active");
}
else {
this.activeSquare.drawStarRays = !this.activeSquare.drawStarRays;
}
this.emCanvas.redrawCanvas();
}
private void toggleDrawUnitStarRays()
{
this.emCanvas.drawUnitStarRays = !this.emCanvas.drawUnitStarRays;
this.updateAndRedraw();
}
private void toggleDrawBaseSquareStarRays()
{
this.emCanvas.drawBaseSquareStarRays = !this.emCanvas.drawBaseSquareStarRays;
this.updateAndRedraw();
}
private void toggleDrawTravelPath()
{
this.emCanvas.drawTravelPath = !this.emCanvas.drawTravelPath;
this.updateAndRedraw();
}
private void toggleDrawActiveSquareAtOrigin()
{
this.emCanvas.drawActiveSquareAtOrigin = !this.emCanvas.drawActiveSquareAtOrigin;
this.updateAndRedraw();
}
private void toggleDrawWorldWireframe()
{
this.emCanvas.drawWorldWireframe = !this.emCanvas.drawWorldWireframe;
this.updateAndRedraw();
}
private void toggleDrawWorldStars()
{
this.emCanvas.drawWorldStars = !this.emCanvas.drawWorldStars;
this.updateAndRedraw();
}
private void toggleDrawSkybox()
{
this.emCanvas.drawSkybox = !this.emCanvas.drawSkybox;
this.updateAndRedraw();
}
private void turnOffAllStarRays()
{
this.emCanvas.turnOffAllStarRays();
this.emCanvas.redrawCanvas();
}
/** Move the camera to the center of the active square. */
private void goToActiveSquareCenter()
{
if (this.activeSquare == null) {
this.errorBox("No active square.");
}
else {
this.moveCamera(this.activeSquare.center);
}
}
/** Place the camera at the specified location. */
private void moveCamera(Vector3f loc)
{
this.emCanvas.cameraPosition = loc;
this.updateAndRedraw();
}
/** Update all stateful UI elements. */
public void updateUIState()
{
this.setStatusLabel();
this.setMenuState();
this.setInfoPanel();
}
/** Set the status label text to reflect other state variables.
* This also updates the state of stateful menu items. */
private void setStatusLabel()
{
StringBuilder sb = new StringBuilder();
sb.append(this.emCanvas.getStatusString());
sb.append(", model="+this.worldObservations.getDescription());
this.statusLabel.setText(sb.toString());
}
/** Set the state of stateful menu items. */
private void setMenuState()
{
this.drawCoordinateAxesCBItem.setSelected(this.emCanvas.drawAxes);
this.drawCrosshairCBItem.setSelected(this.emCanvas.drawCrosshair);
this.drawWireframeSquaresCBItem.setSelected(this.emCanvas.drawWireframeSquares);
this.drawCompassesCBItem.setSelected(this.emCanvas.drawCompasses);
this.drawSurfaceNormalsCBItem.setSelected(this.emCanvas.drawSurfaceNormals);
this.drawCelestialNorthCBItem.setSelected(this.emCanvas.drawCelestialNorth);
this.drawStarRaysCBItem.setSelected(this.activeSquareDrawsStarRays());
this.drawUnitStarRaysCBItem.setSelected(this.emCanvas.drawUnitStarRays);
this.drawBaseSquareStarRaysCBItem.setSelected(this.emCanvas.drawBaseSquareStarRays);
this.drawTravelPathCBItem.setSelected(this.emCanvas.drawTravelPath);
this.drawActiveSquareAtOriginCBItem.setSelected(this.emCanvas.drawActiveSquareAtOrigin);
this.drawWorldWireframeCBItem.setSelected(this.emCanvas.drawWorldWireframe);
this.drawWorldStarsCBItem.setSelected(this.emCanvas.drawWorldStars);
this.drawSkyboxCBItem.setSelected(this.emCanvas.drawSkybox);
this.useSunElevationCBItem.setSelected(this.useSunElevation);
this.invertHorizontalCameraMovementCBItem.setSelected(
this.emCanvas.invertHorizontalCameraMovement);
this.invertVerticalCameraMovementCBItem.setSelected(
this.emCanvas.invertVerticalCameraMovement);
this.newAutomaticOrientationAlgorithmCBItem.setSelected(
this.newAutomaticOrientationAlgorithm);
this.assumeInfiniteStarDistanceCBItem.setSelected(
this.assumeInfiniteStarDistance);
this.onlyCompareElevationsCBItem.setSelected(
this.onlyCompareElevations);
}
/** Update the contents of the info panel. */
private void setInfoPanel()
{
StringBuilder sb = new StringBuilder();
if (this.emCanvas.activeSquareAnimationState != 0) {
sb.append("Animation state: "+this.emCanvas.activeSquareAnimationState+"\n");
}
if (this.activeSquare == null) {
sb.append("No active square.\n");
}
else {
sb.append("Active square:\n");
SurfaceSquare s = this.activeSquare;
sb.append(" lat/lng: ("+s.latitude+","+s.longitude+")\n");
sb.append(" pos: "+s.center+"\n");
sb.append(" rot: "+s.rotationFromNominal+"\n");
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
sb.append(" No obs stats\n");
}
else {
sb.append(" maxSep: "+ostats.maxSeparation+"\n");
sb.append(" sqrtVar: "+(float)Math.sqrt(ostats.variance)+"\n");
sb.append(" var: "+ostats.variance+"\n");
// What do we recommend to improve the variance? If it is
// already zero, nothing. Otherwise, start by thinking we
// should decrease the rotation angle.
char recommendation = (ostats.variance == 0? ' ' : '-');
// What is the best rotation command, and what does it achieve?
VarianceAfterRotations var = this.getVarianceAfterRotations(s,
this.adjustOrientationDegrees);
// Print the effects of all the available rotations.
sb.append("\n");
for (RotationCommand rc : RotationCommand.values()) {
sb.append(" adj("+rc.key+"): ");
Double newVariance = var.rcToVariance.get(rc);
if (newVariance == null) {
sb.append("(none)\n");
}
else {
sb.append(""+newVariance+"\n");
}
}
// Make a final recommendation.
if (var.bestRC != null) {
recommendation = var.bestRC.key;
}
sb.append(" recommend: "+recommendation+"\n");
}
}
sb.append("\n");
sb.append("adjDeg: "+this.adjustOrientationDegrees+"\n");
// Compute average curvature from base.
if (this.activeSquare != null && this.activeSquare.baseSquare != null) {
sb.append("\n");
sb.append("Base at: ("+this.activeSquare.baseSquare.latitude+
","+this.activeSquare.baseSquare.longitude+")\n");
CurvatureCalculator cc = this.computeAverageCurvature(this.activeSquare);
double normalCurvatureDegPer1000km =
FloatUtil.radiansToDegrees(cc.normalCurvature*1000);
sb.append("Normal curvature: "+(float)normalCurvatureDegPer1000km+" deg per 1000 km\n");
if (cc.normalCurvature != 0) {
sb.append("Radius: "+(float)(1/cc.normalCurvature)+" km\n");
}
else {
sb.append("Radius: Infinite\n");
}
sb.append("Geodesic curvature: "+(float)(cc.geodesicCurvature*1000.0)+" deg per 1000 km\n");
sb.append("Geodesic torsion: "+(float)(cc.geodesicTorsion*1000.0)+" deg per 1000 km\n");
}
// Also show star observation data.
if (this.activeSquare != null) {
sb.append("\n");
sb.append("Visible stars (az, el):\n");
// Iterate over stars in name order.
TreeSet<String> stars = new TreeSet<String>(this.activeSquare.starObs.keySet());
for (String starName : stars) {
StarObservation so = this.activeSquare.starObs.get(starName);
sb.append(" "+so.name+": "+so.azimuth+", "+so.elevation+"\n");
}
}
this.infoPanel.setText(sb.toString());
}
/** Compute the average curvature on a path from the base square
* of 's' to 's'. */
private CurvatureCalculator computeAverageCurvature(SurfaceSquare s)
{
// Travel distance and heading.
TravelObservation tobs = this.worldObservations.getTravelObservation(
s.baseSquare.latitude, s.baseSquare.longitude,
s.latitude, s.longitude);
// Unit travel vector in base square coordinate system.
Vector3f startTravel = Vector3f.headingToVector((float)tobs.startToEndHeading);
startTravel = startTravel.rotateAADeg(s.baseSquare.rotationFromNominal);
// And at derived square.
Vector3f endTravel = Vector3f.headingToVector((float)tobs.endToStartHeading + 180);
endTravel = endTravel.rotateAADeg(s.rotationFromNominal);
// Calculate curvature and twist.
CurvatureCalculator c = new CurvatureCalculator();
c.distanceKm = tobs.distanceKm;
c.computeFromNormals(s.baseSquare.up, s.up, startTravel, endTravel);
return c;
}
/** Result of call to 'getVarianceAfterRotations'. */
private static class VarianceAfterRotations {
/** Variance produced by each rotation. The value can be null,
* meaning the rotation produces a situation where we can't
* measure the variance (e.g., because not enough stars are
* above the horizon). */
public HashMap<RotationCommand, Double> rcToVariance = new HashMap<RotationCommand, Double>();
/** Which rotation command produces the greatest improvement
* in variance, if any. */
public RotationCommand bestRC = null;
/** If true, the solution space is underconstrained, meaning
* the best orientation is not unique. */
public boolean underconstrained = false;
}
/** Perform a trial rotation in each direction and record the
* resulting variance, plus a decision about which is best, if any.
* This returns null if we do not have enough data to measure
* the fitness of the square's orientation. */
private VarianceAfterRotations getVarianceAfterRotations(SurfaceSquare s,
float adjustDegrees)
{
// Get variance if no rotation is performed. We only recommend
// a rotation if it improves on this.
ObservationStats ostats = this.fitOfObservations(s);
if (ostats == null) {
return null;
}
VarianceAfterRotations ret = new VarianceAfterRotations();
// Variance achieved by the best rotation command, if there is one.
double bestNewVariance = 0;
// Get the effects of all the available rotations.
for (RotationCommand rc : RotationCommand.values()) {
ObservationStats newStats = this.fitOfAdjustedSquare(s,
rc.axis.times(adjustDegrees));
if (newStats == null || newStats.numSamples < 2) {
ret.rcToVariance.put(rc, null);
}
else {
double newVariance = newStats.variance;
ret.rcToVariance.put(rc, newVariance);
if (ostats.variance == 0 && newVariance == 0) {
// The current orientation is ideal, but here
// is a rotation that keeps it ideal. That
// must mean that the solution space is under-
// constrained.
//
// Note: This is an unnecessarily strong condition for
// being underconstrained. It requires that we
// find a zero in the objective function, and
// furthermore that the solution space be parallel
// to one of the three local rotation axes. I have
// some ideas for more robust detection of underconstraint,
// but haven't tried to implement them yet. For now I
// will rely on manual inspection of the rotation cube
// analysis dialog.
ret.underconstrained = true;
}
if (newVariance < ostats.variance &&
(ret.bestRC == null || newVariance < bestNewVariance))
{
ret.bestRC = rc;
bestNewVariance = newVariance;
}
}
}
return ret;
}
/** True if there is an active square and it is drawing star rays. */
private boolean activeSquareDrawsStarRays()
{
return this.activeSquare != null &&
this.activeSquare.drawStarRays;
}
/** Replace the current observations with a new source and clear
* the virtual map. */
private void changeObservations(WorldObservations obs)
{
this.clearSurfaceSquares();
this.worldObservations = obs;
// Enable all stars in the new model.
this.enabledStars.clear();
for (String starName : this.worldObservations.getAllStars()) {
this.enabledStars.put(starName, true);
}
this.updateAndRedraw();
}
/** Refresh all the UI elements and the map canvas. */
private void updateAndRedraw()
{
this.updateUIState();
this.emCanvas.redrawCanvas();
}
/** Return true if the named star is enabled. */
public boolean isStarEnabled(String starName)
{
return this.enabledStars.containsKey(starName) &&
this.enabledStars.get(starName).equals(true);
}
/** Do some initial steps so I do not have to do them manually each
* time I start the program when I'm working on a certain feature.
* The exact setup here will vary over time as I work on different
* things; it is only meant for use while testing or debugging. */
private void doCannedSetup()
{
// Disable all stars except for Betelgeuse and Dubhe.
this.enabledStars.clear();
for (String starName : this.worldObservations.getAllStars()) {
boolean en = (starName.equals("Betelgeuse") || starName.equals("Dubhe"));
this.enabledStars.put(starName, en);
}
// Build first square in SF as usual.
this.startNewSurfaceAt(38, -122);
// Build next near Washington, DC.
this.buildNextSquareAt(38, -77);
// The plan is to align with just two stars, so we need this.
this.assumeInfiniteStarDistance = true;
// Position the camera to see DC square.
if (this.emCanvas.drawActiveSquareAtOrigin) {
// This is a canned command in the middle of a session.
// Do not reposition the camera.
}
else {
this.emCanvas.drawActiveSquareAtOrigin = true;
// this.emCanvas.cameraPosition = new Vector3f(-0.19f, 0.56f, 1.20f);
// this.emCanvas.cameraAzimuthDegrees = 0.0f;
// this.emCanvas.cameraPitchDegrees = -11.0f;
this.emCanvas.cameraPosition = new Vector3f(-0.89f, 0.52f, -1.06f);
this.emCanvas.cameraAzimuthDegrees = 214.0f;
this.emCanvas.cameraPitchDegrees = 1.0f;
}
// Use wireframes for squares, no world wireframe, but add surface normals.
this.emCanvas.drawWireframeSquares = true;
this.emCanvas.drawWorldWireframe = false;
this.emCanvas.drawSurfaceNormals = true;
this.emCanvas.drawTravelPath = false;
// Show its star rays, and those at SF, as unit vectors.
this.activeSquare.drawStarRays = true;
this.emCanvas.drawBaseSquareStarRays = true;
this.emCanvas.drawUnitStarRays = true;
// Reset the animation.
this.emCanvas.activeSquareAnimationState = 0;
this.updateAndRedraw();
}
/** Set the animation state either to 0, or to an amount
* offset by 's'. */
private void setAnimationState(int s)
{
if (s == 0) {
this.emCanvas.activeSquareAnimationState = 0;
}
else {
this.emCanvas.activeSquareAnimationState += s;
}
this.updateAndRedraw();
}
// ------------------------------- Animation --------------------------------
/** When animation begins, this is the rotation of the active
* square relative to its base. */
private Vector3f animatedRotationStartRotation;
/** Angle through which to rotate the active square. */
private double animatedRotationAngle;
/** Axis about which to rotate the active square. */
private Vector3f animatedRotationAxis;
/** Seconds the animation should take to complete. */
private float animatedRotationSeconds;
/** How many seconds have elapsed since we started animating.
* This is clamped to 'animatedRotationSeconds', and when
* it is equal, the animation is complete. */
private float animatedRotationElapsed;
/** Start a new rotation animation of the active square by
* 'angle' degrees about 'axis' for 'seconds'. */
public void beginAnimatedRotation(double angle, Vector3f axis, float seconds)
{
if (this.activeSquare != null &&
this.activeSquare.baseSquare != null)
{
log("starting rotation animation");
this.animatedRotationStartRotation = this.activeSquare.rotationFromBase;
this.animatedRotationAngle = angle;
this.animatedRotationAxis = axis;
this.animatedRotationSeconds = seconds;
this.animatedRotationElapsed = 0;
}
}
/** If animating, advance to the next frame, based on 'deltaSeconds'
* having elapsed since the last animated frame.
*
* This should *not* trigger a redraw, since that will cause this
* function to be called again during the same frame. */
public void nextAnimatedRotationFrame(float deltaSeconds)
{
if (this.animatedRotationElapsed < this.animatedRotationSeconds &&
this.activeSquare != null &&
this.activeSquare.baseSquare != null)
{
this.animatedRotationElapsed = FloatUtil.clampf(
this.animatedRotationElapsed + deltaSeconds, 0, this.animatedRotationSeconds);
// How much do we want the square to be rotated,
// relative to its orientation at the start of
// the animation?
double rotFraction = this.animatedRotationElapsed / this.animatedRotationSeconds;
Vector3f partialRot = this.animatedRotationAxis.timesd(
this.animatedRotationAngle * rotFraction);
// Compose with the original orientation.
Vector3f newRotationFromBase =
Vector3f.composeRotations(this.animatedRotationStartRotation, partialRot);
SurfaceSquare s = replaceWithNewRotation(
this.activeSquare.baseSquare, this.activeSquare, newRotationFromBase);
this.setActiveSquareNoRedraw(s);
if (this.animatedRotationElapsed >= this.animatedRotationSeconds) {
log("rotation animation finished; normal: "+s.up);
}
}
}
/** Do any "physics" world updates. This is invoked prior to
* rendering a frame in the GL canvas. */
public void updatePhysics(float elapsedSeconds)
{
this.nextAnimatedRotationFrame(elapsedSeconds);
}
/** Get list of stars for which both squares have observations. */
private List<String> getCommonStars(SurfaceSquare s1, SurfaceSquare s2)
{
ArrayList<String> ret = new ArrayList<String>();
for (Map.Entry<String, StarObservation> entry : s1.starObs.entrySet()) {
if (s2.findObservation(entry.getKey()) != null) {
ret.add(entry.getKey());
}
}
return ret;
}
private void showCurvatureDialog()
{
// Default initial values.
CurvatureCalculator c = CurvatureCalculator.getDubheSirius();
// Try to populate 'c' with values from the current square.
if (this.activeSquare != null && this.activeSquare.baseSquare != null) {
SurfaceSquare start = this.activeSquare.baseSquare;
SurfaceSquare end = this.activeSquare;
List<String> common = getCommonStars(start, end);
if (common.size() >= 2) {
// When Dubhe and Betelgeuse are the only ones, I want
// Dubhe first so the calculation agrees with the ad-hoc
// animation, and doing them in this order accomplishes
// that.
String A = common.get(1);
String B = common.get(0);
log("initializing curvature dialog with "+A+" and "+B);
c.start_A_az = start.findObservation(A).azimuth;
c.start_A_el = start.findObservation(A).elevation;
c.start_B_az = start.findObservation(B).azimuth;
c.start_B_el = start.findObservation(B).elevation;
c.end_A_az = end.findObservation(A).azimuth;
c.end_A_el = end.findObservation(A).elevation;
c.end_B_az = end.findObservation(B).azimuth;
c.end_B_el = end.findObservation(B).elevation;
c.setTravelByLatLong(start.latitude, start.longitude, end.latitude, end.longitude);
}
}
// Run the dialog.
(new CurvatureCalculatorDialog(EarthShape.this, c)).exec();
}
}
// EOF
|
Java
|
var searchData=
[
['lcd_2ec',['lcd.c',['../lcd_8c.html',1,'']]],
['lcd_2eh',['lcd.h',['../lcd_8h.html',1,'']]],
['light_2ec',['light.c',['../light_8c.html',1,'']]],
['light_2eh',['light.h',['../light_8h.html',1,'']]]
];
|
Java
|
/*
Copyright (c) 2014, Lars Brubaker
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. 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.
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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using MatterHackers.VectorMath;
namespace MatterHackers.PolygonMesh
{
public static class FaceBspTree
{
private static readonly double considerCoplaner = .1;
/// <summary>
/// This function will search for the first face that produces no polygon cuts
/// and split the tree on it. If it can't find a non-cutting face,
/// it will split on the face that minimizes the area that it divides.
/// </summary>
/// <param name="mesh"></param>
/// <returns></returns>
public static BspNode Create(Mesh mesh, int maxFacesToTest = 10, bool tryToBalanceTree = false)
{
BspNode root = new BspNode();
var sourceFaces = Enumerable.Range(0, mesh.Faces.Count).ToList();
var faces = Enumerable.Range(0, mesh.Faces.Count).ToList();
CreateNoSplittingFast(mesh, sourceFaces, root, faces, maxFacesToTest, tryToBalanceTree);
return root;
}
/// <summary>
/// Get an ordered list of the faces to render based on the camera position.
/// </summary>
/// <param name="node"></param>
/// <param name="meshToViewTransform"></param>
/// <param name="invMeshToViewTransform"></param>
/// <param name="faceRenderOrder"></param>
public static IEnumerable<int> GetFacesInVisibiltyOrder(Mesh mesh, BspNode root, Matrix4X4 meshToViewTransform, Matrix4X4 invMeshToViewTransform)
{
var renderOrder = new Stack<BspNode>(new BspNode[] { root.RenderOrder(mesh, meshToViewTransform, invMeshToViewTransform) });
do
{
var lastBack = renderOrder.Peek().BackNode;
while (lastBack != null
&& lastBack.Index != -1)
{
renderOrder.Peek().BackNode = null;
renderOrder.Push(lastBack.RenderOrder(mesh, meshToViewTransform, invMeshToViewTransform));
lastBack = renderOrder.Peek().BackNode;
}
var node = renderOrder.Pop();
if (node.Index != -1)
{
yield return node.Index;
}
var lastFront = node.FrontNode;
if (lastFront != null && lastFront.Index != -1)
{
renderOrder.Push(lastFront.RenderOrder(mesh, meshToViewTransform, invMeshToViewTransform));
}
} while (renderOrder.Any());
}
private static (double, int) CalculateCrossingArea(Mesh mesh, int faceIndex, List<int> faces, double smallestCrossingArrea)
{
double negativeDistance = 0;
double positiveDistance = 0;
int negativeSideCount = 0;
int positiveSideCount = 0;
int checkFace = faces[faceIndex];
var pointOnCheckFace = mesh.Vertices[mesh.Faces[faces[faceIndex]].v0];
for (int i = 0; i < faces.Count; i++)
{
if (i < faces.Count && i != faceIndex)
{
var iFace = mesh.Faces[faces[i]];
var vertexIndices = new int[] { iFace.v0, iFace.v1, iFace.v2 };
foreach (var vertexIndex in vertexIndices)
{
double distanceToPlan = mesh.Faces[checkFace].normal.Dot(mesh.Vertices[vertexIndex] - pointOnCheckFace);
if (Math.Abs(distanceToPlan) > considerCoplaner)
{
if (distanceToPlan < 0)
{
// Take the square of this distance to penalize far away points
negativeDistance += (distanceToPlan * distanceToPlan);
}
else
{
positiveDistance += (distanceToPlan * distanceToPlan);
}
if (negativeDistance > smallestCrossingArrea
&& positiveDistance > smallestCrossingArrea)
{
return (double.MaxValue, int.MaxValue);
}
}
}
if (negativeDistance > positiveDistance)
{
negativeSideCount++;
}
else
{
positiveSideCount++;
}
}
}
// return whatever side is small as our rating of badness (0 being good)
return (Math.Min(negativeDistance, positiveDistance), Math.Abs(negativeSideCount - positiveSideCount));
}
private static void CreateBackAndFrontFaceLists(Mesh mesh, int faceIndex, List<int> faces, List<int> backFaces, List<int> frontFaces)
{
var checkFaceIndex = faces[faceIndex];
var checkFace = mesh.Faces[checkFaceIndex];
var pointOnCheckFace = mesh.Vertices[mesh.Faces[checkFaceIndex].v0];
for (int i = 0; i < faces.Count; i++)
{
if (i != faceIndex)
{
bool backFace = true;
var vertexIndices = new int[] { checkFace.v0, checkFace.v1, checkFace.v2 };
foreach (var vertexIndex in vertexIndices)
{
double distanceToPlan = mesh.Faces[checkFaceIndex].normal.Dot(mesh.Vertices[vertexIndex] - pointOnCheckFace);
if (Math.Abs(distanceToPlan) > considerCoplaner)
{
if (distanceToPlan > 0)
{
backFace = false;
}
}
}
if (backFace)
{
// it is a back face
backFaces.Add(faces[i]);
}
else
{
// it is a front face
frontFaces.Add(faces[i]);
}
}
}
}
private static void CreateNoSplittingFast(Mesh mesh, List<int> sourceFaces, BspNode node, List<int> faces, int maxFacesToTest, bool tryToBalanceTree)
{
if (faces.Count == 0)
{
return;
}
int bestFaceIndex = -1;
double smallestCrossingArrea = double.MaxValue;
int bestBalance = int.MaxValue;
// find the first face that does not split anything
int step = Math.Max(1, faces.Count / maxFacesToTest);
for (int i = 0; i < faces.Count; i += step)
{
// calculate how much of polygons cross this face
(double crossingArrea, int balance) = CalculateCrossingArea(mesh, i, faces, smallestCrossingArrea);
// keep track of the best face so far
if (crossingArrea < smallestCrossingArrea)
{
smallestCrossingArrea = crossingArrea;
bestBalance = balance;
bestFaceIndex = i;
if (crossingArrea == 0
&& !tryToBalanceTree)
{
break;
}
}
else if (crossingArrea == smallestCrossingArrea
&& balance < bestBalance)
{
// the crossing area is the same but the tree balance is better
bestBalance = balance;
bestFaceIndex = i;
}
}
node.Index = sourceFaces.IndexOf(faces[bestFaceIndex]);
// put the behind stuff in a list
var backFaces = new List<int>();
var frontFaces = new List<int>();
CreateBackAndFrontFaceLists(mesh, bestFaceIndex, faces, backFaces, frontFaces);
CreateNoSplittingFast(mesh, sourceFaces, node.BackNode = new BspNode(), backFaces, maxFacesToTest, tryToBalanceTree);
CreateNoSplittingFast(mesh, sourceFaces, node.FrontNode = new BspNode(), frontFaces, maxFacesToTest, tryToBalanceTree);
}
}
public class BspNode
{
public BspNode BackNode { get; internal set; }
public BspNode FrontNode { get; internal set; }
public int Index { get; internal set; } = -1;
}
public static class BspNodeExtensions
{
public static BspNode RenderOrder(this BspNode node, Mesh mesh, Matrix4X4 meshToViewTransform, Matrix4X4 invMeshToViewTransform)
{
var faceNormalInViewSpace = mesh.Faces[node.Index].normal.TransformNormalInverse(invMeshToViewTransform);
var pointOnFaceInViewSpace = mesh.Vertices[mesh.Faces[node.Index].v0].Transform(meshToViewTransform);
var infrontOfFace = faceNormalInViewSpace.Dot(pointOnFaceInViewSpace) < 0;
if (infrontOfFace)
{
return new BspNode()
{
Index = node.Index,
BackNode = node.BackNode,
FrontNode = node.FrontNode
};
}
else
{
return new BspNode()
{
Index = node.Index,
BackNode = node.FrontNode,
FrontNode = node.BackNode
};
}
}
}
}
|
Java
|
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace LabVIEW_CLI
{
class Program
{
static bool connected = false;
static bool stop = false;
static int Main(string[] args)
{
int exitCode = 0;
Output output = Output.Instance;
string[] cliArgs, lvArgs;
lvComms lvInterface = new lvComms();
lvMsg latestMessage = new lvMsg("NOOP", "");
LvLauncher launcher = null;
CliOptions options = new CliOptions();
lvVersion current = LvVersions.CurrentVersion;
splitArguments(args, out cliArgs, out lvArgs);
//CommandLine.Parser.Default.ParseArguments(cliArgs, options);
if(!CommandLine.Parser.Default.ParseArguments(cliArgs, options))
{
Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
}
if (options.Version)
{
output.writeMessage(Assembly.GetExecutingAssembly().GetName().Version.ToString());
Environment.Exit(0);
}
output.setVerbose(options.Verbose);
output.writeInfo("LabVIEW CLI Started - Verbose Mode");
output.writeInfo("Version " + Assembly.GetExecutingAssembly().GetName().Version);
output.writeInfo("LabVIEW CLI Arguments: " + String.Join(" ", cliArgs));
output.writeInfo("Arguments passed to LabVIEW: " + String.Join(" ", lvArgs));
if (options.noLaunch)
{
output.writeMessage("Auto Launch Disabled");
// disable timeout if noLaunch is specified
options.timeout = -1;
}
else
{
// check launch vi
if(options.LaunchVI == null)
{
output.writeError("No launch VI supplied!");
return 1;
}
if (!File.Exists(options.LaunchVI))
{
output.writeError("File \"" + options.LaunchVI + "\" does not exist!");
return 1;
}
List<string> permittedExtensions = new List<string>{ ".vi", ".lvproj" };
string ext = Path.GetExtension(options.LaunchVI).ToLower();
if (!permittedExtensions.Contains(ext))
{
output.writeError("Cannot handle *" + ext + " files");
return 1;
}
try
{
launcher = new LvLauncher(options.LaunchVI, lvPathFinder(options), lvInterface.port, lvArgs);
launcher.Exited += Launcher_Exited;
launcher.Start();
}
catch(KeyNotFoundException ex)
{
// Fail gracefully if lv-ver option cannot be resolved
string bitness = options.x64 ? " 64bit" : string.Empty;
output.writeError("LabVIEW version \"" + options.lvVer + bitness + "\" not found!");
output.writeMessage("Available LabVIEW versions are:");
foreach(var ver in LvVersions.Versions)
{
output.writeMessage(ver.ToString());
}
return 1;
}
catch(FileNotFoundException ex)
{
output.writeError(ex.Message);
return 1;
}
}
// wait for the LabVIEW application to connect to the cli
connected = lvInterface.waitOnConnection(options.timeout);
// if timed out, kill LabVIEW and exit with error code
if (!connected && launcher!=null)
{
output.writeError("Connection to LabVIEW timed out!");
launcher.Kill();
launcher.Exited -= Launcher_Exited;
return 1;
}
do
{
latestMessage = lvInterface.readMessage();
switch (latestMessage.messageType)
{
case "OUTP":
Console.Write(latestMessage.messageData);
break;
case "EXIT":
exitCode = lvInterface.extractExitCode(latestMessage.messageData);
output.writeMessage("Recieved Exit Code " + exitCode);
stop = true;
break;
case "RDER":
exitCode = 1;
output.writeError("Read Error");
stop = true;
break;
default:
output.writeError("Unknown Message Type Recieved:" + latestMessage.messageType);
break;
}
} while (!stop);
lvInterface.Close();
return exitCode;
}
private static void Launcher_Exited(object sender, EventArgs e)
{
// Just quit by force if the tcp connection was not established or if LabVIEW exited without sending "EXIT" or "RDER"
if (!connected || !stop)
{
Output output = Output.Instance;
output.writeError("LabVIEW terminated unexpectedly!");
Environment.Exit(1);
}
}
private static void splitArguments(string[] args, out string[] cliArgs, out string[] lvArgs)
{
int splitterLocation = -1;
for(int i = 0; i < args.Length; i++)
{
if(args[i] == "--")
{
splitterLocation = i;
}
}
if(splitterLocation > 0)
{
cliArgs = args.Take(splitterLocation).ToArray();
lvArgs = args.Skip(splitterLocation + 1).ToArray();
}
else
{
cliArgs = args;
lvArgs = new string[0];
}
}
private static string lvPathFinder(CliOptions options)
{
if (options.lvExe != null)
{
if (!File.Exists(options.lvExe))
throw new FileNotFoundException("specified executable not found", options.lvExe);
return options.lvExe;
}
if (options.lvVer != null)
{
try
{
return LvVersions.ResolveVersionString(options.lvVer, options.x64).ExePath;
}
catch(KeyNotFoundException ex)
{
throw; // So the exception makes it to the handler above.
}
}
if (LvVersions.CurrentVersion != null)
{
return LvVersions.CurrentVersion.ExePath;
}
else
{
throw new FileNotFoundException("No LabVIEW.exe found...", "LabVIEW.exe");
}
}
}
}
|
Java
|
from celery.task import Task
import requests
class StracksFlushTask(Task):
def run(self, url, data):
requests.post(url + "/", data=data)
|
Java
|
/*
* Ferox, a graphics and game library in Java
*
* Copyright (c) 2012, Michael Ludwig
* All rights reserved.
*
* 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.
*
* 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 HOLDER 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.
*/
package com.ferox.math.bounds;
import com.ferox.math.*;
/**
* <p/>
* Frustum represents the mathematical construction of a frustum. It is described as a 6 sided convex hull,
* where at least two planes are parallel to each other. It supports generating frustums that represent
* perspective projections (a truncated pyramid), or orthographic projections (a rectangular prism).
* <p/>
* Each frustum has a direction vector and an up vector. These vectors define an orthonormal basis for the
* frustum. The two parallel planes of the frustum are specified as distances along the direction vector (near
* and far). The additional planes are computed based on the locations of the four corners of the near plane
* intersection.
* <p/>
* The mapping from world space to frustum space is not as straight-forward as is implied by the above state.
* Frustum provides the functionality to get the {@link #getProjectionMatrix() project matrix} and {@link
* #getViewMatrix() modelview matrix} suitable for use in an OpenGL system. The camera within an OpenGL system
* looks down its local negative z-axis. Thus the provided direction in this Frustum represents the negative
* z-axis within camera space.
*
* @author Michael Ludwig
*/
public class Frustum {
/**
* Result of a frustum test against a {@link AxisAlignedBox}.
*/
public static enum FrustumIntersection {
/**
* Returned when a candidate object is fully enclosed by the Frustum.
*/
INSIDE,
/**
* Returned when a candidate object is completely outside of the Frustum.
*/
OUTSIDE,
/**
* Returned when a candidate object intersects the Frustum but is not completely contained.
*/
INTERSECT
}
public static final int NUM_PLANES = 6;
public static final int NEAR_PLANE = 0;
public static final int FAR_PLANE = 1;
public static final int TOP_PLANE = 2;
public static final int BOTTOM_PLANE = 3;
public static final int LEFT_PLANE = 4;
public static final int RIGHT_PLANE = 5;
private boolean useOrtho;
// local values
private double frustumLeft;
private double frustumRight;
private double frustumTop;
private double frustumBottom;
private double frustumNear;
private double frustumFar;
// frustum orientation
private final Vector3 up;
private final Vector3 direction;
private final Vector3 location;
private final Matrix4 projection;
private final Matrix4 view;
// planes representing frustum, adjusted for
// position, direction and up
private final Vector4[] worldPlanes;
// temporary vector used during intersection queries, saved to avoid allocation
private final Vector3 temp;
/**
* Instantiate a new Frustum that's positioned at the origin, looking down the negative z-axis. The given
* values are equivalent to those described in setPerspective() and are used for the initial frustum
* parameters.
*
* @param fov
* @param aspect
* @param znear
* @param zfar
*/
public Frustum(double fov, double aspect, double znear, double zfar) {
this();
setPerspective(fov, aspect, znear, zfar);
}
/**
* Instantiate a new Frustum that's positioned at the origin, looking down the negative z-axis. The six
* values are equivalent to those specified in setFrustum() and are taken as the initial frustum
* parameters.
*
* @param ortho True if the frustum values are for an orthographic projection, otherwise it's a
* perspective projection
* @param fl
* @param fr
* @param fb
* @param ft
* @param fn
* @param ff
*/
public Frustum(boolean ortho, double fl, double fr, double fb, double ft, double fn, double ff) {
this();
setFrustum(ortho, fl, fr, fb, ft, fn, ff);
}
// initialize everything
private Frustum() {
worldPlanes = new Vector4[6];
location = new Vector3();
up = new Vector3(0, 1, 0);
direction = new Vector3(0, 0, -1);
view = new Matrix4();
projection = new Matrix4();
temp = new Vector3();
}
/**
* Get the left edge of the near frustum plane.
*
* @return The left edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumLeft() {
return frustumLeft;
}
/**
* Get the right edge of the near frustum plane.
*
* @return The right edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumRight() {
return frustumRight;
}
/**
* Get the top edge of the near frustum plane.
*
* @return The top edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumTop() {
return frustumTop;
}
/**
* Get the bottom edge of the near frustum plane.
*
* @return The bottom edge of the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumBottom() {
return frustumBottom;
}
/**
* Get the distance to the near frustum plane from the origin, in camera coords.
*
* @return The distance to the near frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumNear() {
return frustumNear;
}
/**
* Get the distance to the far frustum plane from the origin, in camera coords.
*
* @return The distance to the far frustum plane
*
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public double getFrustumFar() {
return frustumFar;
}
/**
* <p/>
* Sets the dimensions of the viewing frustum in camera coords. left, right, bottom, and top specify edges
* of the rectangular near plane. This plane is positioned perpendicular to the viewing direction, a
* distance near along the direction vector from the view's location.
* <p/>
* If this Frustum is using orthogonal projection, the frustum is a rectangular prism extending from this
* near plane, out to an identically sized plane, that is distance far away. If not, the far plane is the
* far extent of a pyramid with it's point at the location, truncated at the near plane.
*
* @param ortho True if the Frustum should use an orthographic projection
* @param left The left edge of the near frustum plane
* @param right The right edge of the near frustum plane
* @param bottom The bottom edge of the near frustum plane
* @param top The top edge of the near frustum plane
* @param near The distance to the near frustum plane
* @param far The distance to the far frustum plane
*
* @throws IllegalArgumentException if left > right, bottom > top, near > far, or near <= 0 when the view
* isn't orthographic
*/
public void setFrustum(boolean ortho, double left, double right, double bottom, double top, double near,
double far) {
if (left > right || bottom > top || near > far) {
throw new IllegalArgumentException("Frustum values would create an invalid frustum: " + left +
" " +
right + " x " + bottom + " " + top + " x " + near + " " + far);
}
if (near <= 0 && !ortho) {
throw new IllegalArgumentException("Illegal value for near frustum when using perspective projection: " +
near);
}
frustumLeft = left;
frustumRight = right;
frustumBottom = bottom;
frustumTop = top;
frustumNear = near;
frustumFar = far;
useOrtho = ortho;
update();
}
/**
* Set the frustum to be perspective projection with the given field of view (in degrees). Widths and
* heights are calculated using the assumed aspect ration and near and far values. Because perspective
* transforms only make sense for non-orthographic projections, it also sets this view to be
* non-orthographic.
*
* @param fov The field of view
* @param aspect The aspect ratio of the view region (width / height)
* @param near The distance from the view's location to the near camera plane
* @param far The distance from the view's location to the far camera plane
*
* @throws IllegalArgumentException if fov is outside of (0, 180], or aspect is <= 0, or near > far, or if
* near <= 0
*/
public void setPerspective(double fov, double aspect, double near, double far) {
if (fov <= 0f || fov > 180f) {
throw new IllegalArgumentException("Field of view must be in (0, 180], not: " + fov);
}
if (aspect <= 0) {
throw new IllegalArgumentException("Aspect ration must be >= 0, not: " + aspect);
}
double h = Math.tan(Math.toRadians(fov * .5f)) * near;
double w = h * aspect;
setFrustum(false, -w, w, -h, h, near, far);
}
/**
* Set the frustum to be an orthographic projection that uses the given boundary edges for the near
* frustum plane. The near value is set to -1, and the far value is set to 1.
*
* @param left
* @param right
* @param bottom
* @param top
*
* @throws IllegalArgumentException if left > right or bottom > top
* @see #setFrustum(boolean, double, double, double, double, double, double)
*/
public void setOrtho(double left, double right, double bottom, double top) {
setFrustum(true, left, right, bottom, top, -1f, 1f);
}
/**
* Whether or not this view uses a perspective or orthogonal projection.
*
* @return True if the projection matrix is orthographic
*/
public boolean isOrthogonalProjection() {
return useOrtho;
}
/**
* <p/>
* Get the location vector of this view, in world space. The returned vector is read-only. Modifications
* to the frustum's view parameters must be done through {@link #setOrientation(Vector3, Vector3,
* Vector3)}.
*
* @return The location of the view
*/
public
@Const
Vector3 getLocation() {
return location;
}
/**
* <p/>
* Get the up vector of this view, in world space. Together up and direction form a right-handed
* coordinate system. The returned vector is read-only. Modifications to the frustum's view parameters
* must be done through {@link #setOrientation(Vector3, Vector3, Vector3)}.
*
* @return The up vector of this view
*/
public
@Const
Vector3 getUp() {
return up;
}
/**
* <p/>
* Get the direction vector of this frustum, in world space. Together up and direction form a right-handed
* coordinate system. The returned vector is read-only. Modifications to the frustum's view parameters
* must be done through {@link #setOrientation(Vector3, Vector3, Vector3)}.
*
* @return The current direction that this frustum is pointing
*/
public
@Const
Vector3 getDirection() {
return direction;
}
/**
* Compute and return the field of view along the vertical axis that this Frustum uses. This is
* meaningless for an orthographic projection, and returns -1 in that case. Otherwise, an angle in degrees
* is returned in the range 0 to 180. This works correctly even when the bottom and top edges of the
* Frustum are not centered about its location.
*
* @return The field of view of this Frustum
*/
public double getFieldOfView() {
if (useOrtho) {
return -1f;
}
double fovTop = Math.atan(frustumTop / frustumNear);
double fovBottom = Math.atan(frustumBottom / frustumNear);
return Math.toDegrees(fovTop - fovBottom);
}
/**
* <p/>
* Return the 4x4 projection matrix that represents the mathematical projection from the frustum to
* homogenous device coordinates (essentially the unit cube).
* <p/>
* <p/>
* The returned matrix is read-only and will be updated automatically as the projection of the Frustum
* changes.
*
* @return The projection matrix
*/
public
@Const
Matrix4 getProjectionMatrix() {
return projection;
}
/**
* <p/>
* Return the 'view' transform of this Frustum. The view transform represents the coordinate space
* transformation from world space to camera/frustum space. The local basis of the Frustum is formed by
* the left, up and direction vectors of the Frustum. The left vector is <code>up X direction</code>, and
* up and direction are user defined vectors.
* <p/>
* The returned matrix is read-only and will be updated automatically as {@link #setOrientation(Vector3,
* Vector3, Vector3)} is invoked.
*
* @return The view matrix
*/
public
@Const
Matrix4 getViewMatrix() {
return view;
}
/**
* <p/>
* Copy the given vectors into this Frustum for its location, direction and up vectors. The orientation is
* then normalized and orthogonalized, but the provided vectors are unmodified.
* <p/>
* Any later changes to the vectors' x, y, and z values will not be reflected in the frustum planes or
* view transform, unless this method is called again.
*
* @param location The new location vector
* @param direction The new direction vector
* @param up The new up vector
*
* @throws NullPointerException if location, direction or up is null
*/
public void setOrientation(@Const Vector3 location, @Const Vector3 direction, @Const Vector3 up) {
if (location == null || direction == null || up == null) {
throw new NullPointerException("Orientation vectors cannot be null: " + location + " " +
direction +
" " + up);
}
this.location.set(location);
this.direction.set(direction);
this.up.set(up);
update();
}
/**
* Set the orientation of this Frustum based on the affine <var>transform</var>. The 4th column's first 3
* values encode the transformation. The 3rd column holds the direction vector, and the 2nd column defines
* the up vector.
*
* @param transform The new transform of the frustum
*
* @throws NullPointerException if transform is null
*/
public void setOrientation(@Const Matrix4 transform) {
if (transform == null) {
throw new NullPointerException("Transform cannot be null");
}
this.location.set(transform.m03, transform.m13, transform.m23);
this.direction.set(transform.m02, transform.m12, transform.m22);
this.up.set(transform.m01, transform.m11, transform.m21);
update();
}
/**
* Set the orientation of this Frustum based on the given location vector and 3x3 rotation matrix.
* Together the vector and rotation represent an affine transform that is treated the same as in {@link
* #setOrientation(Matrix4)}.
*
* @param location The location of the frustum
* @param rotation The rotation of the frustum
*
* @throws NullPointerException if location or rotation are null
*/
public void setOrientation(@Const Vector3 location, @Const Matrix3 rotation) {
if (location == null) {
throw new NullPointerException("Location cannot be null");
}
if (rotation == null) {
throw new NullPointerException("Rotation matrix cannot be null");
}
this.location.set(location);
this.direction.set(rotation.m02, rotation.m12, rotation.m22);
this.up.set(rotation.m01, rotation.m11, rotation.m21);
update();
}
/**
* <p/>
* Return a plane representing the given plane of the view frustum, in world coordinates. This plane
* should not be modified. The returned plane's normal is configured so that it points into the center of
* the Frustum. The returned {@link Vector4} is encoded as a plane as defined in {@link Plane}; it is also
* normalized.
* <p/>
* <p/>
* The returned plane vector is read-only. It will be updated automatically when the projection or view
* parameters change.
*
* @param i The requested plane index
*
* @return The ReadOnlyVector4f instance for the requested plane, in world coordinates
*
* @throws IndexOutOfBoundsException if plane isn't in [0, 5]
*/
public
@Const
Vector4 getFrustumPlane(int i) {
return worldPlanes[i];
}
/**
* <p/>
* Compute and return the intersection of the AxisAlignedBox and this Frustum, <var>f</var>. It is assumed
* that the Frustum and AxisAlignedBox exist in the same coordinate frame. {@link
* FrustumIntersection#INSIDE} is returned when the AxisAlignedBox is fully contained by the Frustum.
* {@link FrustumIntersection#INTERSECT} is returned when this box is partially contained by the Frustum,
* and {@link FrustumIntersection#OUTSIDE} is returned when the box has no intersection with the Frustum.
* <p/>
* If <var>OUTSIDE</var> is returned, it is guaranteed that the objects enclosed by the bounds do not
* intersect the Frustum. If <var>INSIDE</var> is returned, any object {@link
* AxisAlignedBox#contains(AxisAlignedBox) contained} by the box will also be completely inside the
* Frustum. When <var>INTERSECT</var> is returned, there is a chance that the true representation of the
* objects enclosed by the box will be outside of the Frustum, but it is unlikely. This can occur when a
* corner of the box intersects with the planes of <var>f</var>, but the shape does not exist in that
* corner.
* <p/>
* The argument <var>planeState</var> can be used to hint to this function which planes of the Frustum
* require checking and which do not. When a hierarchy of bounds is used, the planeState can be used to
* remove unnecessary plane comparisons. If <var>planeState</var> is null it is assumed that all planes
* need to be checked. If <var>planeState</var> is not null, this method will mark any plane that the box
* is completely inside of as not requiring a comparison. It is the responsibility of the caller to save
* and restore the plane state as needed based on the structure of the bound hierarchy.
*
* @param bounds The bounds to test for intersection with this frustm
* @param planeState An optional PlaneState hint specifying which planes to check
*
* @return A FrustumIntersection indicating how the frustum and bounds intersect
*
* @throws NullPointerException if bounds is null
*/
public FrustumIntersection intersects(@Const AxisAlignedBox bounds, PlaneState planeState) {
if (bounds == null) {
throw new NullPointerException("Bounds cannot be null");
}
// early escape for potentially deeply nested nodes in a tree
if (planeState != null && !planeState.getTestsRequired()) {
return FrustumIntersection.INSIDE;
}
FrustumIntersection result = FrustumIntersection.INSIDE;
double distMax;
double distMin;
int plane = 0;
Vector4 p;
for (int i = Frustum.NUM_PLANES - 1; i >= 0; i--) {
if (planeState == null || planeState.isTestRequired(i)) {
p = getFrustumPlane(plane);
// set temp to the normal of the plane then compute the extent
// in-place; this is safe but we'll have to reset temp to the
// normal later if needed
temp.set(p.x, p.y, p.z).farExtent(bounds, temp);
distMax = Plane.getSignedDistance(p, temp, true);
if (distMax < 0) {
// the point closest to the plane is behind the plane, so
// we know the bounds must be outside of the frustum
return FrustumIntersection.OUTSIDE;
} else {
// the point closest to the plane is in front of the plane,
// but we need to check the farthest away point
// make sure to reset temp to the normal before computing
// the near extent in-place
temp.set(p.x, p.y, p.z).nearExtent(bounds, temp);
distMin = Plane.getSignedDistance(p, temp, true);
if (distMin < 0) {
// the farthest point is behind the plane, so at best
// this box will be intersecting the frustum
result = FrustumIntersection.INTERSECT;
} else {
// the box is completely contained by the plane, so
// the return result can be INSIDE or INTERSECT (if set by another plane)
if (planeState != null) {
planeState.setTestRequired(plane, false);
}
}
}
}
}
return result;
}
/*
* Update the plane instances returned by getFrustumPlane() to reflect any
* changes to the frustum's local parameters or orientation. Also update the
* view transform and projection matrix.
*/
private void update() {
// compute the right-handed basis vectors of the frustum
Vector3 n = new Vector3().scale(direction.normalize(), -1); // normalizes direction as well
Vector3 u = new Vector3().cross(up, n).normalize();
Vector3 v = up.cross(n, u).normalize(); // recompute up to properly orthogonal to direction
// view matrix
view.set(u.x, u.y, u.z, -location.dot(u), v.x, v.y, v.z, -location.dot(v), n.x, n.y, n.z,
-location.dot(n), 0f, 0f, 0f, 1f);
// projection matrix
if (useOrtho) {
projection.set(2 / (frustumRight - frustumLeft), 0, 0,
-(frustumRight + frustumLeft) / (frustumRight - frustumLeft), 0,
2 / (frustumTop - frustumBottom), 0,
-(frustumTop + frustumBottom) / (frustumTop - frustumBottom), 0, 0,
2 / (frustumNear - frustumFar),
-(frustumFar + frustumNear) / (frustumFar - frustumNear), 0, 0, 0, 1);
} else {
projection.set(2 * frustumNear / (frustumRight - frustumLeft), 0,
(frustumRight + frustumLeft) / (frustumRight - frustumLeft), 0, 0,
2 * frustumNear / (frustumTop - frustumBottom),
(frustumTop + frustumBottom) / (frustumTop - frustumBottom), 0, 0, 0,
-(frustumFar + frustumNear) / (frustumFar - frustumNear),
-2 * frustumFar * frustumNear / (frustumFar - frustumNear), 0, 0, -1, 0);
}
// generate world-space frustum planes, we pass in n and u since we
// created them to compute the view matrix and they're just garbage
// at this point, might as well let plane generation reuse them.
if (useOrtho) {
computeOrthoWorldPlanes(n, u);
} else {
computePerspectiveWorldPlanes(n, u);
}
}
private void computeOrthoWorldPlanes(Vector3 n, Vector3 p) {
// FAR
p.scale(direction, frustumFar).add(location);
n.scale(direction, -1);
setWorldPlane(FAR_PLANE, n, p);
// NEAR
p.scale(direction, frustumNear).add(location);
n.set(direction);
setWorldPlane(NEAR_PLANE, n, p);
// compute right vector for LEFT and RIGHT usage
n.cross(direction, up);
// LEFT
p.scale(n, frustumLeft).add(location);
setWorldPlane(LEFT_PLANE, n, p);
// RIGHT
p.scale(n, frustumRight).add(location);
n.scale(-1);
setWorldPlane(RIGHT_PLANE, n, p);
// BOTTOM
p.scale(up, frustumBottom).add(location);
setWorldPlane(BOTTOM_PLANE, up, p);
// TOP
n.scale(up, -1);
p.scale(up, frustumTop).add(location);
setWorldPlane(TOP_PLANE, n, p);
}
private void computePerspectiveWorldPlanes(Vector3 n, Vector3 p) {
// FAR
p.scale(direction, frustumFar).add(location);
p.scale(direction, -1);
setWorldPlane(FAR_PLANE, n, p);
// NEAR
p.scale(direction, frustumNear).add(location);
n.set(direction);
setWorldPlane(NEAR_PLANE, n, p);
// compute left vector for LEFT and RIGHT usage
p.cross(up, direction);
// LEFT
double invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumLeft * frustumLeft);
n.scale(direction, Math.abs(frustumLeft) / frustumNear).sub(p).scale(frustumNear * invHyp);
setWorldPlane(LEFT_PLANE, n, location);
// RIGHT
invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumRight * frustumRight);
n.scale(direction, Math.abs(frustumRight) / frustumNear).add(p).scale(frustumNear * invHyp);
setWorldPlane(RIGHT_PLANE, n, location);
// BOTTOM
invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumBottom * frustumBottom);
n.scale(direction, Math.abs(frustumBottom) / frustumNear).add(up).scale(frustumNear * invHyp);
setWorldPlane(BOTTOM_PLANE, n, location);
// TOP
invHyp = 1 / Math.sqrt(frustumNear * frustumNear + frustumTop * frustumTop);
n.scale(direction, Math.abs(frustumTop) / frustumNear).sub(up).scale(frustumNear * invHyp);
setWorldPlane(TOP_PLANE, n, location);
}
// set the given world plane so it's a plane with the given normal
// that passes through pos, and then normalize it
private void setWorldPlane(int plane, @Const Vector3 normal, @Const Vector3 pos) {
setWorldPlane(plane, normal.x, normal.y, normal.z, -normal.dot(pos));
}
// set the given world plane, with the 4 values, and then normalize it
private void setWorldPlane(int plane, double a, double b, double c, double d) {
Vector4 cp = worldPlanes[plane];
if (cp == null) {
cp = new Vector4(a, b, c, d);
worldPlanes[plane] = cp;
} else {
cp.set(a, b, c, d);
}
Plane.normalize(cp);
}
}
|
Java
|
module Convert.LRChirotope where
-- standard modules
import Data.List
import qualified Data.Map as Map
import Data.Maybe
import qualified Data.Set as Set
-- local modules
import Basics
import Calculus.FlipFlop
import Helpful.General
--import Debug.Trace
{------------------------------------------------------------------------------
- FlipFlop to Chirotope
------------------------------------------------------------------------------}
flipflopsToChirotope :: Network [String] (ARel FlipFlop)
-> Maybe (Network [Int] Int)
flipflopsToChirotope net
| isNothing net5 || isNothing net3 = Nothing
| otherwise = Just $ (fromJust net3)
{ nCons = fst $ Map.foldlWithKey
collectOneCon
(Map.empty, Map.empty)
cons
}
where
collectOneCon (consAcc, mapAcc) nodes rel =
let
(newMap, convertedNodes) = mapAccumL
(\ m node -> let mappedNode = Map.lookup node m in
case mappedNode of
Nothing -> let n = (Map.size m) + 1 in
(Map.insert node n m, n)
otherwise -> (m, fromJust mappedNode)
)
mapAcc
nodes
newRel = case aRel rel of
R -> (-1)
I -> 0
L -> 1
in
( foldl (flip $ uncurry Map.insert) consAcc $
[(x, newRel * y)
| (x,y) <- kPermutationsWithParity 3 convertedNodes
]
, newMap
)
net5 = ffsToFF5s net
net3 = ff5sToFF3s $ fromJust net5
cons = nCons $ fromJust net3
|
Java
|
### Some tips for using linspecer ###
---------------------------------
I personally like the first color to be black, so I begin with:
colors = [0,0,0; linspecer(10)];
which creates an 11x3 matrix of RGB colors.
Note: you must add the linspecer to your path via:
addpath('~\path-to-linspecer-directory/linspecer')
you can add this to the startup.m file, found in your default startup directory for Matlab (on my Mac it's at `/Users/USERNAME/Documents/MATLAB/`)
If you'd like Matlab to use this color order by default, add this code to your startup.m file:
addpath('~/path-to-linspecer/linspecer')
colors = [0,0,0; linspecer(8)];
set(0,'DefaultAxesColorOrder',colors);
where `'~/path-to-linspecer/linspecer'` is the path to you `linspecer` folder.
|
Java
|
var files =
[
[ "Code", "dir_a44bec13de8698b1b3f25058862347f8.html", "dir_a44bec13de8698b1b3f25058862347f8" ]
];
|
Java
|
{-# LANGUAGE FlexibleContexts #-}
module BRC.Solver.Error where
import Control.Monad.Error (Error(..), MonadError(..))
-- | Solver errors, really just a container for a possibly useful error message.
data SolverError = SolverError String deriving (Eq, Ord)
instance Show (SolverError) where
show (SolverError msg) = "Solver error: " ++ msg
instance Error SolverError where
strMsg = SolverError
-- | Throws an error with a given message in a solver error monad.
solverError :: MonadError SolverError m => String -> m a
solverError = throwError . strMsg
|
Java
|
package cocoonClient.Panels;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
import JSONTransmitProtocol.newReader.JSONReader;
import cocoonClient.Connector.AbstractConnector;
import cocoonClient.Data.UserInfo;
public class StatusPanel extends CocoonDisplayPanel implements AbstractConnector{
private JTable table;
public StatusPanel(){
super(UserInfo.getMainFrame());
setRightPanel(new TestRightPanel());
this.setSize(600, 500);
this.setLayout(new FlowLayout());
init();
UserInfo.getPanels().put("Status", this);
}
private void init() {
try{
//Table//以Model物件宣告建立表格的JTable元件
table = new JTable(){
public void valueChanged(ListSelectionEvent e){
super.valueChanged(e); //呼叫基礎類別的valueChanged()方法, 否則選取動作無法正常執行
if( table.getSelectedRow() == -1) return;//取得表格目前的選取列,若沒有選取列則終止執行方法
}
};
table.setModel(new DefaultTableModel(){
@Override
public boolean isCellEditable(int row, int column){
return false;
}
});
table.setShowGrid(true);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
table.setSelectionBackground(Color.ORANGE);//設定選取背景顏色
table.setCellSelectionEnabled(true); //設定允許儲存格選取
//取得處理表格資料的Model物件,建立關聯
DefaultTableModel dtm = (DefaultTableModel)table.getModel(); //宣告處理表格資料的TableModel物件
String columnTitle[] = new String[]{"Date", "Username", "Problem", "Status"};
int columnWidth[] = new int[]{150, 120, 190, 120};
for(int i = 0; i < columnTitle.length; i++){
dtm.addColumn(columnTitle[i]);
}
for(int i = 0; i < columnWidth.length; i++){
//欄寬設定
table.getColumnModel().getColumn(i).setPreferredWidth(columnWidth[i]);
}
//註冊回應JTable元件的MouseEvent事件的監聽器物件
/* table.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
int selRow = table.rowAtPoint(e.getPoint());//取得滑鼠點選位置所在之資料的列索引
String Size = (String) table.getValueAt(selRow, 2); //取得被點選資料列的第3欄的值
if (Integer.parseInt(Size)> 0 ){
}
}
});*/
}catch ( Exception e){
e.printStackTrace();
}
JScrollPane pane = new JScrollPane(table);
pane.setPreferredSize(new Dimension(600, 450));
add(pane);
}
private void addStatus(String response){
JSONReader reader = new JSONReader(response);
DefaultTableModel dtm = (DefaultTableModel)table.getModel();
String result = "";
try{
result = reader.getSubmission().getResult().split("\n")[0];
}
catch(Exception e){}
dtm.addRow(new String[] {
reader.getSubmission().getTime(),
reader.getSubmission().getUsername(),
UserInfo.getProblemSet().getProblemName(reader.getSubmission().getPID()),
result
});
}
@Override
public void recieveResponse(String response) {
addStatus(response);
}
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_51) on Fri Mar 06 12:54:17 CET 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="UTF-8">
<title>Trash.Mode</title>
<meta name="date" content="2015-03-06">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Trash.Mode";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/jetel/component/Trash.html" title="class in org.jetel.component"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/jetel/component/TreeReader.html" title="class in org.jetel.component"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/jetel/component/Trash.Mode.html" target="_top">Frames</a></li>
<li><a href="Trash.Mode.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.jetel.component</div>
<h2 title="Enum Trash.Mode" class="title">Enum Trash.Mode</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>java.lang.Enum<<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>></li>
<li>
<ul class="inheritance">
<li>org.jetel.component.Trash.Mode</li>
</ul>
</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Implemented Interfaces:</dt>
<dd>java.io.Serializable, java.lang.Comparable<<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>></dd>
</dl>
<dl>
<dt>Enclosing class:</dt>
<dd><a href="../../../org/jetel/component/Trash.html" title="class in org.jetel.component">Trash</a></dd>
</dl>
<hr>
<br>
<pre>public static enum <span class="strong">Trash.Mode</span>
extends java.lang.Enum<<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>></pre>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- =========== ENUM CONSTANT SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_summary">
<!-- -->
</a>
<h3>Enum Constant Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Enum Constant Summary table, listing enum constants, and an explanation">
<caption><span>Enum Constants</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Enum Constant and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><strong><a href="../../../org/jetel/component/Trash.Mode.html#PERFORMANCE">PERFORMANCE</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colOne"><code><strong><a href="../../../org/jetel/component/Trash.Mode.html#VALIDATE_RECORDS">VALIDATE_RECORDS</a></strong></code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr class="altColor">
<td class="colFirst"><code>static <a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a></code></td>
<td class="colLast"><code><strong><a href="../../../org/jetel/component/Trash.Mode.html#valueOf(java.lang.String)">valueOf</a></strong>(java.lang.String name)</code>
<div class="block">Returns the enum constant of this type with the specified name.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>static <a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>[]</code></td>
<td class="colLast"><code><strong><a href="../../../org/jetel/component/Trash.Mode.html#values()">values</a></strong>()</code>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared.</div>
</td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Enum">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Enum</h3>
<code>clone, compareTo, equals, finalize, getDeclaringClass, hashCode, name, ordinal, toString, valueOf</code></li>
</ul>
<ul class="blockList">
<li class="blockList"><a name="methods_inherited_from_class_java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>getClass, notify, notifyAll, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ ENUM CONSTANT DETAIL =========== -->
<ul class="blockList">
<li class="blockList"><a name="enum_constant_detail">
<!-- -->
</a>
<h3>Enum Constant Detail</h3>
<a name="VALIDATE_RECORDS">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>VALIDATE_RECORDS</h4>
<pre>public static final <a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a> VALIDATE_RECORDS</pre>
</li>
</ul>
<a name="PERFORMANCE">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>PERFORMANCE</h4>
<pre>public static final <a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a> PERFORMANCE</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="values()">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>values</h4>
<pre>public static <a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>[] values()</pre>
<div class="block">Returns an array containing the constants of this enum type, in
the order they are declared. This method may be used to iterate
over the constants as follows:
<pre>
for (Trash.Mode c : Trash.Mode.values())
System.out.println(c);
</pre></div>
<dl><dt><span class="strong">Returns:</span></dt><dd>an array containing the constants of this enum type, in
the order they are declared</dd></dl>
</li>
</ul>
<a name="valueOf(java.lang.String)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>valueOf</h4>
<pre>public static <a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a> valueOf(java.lang.String name)</pre>
<div class="block">Returns the enum constant of this type with the specified name.
The string must match <i>exactly</i> an identifier used to declare an
enum constant in this type. (Extraneous whitespace characters are
not permitted.)</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>name</code> - the name of the enum constant to be returned.</dd>
<dt><span class="strong">Returns:</span></dt><dd>the enum constant with the specified name</dd>
<dt><span class="strong">Throws:</span></dt>
<dd><code>java.lang.IllegalArgumentException</code> - if this enum type has no constant
with the specified name</dd>
<dd><code>java.lang.NullPointerException</code> - if the argument is null</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../org/jetel/component/Trash.html" title="class in org.jetel.component"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../org/jetel/component/TreeReader.html" title="class in org.jetel.component"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/jetel/component/Trash.Mode.html" target="_top">Frames</a></li>
<li><a href="Trash.Mode.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li><a href="#enum_constant_summary">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li><a href="#enum_constant_detail">Enum Constants</a> | </li>
<li>Field | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<address>Copyright © 2002-2015 Javlin a.s.</address>
</small></p>
</body>
</html>
|
Java
|
/**
* Created on: Dec 7, 2013
*/
package com.iteamsolutions.angular.models.atom
import scalaz.{
Failure => _,
Success => _,
_
}
/**
* The '''Link''' type is the Domain Object Model representation of an
* [[http://www.ietf.org/rfc/rfc4287.txt Atom Link]].
*
* @author svickers
*
*/
final case class Link (
val href : URI,
val rel : String \/ URI,
val title : Option[String]
)
{
}
object Link
{
}
|
Java
|
package de.lman;
import de.lman.engine.Colors;
import de.lman.engine.Game;
import de.lman.engine.InputState;
import de.lman.engine.Keys;
import de.lman.engine.Mouse;
import de.lman.engine.math.Mat2f;
import de.lman.engine.math.Scalar;
import de.lman.engine.math.Transform;
import de.lman.engine.math.Vec2f;
import de.lman.engine.physics.Body;
import de.lman.engine.physics.ContactStatePair;
import de.lman.engine.physics.GeometryUtils;
import de.lman.engine.physics.Physics;
import de.lman.engine.physics.contacts.Contact;
import de.lman.engine.physics.contacts.ContactListener;
import de.lman.engine.physics.shapes.BoxShape;
import de.lman.engine.physics.shapes.EdgeShape;
import de.lman.engine.physics.shapes.PhysicsMaterial;
import de.lman.engine.physics.shapes.PlaneShape;
import de.lman.engine.physics.shapes.PolygonShape;
import de.lman.engine.physics.shapes.Shape;
/*
Probleme lösen:
- Linien-Zeichnen korrigieren
Aufgaben:
- Tastatureingaben robuster machen (ist gedrückt, war gedrückt)
- Bitmap laden, konvertieren und zeichnen
- Bitmap transformiert zeichnen (Rotation)
- Bitmap fonts generieren
- Bitmap fonts zeichnen
- Bitmap Bilinär filtern
- Debug Informationen
- Fps / Framedauer anzeigen
- Zeitmessungen
- Speichern für mehrere Frames
- Visualisierung (Bar, Line)
- UI
- Panel
- Button
- Label
- Checkbox
- Radiobutton
- Sensor-Flag für Shape
- ECS
- Integrierter-Level-Editor
- Skalierung
- Propertionales vergrößern von Seiten
- Verschiebung von Eckpunkten
- Löschen
- Kopieren / Einfügen
- Gitter-Snap
- Mehrere Shapetypen + Auswahlmöglichkeit:
- Kreis
- Linien-Segment
- Polygone
- Boxen
- Ebenen
- Laden / Speichern
- Körper & Formen serialisieren und deserialisieren (JSON)
- Rotationsdynamik:
- Kreuzprodukt
- updateAABB in Body robuster machen
- getSupportPoints vereinfachen / robuster machen
- Massenzentrum (COM)
- Traegheitsmoment (Inertia, AngularVelocity)
- Kontaktausschnitt
- Asset-Management
- Preloading
- Erstellung von Kontakt-Szenarien vereinfachen -> offset()
*/
public class Leverman extends Game implements ContactListener {
public Leverman() {
super("Leverman");
}
public static void main(String[] args) {
Leverman game = new Leverman();
game.run();
}
private Physics physics;
private boolean showContacts = true;
private boolean showAABBs = false;
private boolean physicsSingleStep = false;
public final static PhysicsMaterial MAT_STATIC = new PhysicsMaterial(0f, 0.1f);
public final static PhysicsMaterial MAT_DYNAMIC = new PhysicsMaterial(1f, 0.1f);
private Body playerBody;
private boolean playerOnGround = false;
private boolean playerJumping = false;
private int playerGroundHash = 0;
private final Vec2f groundNormal = new Vec2f(0, 1);
@Override
public void physicsBeginContact(int hash, ContactStatePair pair) {
Contact contact = pair.pair.contacts[pair.contactIndex];
Vec2f normal = contact.normal;
Body player = null;
if (pair.pair.a.id == playerBody.id) {
player = pair.pair.a;
normal = new Vec2f(contact.normal).invert();
} else if (pair.pair.b.id == playerBody.id) {
player = pair.pair.b;
}
float d = normal.dot(groundNormal);
if (d > 0) {
if (player != null && (!playerOnGround)) {
playerOnGround = true;
playerGroundHash = hash;
}
}
}
@Override
public void physicsEndContact(int hash, ContactStatePair pair) {
Contact contact = pair.pair.contacts[pair.contactIndex];
Vec2f normal = contact.normal;
Body player = null;
if (pair.pair.a.id == playerBody.id) {
player = pair.pair.a;
normal = new Vec2f(contact.normal).invert();
} else if (pair.pair.b.id == playerBody.id) {
player = pair.pair.b;
}
float d = normal.dot(groundNormal);
if (d > 0) {
if (player != null && playerOnGround && (playerGroundHash == hash)) {
playerOnGround = false;
playerGroundHash = 0;
}
}
}
private void addPlatform(float x, float y, float rx, float ry) {
Body body;
physics.addBody(body = new Body().addShape(new BoxShape(new Vec2f(rx, ry)).setMaterial(MAT_STATIC)));
body.pos.set(x, y);
}
private void addBox(float x, float y, float rx, float ry) {
Body body;
physics.addBody(body = new Body().addShape(new BoxShape(new Vec2f(rx, ry)).setMaterial(MAT_DYNAMIC)));
body.pos.set(x, y);
}
protected void initGame() {
physics = new Physics(this);
physics.enableSingleStepMode(physicsSingleStep);
Body body;
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.y).rotation(Scalar.PI * 0f).setMaterial(MAT_STATIC)));
body.pos.set(-halfWidth + 0.5f, 0);
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.y).rotation(Scalar.PI * 1f).setMaterial(MAT_STATIC)));
body.pos.set(halfWidth - 0.5f, 0);
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.x).rotation(Scalar.PI * 0.5f).setMaterial(MAT_STATIC)));
body.pos.set(0, -halfHeight + 0.5f);
physics.addBody(body = new Body().addShape(new PlaneShape(viewport.x).rotation(Scalar.PI * 1.5f).setMaterial(MAT_STATIC)));
body.pos.set(0, halfHeight - 0.5f);
addPlatform(0 - 2.9f, 0 - 2.0f, 0.6f, 0.1f);
addPlatform(0, 0 - 1.3f, 0.7f, 0.1f);
addPlatform(0 + 2.9f, 0 - 0.8f, 0.6f, 0.1f);
//addBox(0, -0.5f, 0.2f, 0.2f);
addPlatform(0 + 2.0f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
addPlatform(0 + 2.4f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
addPlatform(0 + 2.8f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
addPlatform(0 + 3.2f, -halfHeight + 0.2f + 0.5f, 0.2f, 0.2f);
playerBody = new Body();
BoxShape playerBox = (BoxShape) new BoxShape(new Vec2f(0.2f, 0.4f)).setMaterial(MAT_DYNAMIC);
playerBody.addShape(playerBox);
playerBody.pos.set(0, -halfHeight + playerBox.radius.y + 0.5f);
physics.addBody(playerBody);
Vec2f[] polyVerts = new Vec2f[]{
new Vec2f(0, 0.5f),
new Vec2f(-0.5f, -0.5f),
new Vec2f(0.5f, -0.5f),
};
physics.addBody(body = new Body().addShape(new PolygonShape(polyVerts).setMaterial(MAT_STATIC)));
body.pos.set(0, 0);
}
private boolean dragging = false;
private Vec2f dragStart = new Vec2f();
private Body dragBody = null;
private void updateGameInput(float dt, InputState inputState) {
boolean leftMousePressed = inputState.isMouseDown(Mouse.LEFT);
if (!dragging) {
if (leftMousePressed) {
dragBody = null;
for (int i = 0; i < physics.numBodies; i++) {
Body body = physics.bodies[i];
if (body.invMass > 0) {
if (GeometryUtils.isPointInAABB(inputState.mousePos.x, inputState.mousePos.y, body.aabb)) {
dragging = true;
dragStart.set(inputState.mousePos);
dragBody = body;
break;
}
}
}
}
} else {
if (leftMousePressed) {
float dx = inputState.mousePos.x - dragStart.x;
float dy = inputState.mousePos.y - dragStart.y;
dragBody.vel.x += dx * 0.1f;
dragBody.vel.y += dy * 0.1f;
dragStart.set(inputState.mousePos);
} else {
dragging = false;
}
}
// Kontakte ein/ausschalten
if (inputState.isKeyDown(Keys.F2)) {
showContacts = !showContacts;
inputState.setKeyDown(Keys.F2, false);
}
// AABBs ein/ausschalten
if (inputState.isKeyDown(Keys.F3)) {
showAABBs = !showAABBs;
inputState.setKeyDown(Keys.F3, false);
}
// Einzelschritt-Physik-Modus ein/ausschalten
if (inputState.isKeyDown(Keys.F5)) {
physicsSingleStep = !physicsSingleStep;
physics.enableSingleStepMode(physicsSingleStep);
inputState.setKeyDown(Keys.F5, false);
}
if (inputState.isKeyDown(Keys.F6)) {
if (physicsSingleStep) {
physics.nextStep();
}
inputState.setKeyDown(Keys.F6, false);
}
// Player bewegen
if (inputState.isKeyDown(Keys.W)) {
if (!playerJumping && playerOnGround) {
playerBody.acc.y += 4f / dt;
playerJumping = true;
}
} else {
if (playerJumping && playerOnGround) {
playerJumping = false;
}
}
if (inputState.isKeyDown(Keys.A)) {
playerBody.acc.x -= 0.1f / dt;
} else if (inputState.isKeyDown(Keys.D)) {
playerBody.acc.x += 0.1f / dt;
}
}
private final Editor editor = new Editor();
private boolean editorWasShownAABB = false;
protected void updateInput(float dt, InputState input) {
// Editormodus ein/ausschalten
if (input.isKeyDown(Keys.F4)) {
editor.active = !editor.active;
if (editor.active) {
editorWasShownAABB = showAABBs;
showAABBs = true;
editor.init(physics);
} else {
showAABBs = editorWasShownAABB;
}
input.setKeyDown(Keys.F4, false);
}
if (editor.active) {
editor.updateInput(dt, physics, input);
} else {
updateGameInput(dt, input);
}
}
@Override
protected String getAdditionalTitle() {
return String.format(" [Frames: %d, Bodies: %d, Contacts: %d]", numFrames, physics.numBodies, physics.numContacts);
}
protected void updateGame(float dt) {
if (!editor.active) {
physics.step(dt);
}
}
private void renderEditor(float dt) {
// TODO: Move to editor class
clear(0x000000);
for (int i = 0; i < viewport.x / Editor.GRID_SIZE; i++) {
drawLine(-halfWidth + i * Editor.GRID_SIZE, -halfHeight, -halfWidth + i * Editor.GRID_SIZE, halfHeight, Colors.DarkSlateGray);
}
for (int i = 0; i < viewport.y / Editor.GRID_SIZE; i++) {
drawLine(-halfWidth, -halfHeight + i * Editor.GRID_SIZE, halfWidth, -halfHeight + i * Editor.GRID_SIZE, Colors.DarkSlateGray);
}
drawBodies(physics.numBodies, physics.bodies);
if (editor.selectedBody != null) {
Editor.DragSide[] dragSides = editor.getDragSides(editor.selectedBody);
Shape shape = editor.selectedBody.shapes[0];
if (dragSides.length > 0 && shape instanceof EdgeShape) {
EdgeShape edgeShape = (EdgeShape) shape;
Transform t = new Transform(shape.localPos, shape.localRotation).offset(editor.selectedBody.pos);
Vec2f[] localVertices = edgeShape.getLocalVertices();
for (int i = 0; i < dragSides.length; i++) {
Vec2f dragPoint = dragSides[i].center;
drawPoint(dragPoint, Editor.DRAGPOINT_RADIUS, Colors.White);
if (editor.resizeSideIndex == i) {
Vec2f v0 = new Vec2f(localVertices[dragSides[i].index0]).transform(t);
Vec2f v1 = new Vec2f(localVertices[dragSides[i].index1]).transform(t);
drawPoint(v0, Editor.DRAGPOINT_RADIUS, Colors.GoldenRod);
drawPoint(v1, Editor.DRAGPOINT_RADIUS, Colors.GoldenRod);
}
}
}
Mat2f mat = new Mat2f(shape.localRotation).transpose();
drawNormal(editor.selectedBody.pos, mat.col1, DEFAULT_ARROW_RADIUS, DEFAULT_ARROW_LENGTH, Colors.Red);
}
drawPoint(inputState.mousePos.x, inputState.mousePos.y, DEFAULT_POINT_RADIUS, 0x0000FF);
}
private void renderInternalGame(float dt) {
clear(0x000000);
drawBodies(physics.numBodies, physics.bodies);
if (showAABBs) {
drawAABBs(physics.numBodies, physics.bodies);
}
if (showContacts) {
drawContacts(dt, physics.numPairs, physics.pairs, false, true);
}
}
protected void renderGame(float dt) {
if (editor.active) {
renderEditor(dt);
} else {
renderInternalGame(dt);
}
}
}
|
Java
|
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
module NW.Monster where
import NW.Stats
data MonsterClass
= MCFighter
| MCMage
deriving (Eq, Show)
data Monster = Monster
{ mClass :: MonsterClass
, mName :: String
, mStatsBase :: [Stat]
, mLootBonus :: Int
} deriving (Eq, Show)
type MonsterDB = [Monster]
|
Java
|
package org.jvnet.jaxb2_commons.plugin.mergeable;
import java.util.Arrays;
import java.util.Collection;
import javax.xml.namespace.QName;
import org.jvnet.jaxb2_commons.lang.JAXBMergeStrategy;
import org.jvnet.jaxb2_commons.lang.MergeFrom2;
import org.jvnet.jaxb2_commons.lang.MergeStrategy2;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
import org.jvnet.jaxb2_commons.plugin.AbstractParameterizablePlugin;
import org.jvnet.jaxb2_commons.plugin.Customizations;
import org.jvnet.jaxb2_commons.plugin.CustomizedIgnoring;
import org.jvnet.jaxb2_commons.plugin.Ignoring;
import org.jvnet.jaxb2_commons.plugin.util.FieldOutlineUtils;
import org.jvnet.jaxb2_commons.plugin.util.StrategyClassUtils;
import org.jvnet.jaxb2_commons.util.ClassUtils;
import org.jvnet.jaxb2_commons.util.FieldAccessorFactory;
import org.jvnet.jaxb2_commons.util.PropertyFieldAccessorFactory;
import org.jvnet.jaxb2_commons.xjc.outline.FieldAccessorEx;
import org.xml.sax.ErrorHandler;
import com.sun.codemodel.JBlock;
import com.sun.codemodel.JCodeModel;
import com.sun.codemodel.JConditional;
import com.sun.codemodel.JDefinedClass;
import com.sun.codemodel.JExpr;
import com.sun.codemodel.JExpression;
import com.sun.codemodel.JMethod;
import com.sun.codemodel.JMod;
import com.sun.codemodel.JOp;
import com.sun.codemodel.JType;
import com.sun.codemodel.JVar;
import com.sun.tools.xjc.Options;
import com.sun.tools.xjc.outline.ClassOutline;
import com.sun.tools.xjc.outline.FieldOutline;
import com.sun.tools.xjc.outline.Outline;
public class MergeablePlugin extends AbstractParameterizablePlugin {
@Override
public String getOptionName() {
return "Xmergeable";
}
@Override
public String getUsage() {
return "TBD";
}
private FieldAccessorFactory fieldAccessorFactory = PropertyFieldAccessorFactory.INSTANCE;
public FieldAccessorFactory getFieldAccessorFactory() {
return fieldAccessorFactory;
}
public void setFieldAccessorFactory(
FieldAccessorFactory fieldAccessorFactory) {
this.fieldAccessorFactory = fieldAccessorFactory;
}
private String mergeStrategyClass = JAXBMergeStrategy.class.getName();
public void setMergeStrategyClass(final String mergeStrategyClass) {
this.mergeStrategyClass = mergeStrategyClass;
}
public String getMergeStrategyClass() {
return mergeStrategyClass;
}
public JExpression createMergeStrategy(JCodeModel codeModel) {
return StrategyClassUtils.createStrategyInstanceExpression(codeModel,
MergeStrategy2.class, getMergeStrategyClass());
}
private Ignoring ignoring = new CustomizedIgnoring(
org.jvnet.jaxb2_commons.plugin.mergeable.Customizations.IGNORED_ELEMENT_NAME,
Customizations.IGNORED_ELEMENT_NAME,
Customizations.GENERATED_ELEMENT_NAME);
public Ignoring getIgnoring() {
return ignoring;
}
public void setIgnoring(Ignoring ignoring) {
this.ignoring = ignoring;
}
@Override
public Collection<QName> getCustomizationElementNames() {
return Arrays
.asList(org.jvnet.jaxb2_commons.plugin.mergeable.Customizations.IGNORED_ELEMENT_NAME,
Customizations.IGNORED_ELEMENT_NAME,
Customizations.GENERATED_ELEMENT_NAME);
}
@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) {
for (final ClassOutline classOutline : outline.getClasses())
if (!getIgnoring().isIgnored(classOutline)) {
processClassOutline(classOutline);
}
return true;
}
protected void processClassOutline(ClassOutline classOutline) {
final JDefinedClass theClass = classOutline.implClass;
ClassUtils
._implements(theClass, theClass.owner().ref(MergeFrom2.class));
@SuppressWarnings("unused")
final JMethod mergeFrom$mergeFrom0 = generateMergeFrom$mergeFrom0(
classOutline, theClass);
@SuppressWarnings("unused")
final JMethod mergeFrom$mergeFrom = generateMergeFrom$mergeFrom(
classOutline, theClass);
if (!classOutline.target.isAbstract()) {
@SuppressWarnings("unused")
final JMethod createCopy = generateMergeFrom$createNewInstance(
classOutline, theClass);
}
}
protected JMethod generateMergeFrom$mergeFrom0(
final ClassOutline classOutline, final JDefinedClass theClass) {
JCodeModel codeModel = theClass.owner();
final JMethod mergeFrom$mergeFrom = theClass.method(JMod.PUBLIC,
codeModel.VOID, "mergeFrom");
mergeFrom$mergeFrom.annotate(Override.class);
{
final JVar left = mergeFrom$mergeFrom.param(Object.class, "left");
final JVar right = mergeFrom$mergeFrom.param(Object.class, "right");
final JBlock body = mergeFrom$mergeFrom.body();
final JVar mergeStrategy = body.decl(JMod.FINAL,
codeModel.ref(MergeStrategy2.class), "strategy",
createMergeStrategy(codeModel));
body.invoke("mergeFrom").arg(JExpr._null()).arg(JExpr._null())
.arg(left).arg(right).arg(mergeStrategy);
}
return mergeFrom$mergeFrom;
}
protected JMethod generateMergeFrom$mergeFrom(ClassOutline classOutline,
final JDefinedClass theClass) {
final JCodeModel codeModel = theClass.owner();
final JMethod mergeFrom = theClass.method(JMod.PUBLIC, codeModel.VOID,
"mergeFrom");
mergeFrom.annotate(Override.class);
{
final JVar leftLocator = mergeFrom.param(ObjectLocator.class,
"leftLocator");
final JVar rightLocator = mergeFrom.param(ObjectLocator.class,
"rightLocator");
final JVar left = mergeFrom.param(Object.class, "left");
final JVar right = mergeFrom.param(Object.class, "right");
final JVar mergeStrategy = mergeFrom.param(MergeStrategy2.class,
"strategy");
final JBlock methodBody = mergeFrom.body();
Boolean superClassImplementsMergeFrom = StrategyClassUtils
.superClassImplements(classOutline, getIgnoring(),
MergeFrom2.class);
if (superClassImplementsMergeFrom == null) {
} else if (superClassImplementsMergeFrom.booleanValue()) {
methodBody.invoke(JExpr._super(), "mergeFrom").arg(leftLocator)
.arg(rightLocator).arg(left).arg(right)
.arg(mergeStrategy);
} else {
}
final FieldOutline[] declaredFields = FieldOutlineUtils.filter(
classOutline.getDeclaredFields(), getIgnoring());
if (declaredFields.length > 0) {
final JBlock body = methodBody._if(right._instanceof(theClass))
._then();
JVar target = body.decl(JMod.FINAL, theClass, "target",
JExpr._this());
JVar leftObject = body.decl(JMod.FINAL, theClass, "leftObject",
JExpr.cast(theClass, left));
JVar rightObject = body.decl(JMod.FINAL, theClass,
"rightObject", JExpr.cast(theClass, right));
for (final FieldOutline fieldOutline : declaredFields) {
final FieldAccessorEx leftFieldAccessor = getFieldAccessorFactory()
.createFieldAccessor(fieldOutline, leftObject);
final FieldAccessorEx rightFieldAccessor = getFieldAccessorFactory()
.createFieldAccessor(fieldOutline, rightObject);
if (leftFieldAccessor.isConstant()
|| rightFieldAccessor.isConstant()) {
continue;
}
final JBlock block = body.block();
final JExpression leftFieldHasSetValue = (leftFieldAccessor
.isAlwaysSet() || leftFieldAccessor.hasSetValue() == null) ? JExpr.TRUE
: leftFieldAccessor.hasSetValue();
final JExpression rightFieldHasSetValue = (rightFieldAccessor
.isAlwaysSet() || rightFieldAccessor.hasSetValue() == null) ? JExpr.TRUE
: rightFieldAccessor.hasSetValue();
final JVar shouldBeSet = block.decl(
codeModel.ref(Boolean.class),
fieldOutline.getPropertyInfo().getName(false)
+ "ShouldBeMergedAndSet",
mergeStrategy.invoke("shouldBeMergedAndSet")
.arg(leftLocator).arg(rightLocator)
.arg(leftFieldHasSetValue)
.arg(rightFieldHasSetValue));
final JConditional ifShouldBeSetConditional = block._if(JOp
.eq(shouldBeSet, codeModel.ref(Boolean.class)
.staticRef("TRUE")));
final JBlock ifShouldBeSetBlock = ifShouldBeSetConditional
._then();
final JConditional ifShouldNotBeSetConditional = ifShouldBeSetConditional
._elseif(JOp.eq(
shouldBeSet,
codeModel.ref(Boolean.class).staticRef(
"FALSE")));
final JBlock ifShouldBeUnsetBlock = ifShouldNotBeSetConditional
._then();
// final JBlock ifShouldBeIgnoredBlock =
// ifShouldNotBeSetConditional
// ._else();
final JVar leftField = ifShouldBeSetBlock.decl(
leftFieldAccessor.getType(),
"lhs"
+ fieldOutline.getPropertyInfo().getName(
true));
leftFieldAccessor.toRawValue(ifShouldBeSetBlock, leftField);
final JVar rightField = ifShouldBeSetBlock.decl(
rightFieldAccessor.getType(),
"rhs"
+ fieldOutline.getPropertyInfo().getName(
true));
rightFieldAccessor.toRawValue(ifShouldBeSetBlock,
rightField);
final JExpression leftFieldLocator = codeModel
.ref(LocatorUtils.class).staticInvoke("property")
.arg(leftLocator)
.arg(fieldOutline.getPropertyInfo().getName(false))
.arg(leftField);
final JExpression rightFieldLocator = codeModel
.ref(LocatorUtils.class).staticInvoke("property")
.arg(rightLocator)
.arg(fieldOutline.getPropertyInfo().getName(false))
.arg(rightField);
final FieldAccessorEx targetFieldAccessor = getFieldAccessorFactory()
.createFieldAccessor(fieldOutline, target);
final JExpression mergedValue = JExpr.cast(
targetFieldAccessor.getType(),
mergeStrategy.invoke("merge").arg(leftFieldLocator)
.arg(rightFieldLocator).arg(leftField)
.arg(rightField).arg(leftFieldHasSetValue)
.arg(rightFieldHasSetValue));
final JVar merged = ifShouldBeSetBlock.decl(
rightFieldAccessor.getType(),
"merged"
+ fieldOutline.getPropertyInfo().getName(
true), mergedValue);
targetFieldAccessor.fromRawValue(
ifShouldBeSetBlock,
"unique"
+ fieldOutline.getPropertyInfo().getName(
true), merged);
targetFieldAccessor.unsetValues(ifShouldBeUnsetBlock);
}
}
}
return mergeFrom;
}
protected JMethod generateMergeFrom$createNewInstance(
final ClassOutline classOutline, final JDefinedClass theClass) {
final JMethod existingMethod = theClass.getMethod("createNewInstance",
new JType[0]);
if (existingMethod == null) {
final JMethod newMethod = theClass.method(JMod.PUBLIC, theClass
.owner().ref(Object.class), "createNewInstance");
newMethod.annotate(Override.class);
{
final JBlock body = newMethod.body();
body._return(JExpr._new(theClass));
}
return newMethod;
} else {
return existingMethod;
}
}
}
|
Java
|
using System;
using System.Collections.Generic;
using System.Drawing;
using DevExpress.XtraBars;
namespace bv.winclient.Core.TranslationTool
{
public partial class PropertyGrid : BvForm
{
public ControlDesigner SourceControl { get; private set; }
public ControlModel Model { get; private set; }
public PropertyGrid()
{
InitializeComponent();
}
public void RefreshPropertiesGrid(BarItemLinkCollection sourceControl)
{
rowCaption.Visible = categoryLocation.Visible = categorySize.Visible = false;
categoryMenuItems.Visible = true;
Model = new ControlModel
{
CanCaptionChange = false
};
foreach (var o in sourceControl)
{
var caption = String.Empty;
if (o is BarSubItemLink)
{
caption = ((BarSubItemLink) o).Item.Caption;
}
else if (o is BarLargeButtonItemLink)
{
caption = ((BarLargeButtonItemLink) o).Item.Caption;
}
if (caption.Length == 0) continue;
Model.MenuItems.Add(caption);
}
propGrid.SelectedObject = Model;
}
public void RefreshPropertiesGrid(ControlDesigner sourceControl)
{
SourceControl = sourceControl;
var control = SourceControl.RealControl;
Model = new ControlModel
{
X = control.Location.X,
Y = control.Location.Y,
Width = control.Size.Width,
Height = control.Size.Height,
CanCaptionChange = TranslationToolHelperWinClient.IsEditableControl(control)
};
if (Model.CanCaptionChange)
{
Model.OldCaption =
Model.Caption =
TranslationToolHelperWinClient.GetComponentText(control);
}
else
{
rowCaption.Visible = false;
}
if (SourceControl.MovingEnabled)
{
Model.OldLocation = control.Location;
}
else
{
categoryLocation.Visible = false;
}
if (SourceControl.SizingEnabled)
{
Model.OldSize = control.Size;
}
else
{
categorySize.Visible = false;
}
//we create a list with all menu items
if (control is PopUpButton)
{
var pb = (PopUpButton) control;
foreach (BarButtonItemLink action in pb.PopupActions.ItemLinks)
{
Model.MenuItems.Add(action.Item.Caption);
}
categoryMenuItems.Visible = true;
}
else
{
categoryMenuItems.Visible = false;
}
propGrid.SelectedObject = Model;
}
private void bCancel_Click(object sender, EventArgs e)
{
Close();
}
private void BOk_Click(object sender, EventArgs e)
{
//todo validation?
Close();
}
}
public class ControlModel
{
public string Caption { get; set; }
public int X { get; set; }
public int Y { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public bool CanCaptionChange { get; set; }
public Point OldLocation { get; set; }
public Size OldSize { get; set; }
public string OldCaption { get; set; }
public List<string> MenuItems { get; set; }
public ControlModel()
{
Caption = String.Empty;
OldCaption = String.Empty;
X = Y = Width = Height = 0;
CanCaptionChange = false;
OldLocation = new Point(0, 0);
OldSize = new Size(0, 0);
MenuItems = new List<string>();
}
public bool IsLocationChanged()
{
return new Point(X, Y) != OldLocation;
}
public bool IsSizeChanged()
{
return new Size(Width, Height) != OldSize;
}
public bool IsCaptionChanged()
{
return Caption != OldCaption;
}
}
}
|
Java
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('freebasics', '0006_change_site_url_field_type'),
]
operations = [
migrations.AddField(
model_name='freebasicscontroller',
name='postgres_db_url',
field=models.TextField(null=True, blank=True),
),
]
|
Java
|
// Copyright (c) 2019 ASMlover. All rights reserved.
//
// 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 ofconditions 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 materialsprovided with the
// distribution.
//
// 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 HOLDER 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.
#pragma once
#include "value.hh"
namespace wrencc {
class Compiler;
FunctionObject* compile(WrenVM& vm,
ModuleObject* module, const str_t& source_bytes,
bool is_expression = false, bool print_errors = false);
void mark_compiler(WrenVM& vm, Compiler* compiler);
}
|
Java
|
<?php
namespace SilverShop\ORM\FieldType;
use SilverShop\Extension\ShopConfigExtension;
use SilverStripe\Core\Convert;
use SilverStripe\ORM\FieldType\DBVarchar;
class ShopCountry extends DBVarchar
{
public function __construct($name = null, $size = 3, $options = [])
{
parent::__construct($name, $size = 3, $options);
}
public function forTemplate()
{
return $this->Nice();
}
/**
* Convert ISO abbreviation to full, translated country name
*/
public function Nice()
{
$val = ShopConfigExtension::countryCode2name($this->value);
if (!$val) {
$val = $this->value;
}
return _t(__CLASS__ . '.' . $this->value, $val);
}
public function XML()
{
return Convert::raw2xml($this->Nice());
}
}
|
Java
|
<!DOCTYPE html>
<html lang="en" dir="ltr"
xmlns:dc="http://purl.org/dc/terms/">
<head>
<meta charset="utf-8" />
<meta name="generator" content="diff2html.py (http://git.droids-corp.org/gitweb/?p=diff2html)" />
<!--meta name="author" content="Fill in" /-->
<title>HTML Diff futures/daytime_client.cpp</title>
<link rel="shortcut icon" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQAgMAAABinRfyAAAACVBMVEXAAAAAgAD///+K/HwIAAAAJUlEQVQI12NYBQQM2IgGBQ4mCIEQW7oyK4phampkGIQAc1G1AQCRxCNbyW92oQAAAABJRU5ErkJggg==" type="image/png" />
<meta property="dc:language" content="en" />
<!--meta property="dc:date" content="" /-->
<meta property="dc:modified" content="2013-11-15T07:51:48.749891+01:00" />
<meta name="description" content="File comparison" />
<meta property="dc:abstract" content="File comparison" />
<style>
table { border:0px; border-collapse:collapse; width: 100%; font-size:0.75em; font-family: Lucida Console, monospace }
td.line { color:#8080a0 }
th { background: black; color: white }
tr.diffunmodified td { background: #D0D0E0 }
tr.diffhunk td { background: #A0A0A0 }
tr.diffadded td { background: #CCFFCC }
tr.diffdeleted td { background: #FFCCCC }
tr.diffchanged td { background: #FFFFA0 }
span.diffchanged2 { background: #E0C880 }
span.diffponct { color: #B08080 }
tr.diffmisc td {}
tr.diffseparator td {}
</style>
</head>
<body>
<table class="diff">
</table>
<footer>
<p>Modified at 15.11.2013. HTML formatting created by <a href="http://git.droids-corp.org/gitweb/?p=diff2html;a=summary">diff2html</a>. </p>
</footer>
</body></html>
|
Java
|
def excise(conn, qrelname, tid):
with conn.cursor() as cur:
# Assume 'id' column exists and print that for bookkeeping.
#
# TODO: Instead should find unique constraints and print
# those, or try to print all attributes that are not corrupt.
sql = 'DELETE FROM {0} WHERE ctid = %s RETURNING id'.format(qrelname)
params = (tid,)
cur.execute(sql, params)
row = cur.fetchone()
if row:
return row[0]
return None
|
Java
|
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | Artisan Smarty |
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright 2004-2005 ARTISAN PROJECT All rights reserved. |
// +----------------------------------------------------------------------+
// | Authors: Akito<akito-artisan@five-foxes.com> |
// +----------------------------------------------------------------------+
//
/**
* ArtisanSmarty plugin
* @package ArtisanSmarty
* @subpackage plugins
*/
/**
* Smarty count_sentences modifier plugin
*
* Type: modifier<br>
* Name: count_sentences
* Purpose: count the number of sentences in a text
* @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php
* count_sentences (Smarty online manual)
* @param string
* @return integer
*/
function smarty_modifier_count_sentences($string)
{
// find periods with a word before but not after.
return preg_match_all('/[^\s]\.(?!\w)/', $string, $match);
}
/* vim: set expandtab: */
?>
|
Java
|
/*
* Copyright 2013 Toshiyuki Takahashi
*
* All rights reserved.
*
* 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.
*
* 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 HOLDER 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.
*/
package com.github.tototoshi.slick.converter
import org.joda.time._
import java.sql.{ Timestamp, Time }
trait JodaDateTimeZoneSqlStringConverter
extends SqlTypeConverter[String, DateTimeZone] {
def toSqlType(z: DateTimeZone): String =
if (z == null) null else z.getID
def fromSqlType(z: String): DateTimeZone =
if (z == null) null else DateTimeZone.forID(z)
}
trait JodaLocalDateSqlDateConverter
extends SqlTypeConverter[java.sql.Date, LocalDate] {
def toSqlType(d: LocalDate): java.sql.Date =
if (d == null) null else millisToSqlType(d.toDate)
def fromSqlType(d: java.sql.Date): LocalDate =
if (d == null) null else new LocalDate(d.getTime)
}
trait JodaDateTimeSqlTimestampConverter
extends SqlTypeConverter[Timestamp, DateTime] {
def fromSqlType(t: java.sql.Timestamp): DateTime =
if (t == null) null else new DateTime(t.getTime)
def toSqlType(t: DateTime): java.sql.Timestamp =
if (t == null) null else new java.sql.Timestamp(t.getMillis)
}
trait JodaInstantSqlTimestampConverter
extends SqlTypeConverter[Timestamp, Instant] {
def fromSqlType(t: java.sql.Timestamp): Instant =
if (t == null) null else new Instant(t.getTime)
def toSqlType(t: Instant): java.sql.Timestamp =
if (t == null) null else new java.sql.Timestamp(t.getMillis)
}
trait JodaLocalDateTimeSqlTimestampConverter
extends SqlTypeConverter[Timestamp, LocalDateTime] {
def fromSqlType(t: java.sql.Timestamp): LocalDateTime =
if (t == null) null else new LocalDateTime(t.getTime)
def toSqlType(t: LocalDateTime): java.sql.Timestamp =
if (t == null) null else new java.sql.Timestamp(t.toDate.getTime)
}
trait JodaLocalTimeSqlTimeConverter
extends SqlTypeConverter[Time, LocalTime] {
def fromSqlType(t: java.sql.Time): LocalTime =
if (t == null) null else new LocalTime(t.getTime)
def toSqlType(t: LocalTime): java.sql.Time = {
if (t == null) null else new java.sql.Time(t.toDateTimeToday.getMillis)
}
}
|
Java
|
# frozen_string_literal: true
require_relative '../helpers/load_file'
module WavefrontCli
module Subcommand
#
# Stuff to import an object
#
class Import
attr_reader :wf, :options
def initialize(calling_class, options)
@calling_class = calling_class
@wf = calling_class.wf
@options = options
@message = 'IMPORTED'
end
def run!
errs = 0
[raw_input].flatten.each do |obj|
resp = import_object(obj)
next if options[:noop]
errs += 1 unless resp.ok?
puts import_message(obj, resp)
end
exit errs
end
private
def raw_input
WavefrontCli::Helper::LoadFile.new(options[:'<file>']).load
end
def import_message(obj, resp)
format('%-15<id>s %-10<status>s %<message>s',
id: obj[:id] || obj[:url],
status: resp.ok? ? @message : 'FAILED',
message: resp.status.message)
end
def import_object(raw)
raw = preprocess_rawfile(raw) if respond_to?(:preprocess_rawfile)
prepped = @calling_class.import_to_create(raw)
if options[:upsert]
import_upsert(raw, prepped)
elsif options[:update]
@message = 'UPDATED'
import_update(raw)
else
wf.create(prepped)
end
end
def import_upsert(raw, prepped)
update_call = import_update(raw)
if update_call.ok?
@message = 'UPDATED'
return update_call
end
puts 'update failed, inserting' if options[:verbose] || options[:debug]
wf.create(prepped)
end
def import_update(raw)
wf.update(raw[:id], raw, false)
end
end
end
end
|
Java
|
/*
* Copyright (c) 2014 ASMlover. All rights reserved.
*
* 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 ofconditions 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 materialsprovided with the
* distribution.
*
* 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 HOLDER 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.
*/
#include "global.h"
#include "lexer.h"
struct KL_Lexer {
char fname[BFILE];
FILE* stream;
char lexbuf[BSIZE];
int lineno;
int bsize;
int pos;
KL_Boolean eof;
};
enum KL_LexState {
LEX_STATE_BEGIN = 0,
LEX_STATE_FINISH,
LEX_STATE_IN_CINT,
LEX_STATE_IN_CREAL,
LEX_STATE_IN_CSTR,
LEX_STATE_IN_ID,
LEX_STATE_IN_ASSIGNEQ, /* =/== */
LEX_STATE_IN_NEGLTLE, /* <>/</<= */
LEX_STATE_IN_GTGE, /* >/>= */
LEX_STATE_IN_AND, /* && */
LEX_STATE_IN_OR, /* || */
LEX_STATE_IN_COMMENT, /* # */
};
static const struct {
const char* lexptr;
int token;
} kReserveds[] = {
{"nil", TT_NIL},
{"true", TT_TRUE},
{"false", TT_FALSE},
{"if", TT_IF},
{"else", TT_ELSE},
{"while", TT_WHILE},
{"break", TT_BREAK},
{"func", TT_FUNC},
{"return", TT_RET},
};
static int
get_char(KL_Lexer* lex)
{
if (lex->pos >= lex->bsize) {
if (NULL != fgets(lex->lexbuf, sizeof(lex->lexbuf), lex->stream)) {
lex->pos = 0;
lex->bsize = (int)strlen(lex->lexbuf);
}
else {
lex->eof = BOOL_YES;
return EOF;
}
}
return lex->lexbuf[lex->pos++];
}
static void
unget_char(KL_Lexer* lex)
{
if (!lex->eof)
--lex->pos;
}
static int
lookup_reserved(const char* s)
{
int i, count = countof(kReserveds);
for (i = 0; i < count; ++i) {
if (0 == strcmp(kReserveds[i].lexptr, s))
return kReserveds[i].token;
}
return TT_ID;
}
KL_Lexer*
KL_lexer_create(const char* fname)
{
KL_Lexer* lex = (KL_Lexer*)malloc(sizeof(*lex));
if (NULL == lex)
return NULL;
do {
lex->stream = fopen(fname, "r");
if (NULL == lex->stream)
break;
strcpy(lex->fname, fname);
lex->lineno = 1;
lex->bsize = 0;
lex->pos = 0;
lex->eof = BOOL_NO;
return lex;
} while (0);
if (NULL != lex)
free(lex);
return NULL;
}
void
KL_lexer_release(KL_Lexer** lex)
{
if (NULL != *lex) {
if (NULL != (*lex)->stream)
fclose((*lex)->stream);
free(*lex);
*lex = NULL;
}
}
int
KL_lexer_token(KL_Lexer* lex, KL_Token* tok)
{
int type = TT_ERR;
int i = 0;
int state = LEX_STATE_BEGIN;
KL_Boolean save = BOOL_NO;
int c;
while (LEX_STATE_FINISH != state) {
c = get_char(lex);
save = BOOL_YES;
switch (state) {
case LEX_STATE_BEGIN:
if (' ' == c || '\t' == c) {
save = BOOL_NO;
}
else if ('\n' == c) {
save = BOOL_NO;
++lex->lineno;
}
else if (isdigit(c)) {
state = LEX_STATE_IN_CINT;
}
else if ('\'' == c) {
save = BOOL_NO;
state = LEX_STATE_IN_CSTR;
}
else if (isdigit(c) || '_' == c) {
state = LEX_STATE_IN_ID;
}
else if ('=' == c) {
state = LEX_STATE_IN_ASSIGNEQ;
}
else if ('>' == c) {
state = LEX_STATE_IN_GTGE;
}
else if ('<' == c) {
state = LEX_STATE_IN_NEGLTLE;
}
else if ('&' == c) {
state = LEX_STATE_IN_AND;
}
else if ('|' == c) {
state = LEX_STATE_IN_OR;
}
else if ('#' == c) {
state = LEX_STATE_IN_COMMENT;
}
else {
state = LEX_STATE_FINISH;
switch (c) {
case EOF:
save = BOOL_NO;
type = TT_EOF;
break;
case '+':
type = TT_ADD;
break;
case '-':
type = TT_SUB;
break;
case '*':
type = TT_MUL;
break;
case '/':
type = TT_DIV;
break;
case '%':
type = TT_MOD;
break;
case '.':
type = TT_DOT;
break;
case ',':
type = TT_COMMA;
break;
case ';':
type = TT_SEMI;
break;
case '(':
type = TT_LPAREN;
break;
case ')':
type = TT_RPAREN;
break;
case '[':
type = TT_LBRACKET;
break;
case ']':
type = TT_RBRACKET;
break;
case '{':
type = TT_LBRACE;
break;
case '}':
type = TT_RBRACE;
break;
default:
save = BOOL_NO;
type = TT_ERR;
break;
}
}
break;
case LEX_STATE_IN_CINT:
if ('.' == c) {
state = LEX_STATE_IN_CREAL;
}
else {
if (!isdigit(c)) {
unget_char(lex);
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_CINT;
}
}
break;
case LEX_STATE_IN_CREAL:
if (!isdigit(c)) {
unget_char(lex);
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_CREAL;
}
break;
case LEX_STATE_IN_CSTR:
if ('\'' == c) {
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_CSTR;
}
break;
case LEX_STATE_IN_ID:
if (!isalnum(c) && '_' != c) {
unget_char(lex);
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_ID;
}
break;
case LEX_STATE_IN_ASSIGNEQ:
if ('=' == c) {
type = TT_EQ;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_ASSIGN;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_NEGLTLE:
if ('>' == c) {
type = TT_NEQ;
}
else if ('=' == c) {
type = TT_LE;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_LT;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_GTGE:
if ('=' == c) {
type = TT_GE;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_GT;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_AND:
if ('&' == c) {
type = TT_ADD;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_ERR;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_OR:
if ('|' == c) {
type = TT_OR;
}
else {
unget_char(lex);
save = BOOL_NO;
type = TT_ERR;
}
state = LEX_STATE_FINISH;
break;
case LEX_STATE_IN_COMMENT:
save = BOOL_NO;
if (EOF == c) {
state = LEX_STATE_FINISH;
type = TT_ERR;
}
else if ('\n' == c) {
++lex->lineno;
state = LEX_STATE_BEGIN;
}
break;
case LEX_STATE_FINISH:
default:
save = BOOL_NO;
state = LEX_STATE_FINISH;
type = TT_ERR;
break;
}
if (save && i < BSIZE)
tok->name[i++] = (char)c;
if (LEX_STATE_FINISH == state) {
tok->name[i] = 0;
tok->type = type;
tok->line.lineno = lex->lineno;
strcpy(tok->line.fname, lex->fname);
if (TT_ID == type)
tok->type = type = lookup_reserved(tok->name);
}
}
return type;
}
|
Java
|
import datetime
from django.utils import timezone
from django.test import TestCase
from django.urls import reverse
from .models import Question
class QuestionMethodTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is in the future.
"""
time = timezone.now() + datetime.timedelta(days=30)
future_question = Question(pub_date=time)
self.assertIs(future_question.was_published_recently(), False)
def test_was_published_recently_with_old_question(self):
"""
was_published_recently() should return False for questions whose
pub_date is older than 1 day.
"""
time = timezone.now() - datetime.timedelta(days=30)
old_question = Question(pub_date=time)
self.assertIs(old_question.was_published_recently(), False)
def test_was_published_recently_with_recent_question(self):
"""
was_published_recently() should return True for questions whose
pub_date is within the last day.
"""
time = timezone.now() - datetime.timedelta(hours=1)
recent_question = Question(pub_date=time)
self.assertIs(recent_question.was_published_recently(), True)
def create_question(question_text, days):
"""
Creates a question with the given `question_text` and published the
given number of `days` offset to now (negative for questions published
in the past, positive for questions that have yet to be published).
"""
time = timezone.now() + datetime.timedelta(days=days)
return Question.objects.create(question_text=question_text, pub_date=time)
class QuestionViewTests(TestCase):
def test_index_view_with_no_questions(self):
"""
If no questions exist, an appropriate message should be displayed.
"""
response = self.client.get(reverse('polls:index'))
self.assertEqual(response.status_code, 200)
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_index_view_with_a_past_question(self):
"""
Questions with a pub_date in the past should be displayed on the
index page.
"""
create_question(question_text="Past question.", days=-30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_a_future_question(self):
"""
Questions with a pub_date in the future should not be displayed on
the index page.
"""
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertContains(response, "No polls are available.")
self.assertQuerysetEqual(response.context['latest_question_list'], [])
def test_index_view_with_future_question_and_past_question(self):
"""
Even if both past and future questions exist, only past questions
should be displayed.
"""
create_question(question_text="Past question.", days=-30)
create_question(question_text="Future question.", days=30)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question.>']
)
def test_index_view_with_two_past_questions(self):
"""
The questions index page may display multiple questions.
"""
create_question(question_text="Past question 1.", days=-30)
create_question(question_text="Past question 2.", days=-5)
response = self.client.get(reverse('polls:index'))
self.assertQuerysetEqual(
response.context['latest_question_list'],
['<Question: Past question 2.>', '<Question: Past question 1.>']
)
class QuestionIndexDetailTests(TestCase):
def test_detail_view_with_a_future_question(self):
"""
The detail view of a question with a pub_date in the future should
return a 404 not found.
"""
future_question = create_question(question_text='Future question.', days=5)
url = reverse('polls:detail', args=(future_question.id,))
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_detail_view_with_a_past_question(self):
"""
The detail view of a question with a pub_date in the past should
display the question's text.
"""
past_question = create_question(question_text='Past Question.', days=-5)
url = reverse('polls:detail', args=(past_question.id,))
response = self.client.get(url)
self.assertContains(response, past_question.question_text)
|
Java
|
class GetIplayer < Formula
desc "Utility for downloading TV and radio programmes from BBC iPlayer"
homepage "https://github.com/get-iplayer/get_iplayer"
url "https://github.com/get-iplayer/get_iplayer/archive/v3.06.tar.gz"
sha256 "fba3f1abd01ca6f9aaed30f9650e1e520fd3b2147fe6aa48fe7c747725b205f7"
head "https://github.com/get-iplayer/get_iplayer.git", :branch => "develop"
bottle do
cellar :any_skip_relocation
sha256 "1ed429e5a0b2df706f9015c8ca40f5b485e7e0ae68dfee45c76f784eca32b553" => :high_sierra
sha256 "1c9101656db2554d72b6f53d13fba9f84890f82119414675c5f62fb7e126373e" => :sierra
sha256 "1c9101656db2554d72b6f53d13fba9f84890f82119414675c5f62fb7e126373e" => :el_capitan
end
depends_on "atomicparsley" => :recommended
depends_on "ffmpeg" => :recommended
depends_on :macos => :yosemite
resource "IO::Socket::IP" do
url "https://cpan.metacpan.org/authors/id/P/PE/PEVANS/IO-Socket-IP-0.39.tar.gz"
sha256 "11950da7636cb786efd3bfb5891da4c820975276bce43175214391e5c32b7b96"
end
resource "Mojolicious" do
url "https://cpan.metacpan.org/authors/id/S/SR/SRI/Mojolicious-7.48.tar.gz"
sha256 "86d28e66a352e808ab1eae64ef93b90a9a92b3c1b07925bd2d3387a9e852388e"
end
def install
ENV.prepend_create_path "PERL5LIB", libexec/"lib/perl5"
resources.each do |r|
r.stage do
system "perl", "Makefile.PL", "INSTALL_BASE=#{libexec}"
system "make", "install"
end
end
inreplace ["get_iplayer", "get_iplayer.cgi"] do |s|
s.gsub!(/^(my \$version_text);/i, "\\1 = \"#{pkg_version}-homebrew\";")
s.gsub! "#!/usr/bin/env perl", "#!/usr/bin/perl"
end
bin.install "get_iplayer", "get_iplayer.cgi"
bin.env_script_all_files(libexec/"bin", :PERL5LIB => ENV["PERL5LIB"])
man1.install "get_iplayer.1"
end
test do
output = shell_output("\"#{bin}/get_iplayer\" --refresh --refresh-include=\"BBC None\" --quiet dontshowanymatches 2>&1")
assert_match "get_iplayer #{pkg_version}-homebrew", output, "Unexpected version"
assert_match "INFO: 0 matching programmes", output, "Unexpected output"
assert_match "INFO: Indexing tv programmes (concurrent)", output,
"Mojolicious not found"
end
end
|
Java
|
/*
* (C) 2014,2015,2017 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/
#include <botan/asn1_print.h>
#include <botan/bigint.h>
#include <botan/hex.h>
#include <botan/der_enc.h>
#include <botan/ber_dec.h>
#include <botan/asn1_time.h>
#include <botan/asn1_str.h>
#include <botan/oids.h>
#include <iomanip>
#include <sstream>
#include <cctype>
namespace Botan {
namespace {
bool all_printable_chars(const uint8_t bits[], size_t bits_len)
{
for(size_t i = 0; i != bits_len; ++i)
{
int c = bits[i];
if(c > 127)
return false;
if((std::isalnum(c) || c == '.' || c == ':' || c == '/' || c == '-') == false)
return false;
}
return true;
}
/*
* Special hack to handle GeneralName [2] and [6] (DNS name and URI)
*/
bool possibly_a_general_name(const uint8_t bits[], size_t bits_len)
{
if(bits_len <= 2)
return false;
if(bits[0] != 0x82 && bits[0] != 0x86)
return false;
if(bits[1] != bits_len - 2)
return false;
if(all_printable_chars(bits + 2, bits_len - 2) == false)
return false;
return true;
}
}
std::string ASN1_Formatter::print(const uint8_t in[], size_t len) const
{
std::ostringstream output;
print_to_stream(output, in, len);
return output.str();
}
void ASN1_Formatter::print_to_stream(std::ostream& output,
const uint8_t in[],
size_t len) const
{
BER_Decoder dec(in, len);
decode(output, dec, 0);
}
void ASN1_Formatter::decode(std::ostream& output,
BER_Decoder& decoder,
size_t level) const
{
BER_Object obj = decoder.get_next_object();
while(obj.type_tag != NO_OBJECT)
{
const ASN1_Tag type_tag = obj.type_tag;
const ASN1_Tag class_tag = obj.class_tag;
const size_t length = obj.value.size();
/* hack to insert the tag+length back in front of the stuff now
that we've gotten the type info */
DER_Encoder encoder;
encoder.add_object(type_tag, class_tag, obj.value);
const std::vector<uint8_t> bits = encoder.get_contents_unlocked();
BER_Decoder data(bits);
if(class_tag & CONSTRUCTED)
{
BER_Decoder cons_info(obj.value);
output << format(type_tag, class_tag, level, length, "");
decode(output, cons_info, level + 1); // recurse
}
else if((class_tag & APPLICATION) || (class_tag & CONTEXT_SPECIFIC))
{
bool success_parsing_cs = false;
if(m_print_context_specific)
{
try
{
if(possibly_a_general_name(bits.data(), bits.size()))
{
output << format(type_tag, class_tag, level, level,
std::string(cast_uint8_ptr_to_char(&bits[2]), bits.size() - 2));
success_parsing_cs = true;
}
else
{
std::vector<uint8_t> inner_bits;
data.decode(inner_bits, type_tag);
BER_Decoder inner(inner_bits);
std::ostringstream inner_data;
decode(inner_data, inner, level + 1); // recurse
output << inner_data.str();
success_parsing_cs = true;
}
}
catch(...)
{
}
}
if(success_parsing_cs == false)
{
output << format(type_tag, class_tag, level, length,
format_bin(type_tag, class_tag, bits));
}
}
else if(type_tag == OBJECT_ID)
{
OID oid;
data.decode(oid);
std::string out = OIDS::lookup(oid);
if(out.empty())
{
out = oid.as_string();
}
else
{
out += " [" + oid.as_string() + "]";
}
output << format(type_tag, class_tag, level, length, out);
}
else if(type_tag == INTEGER || type_tag == ENUMERATED)
{
BigInt number;
if(type_tag == INTEGER)
{
data.decode(number);
}
else if(type_tag == ENUMERATED)
{
data.decode(number, ENUMERATED, class_tag);
}
const std::vector<uint8_t> rep = BigInt::encode(number, BigInt::Hexadecimal);
std::string str;
for(size_t i = 0; i != rep.size(); ++i)
{
str += static_cast<char>(rep[i]);
}
output << format(type_tag, class_tag, level, length, str);
}
else if(type_tag == BOOLEAN)
{
bool boolean;
data.decode(boolean);
output << format(type_tag, class_tag, level, length, (boolean ? "true" : "false"));
}
else if(type_tag == NULL_TAG)
{
output << format(type_tag, class_tag, level, length, "");
}
else if(type_tag == OCTET_STRING || type_tag == BIT_STRING)
{
std::vector<uint8_t> decoded_bits;
data.decode(decoded_bits, type_tag);
try
{
BER_Decoder inner(decoded_bits);
std::ostringstream inner_data;
decode(inner_data, inner, level + 1); // recurse
output << format(type_tag, class_tag, level, length, "");
output << inner_data.str();
}
catch(...)
{
output << format(type_tag, class_tag, level, length,
format_bin(type_tag, class_tag, decoded_bits));
}
}
else if(ASN1_String::is_string_type(type_tag))
{
ASN1_String str;
data.decode(str);
output << format(type_tag, class_tag, level, length, str.value());
}
else if(type_tag == UTC_TIME || type_tag == GENERALIZED_TIME)
{
X509_Time time;
data.decode(time);
output << format(type_tag, class_tag, level, length, time.readable_string());
}
else
{
output << "Unknown ASN.1 tag class=" << static_cast<int>(class_tag)
<< " type=" << static_cast<int>(type_tag) << "\n";;
}
obj = decoder.get_next_object();
}
}
namespace {
std::string format_type(ASN1_Tag type_tag, ASN1_Tag class_tag)
{
if(class_tag == UNIVERSAL)
return asn1_tag_to_string(type_tag);
if(class_tag == CONSTRUCTED && (type_tag == SEQUENCE || type_tag == SET))
return asn1_tag_to_string(type_tag);
std::string name;
if(class_tag & CONSTRUCTED)
name += "cons ";
name += "[" + std::to_string(type_tag) + "]";
if(class_tag & APPLICATION)
{
name += " appl";
}
if(class_tag & CONTEXT_SPECIFIC)
{
name += " context";
}
return name;
}
}
std::string ASN1_Pretty_Printer::format(ASN1_Tag type_tag,
ASN1_Tag class_tag,
size_t level,
size_t length,
const std::string& value) const
{
bool should_skip = false;
if(value.length() > m_print_limit)
{
should_skip = true;
}
if((type_tag == OCTET_STRING || type_tag == BIT_STRING) &&
value.length() > m_print_binary_limit)
{
should_skip = true;
}
level += m_initial_level;
std::ostringstream oss;
oss << " d=" << std::setw(2) << level
<< ", l=" << std::setw(4) << length << ":"
<< std::string(level + 1, ' ') << format_type(type_tag, class_tag);
if(value != "" && !should_skip)
{
const size_t current_pos = static_cast<size_t>(oss.tellp());
const size_t spaces_to_align =
(current_pos >= m_value_column) ? 1 : (m_value_column - current_pos);
oss << std::string(spaces_to_align, ' ') << value;
}
oss << "\n";
return oss.str();
}
std::string ASN1_Pretty_Printer::format_bin(ASN1_Tag /*type_tag*/,
ASN1_Tag /*class_tag*/,
const std::vector<uint8_t>& vec) const
{
if(all_printable_chars(vec.data(), vec.size()))
{
return std::string(cast_uint8_ptr_to_char(vec.data()), vec.size());
}
else
return hex_encode(vec);
}
}
|
Java
|
package operations;
import data.Collector;
import graph.implementation.Edge;
import utility.GraphFunctions;
/**
* Set the curve point to an ideal position.
* If source and destination are equal, it would be a line.
* If not, it is a noose on top of the vertex.
*/
public class O_RelaxEdge implements EdgeOperation {
private Edge edge;
public O_RelaxEdge(Edge edge) {
super();
this.edge = edge;
}
@Override
public void run() {
Collector.getSlides().addUndo();
GraphFunctions.relaxEdge(edge);
}
@Override
public void setEdge(Edge edge) {
this.edge = edge;
}
}
|
Java
|
/*
* Copyright (c) 2016, Linaro Limited
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. 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.
*
* 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 HOLDER 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.
*/
#include <types_ext.h>
#include <drivers/ps2mouse.h>
#include <drivers/serial.h>
#include <string.h>
#include <keep.h>
#include <trace.h>
#define PS2_CMD_RESET 0xff
#define PS2_CMD_ACK 0xfa
#define PS2_CMD_ENABLE_DATA_REPORTING 0xf4
#define PS2_BAT_OK 0xaa
#define PS2_MOUSE_ID 0x00
#define PS2_BYTE0_Y_OVERFLOW (1 << 7)
#define PS2_BYTE0_X_OVERFLOW (1 << 6)
#define PS2_BYTE0_Y_SIGN (1 << 5)
#define PS2_BYTE0_X_SIGN (1 << 4)
#define PS2_BYTE0_ALWAYS_ONE (1 << 3)
#define PS2_BYTE0_MIDDLE_DOWN (1 << 2)
#define PS2_BYTE0_RIGHT_DOWN (1 << 1)
#define PS2_BYTE0_LEFT_DOWN (1 << 0)
static void call_callback(struct ps2mouse_data *d, uint8_t byte1,
uint8_t byte2, uint8_t byte3)
{
uint8_t button;
int16_t xdelta;
int16_t ydelta;
button = byte1 & (PS2_BYTE0_MIDDLE_DOWN | PS2_BYTE0_RIGHT_DOWN |
PS2_BYTE0_LEFT_DOWN);
if (byte1 & PS2_BYTE0_X_OVERFLOW) {
xdelta = byte1 & PS2_BYTE0_X_SIGN ? -255 : 255;
} else {
xdelta = byte2;
if (byte1 & PS2_BYTE0_X_SIGN)
xdelta |= 0xff00; /* sign extend */
}
if (byte1 & PS2_BYTE0_Y_OVERFLOW) {
ydelta = byte1 & PS2_BYTE0_Y_SIGN ? -255 : 255;
} else {
ydelta = byte3;
if (byte1 & PS2_BYTE0_Y_SIGN)
ydelta |= 0xff00; /* sign extend */
}
d->callback(d->callback_data, button, xdelta, -ydelta);
}
static void psm_consume(struct ps2mouse_data *d, uint8_t b)
{
switch (d->state) {
case PS2MS_RESET:
if (b != PS2_CMD_ACK)
goto reset;
d->state = PS2MS_INIT;
return;
case PS2MS_INIT:
if (b != PS2_BAT_OK)
goto reset;
d->state = PS2MS_INIT2;
return;
case PS2MS_INIT2:
if (b != PS2_MOUSE_ID) {
EMSG("Unexpected byte 0x%x in state %d", b, d->state);
d->state = PS2MS_INACTIVE;
return;
}
d->state = PS2MS_INIT3;
d->serial->ops->putc(d->serial, PS2_CMD_ENABLE_DATA_REPORTING);
return;
case PS2MS_INIT3:
d->state = PS2MS_ACTIVE1;
return;
case PS2MS_ACTIVE1:
if (!(b & PS2_BYTE0_ALWAYS_ONE))
goto reset;
d->bytes[0] = b;
d->state = PS2MS_ACTIVE2;
return;
case PS2MS_ACTIVE2:
d->bytes[1] = b;
d->state = PS2MS_ACTIVE3;
return;
case PS2MS_ACTIVE3:
d->state = PS2MS_ACTIVE1;
call_callback(d, d->bytes[0], d->bytes[1], b);
return;
default:
EMSG("Unexpected byte 0x%x in state %d", b, d->state);
return;
}
reset:
EMSG("Unexpected byte 0x%x in state %d, resetting", b, d->state);
d->state = PS2MS_RESET;
d->serial->ops->putc(d->serial, PS2_CMD_RESET);
}
static enum itr_return ps2mouse_itr_cb(struct itr_handler *h)
{
struct ps2mouse_data *d = h->data;
if (!d->serial->ops->have_rx_data(d->serial))
return ITRR_NONE;
while (true) {
psm_consume(d, d->serial->ops->getchar(d->serial));
if (!d->serial->ops->have_rx_data(d->serial))
return ITRR_HANDLED;
}
}
KEEP_PAGER(ps2mouse_itr_cb);
void ps2mouse_init(struct ps2mouse_data *d, struct serial_chip *serial,
size_t serial_it, ps2mouse_callback cb, void *cb_data)
{
memset(d, 0, sizeof(*d));
d->serial = serial;
d->state = PS2MS_RESET;
d->itr_handler.it = serial_it;
d->itr_handler.flags = ITRF_TRIGGER_LEVEL;
d->itr_handler.handler = ps2mouse_itr_cb;
d->itr_handler.data = d;
d->callback = cb;
d->callback_data = cb_data;
itr_add(&d->itr_handler);
itr_enable(&d->itr_handler);
d->serial->ops->putc(d->serial, PS2_CMD_RESET);
}
|
Java
|
# Gearman
[](LICENSE.txt) [](http://godoc.org/github.com/nathanaelle/gearman) [](https://travis-ci.org/nathanaelle/gearman) [](https://goreportcard.com/report/github.com/nathanaelle/gearman)
## Examples
### Worker Example
```
ctx, cancel := context.WithCancel(context.Background())
w := gearman.NewWorker(ctx, nil)
w.AddServers( gearman.NetConn("tcp","localhost:4730") )
w.AddHandler("reverse", gearman.JobHandler(func(payload io.Reader,reply io.Writer) (error){
buff := make([]byte,1<<16)
s,_ := payload.Read(buff)
buff = buff[0:s]
for i:=len(buff); i>0; i-- {
reply.Write([]byte{ buff[i-1] })
}
return nil
} ))
<-ctx.Done()
```
### Client Example
```
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w := gearman.SingleServerClient(ctx, nil)
w.AddServers( gearman.NetConn("tcp","localhost:4730") )
bytes_val, err_if_any := cli.Submit( NewTask("some task", []byte("some byte encoded payload")) ).Value()
```
## Features
* Worker Support
* Client Support
* Access To Raw Packets
* Async Client Task with promise
## Protocol Support
### Protocol Plumbing
The protocol implemented is now https://github.com/gearman/gearmand/blob/master/PROTOCOL
* Binary only protocol
* Access Raw Packets
### Protocol Porcelain
* PacketFactory for parsing socket
* Multi server Worker
* Single server Client
* Round Robin Client
## License
2-Clause BSD
## Benchmarks
### PacketFactory on LoopReader
```
BenchmarkPacketFactoryPkt0size-4 30000000 43.8 ns/op 20 B/op 1 allocs/op
BenchmarkPacketFactoryPkt1len-4 30000000 53.1 ns/op 33 B/op 1 allocs/op
BenchmarkPacketFactoryPktcommon-4 10000000 145 ns/op 128 B/op 2 allocs/op
```
### Unmarshal
```
BenchmarkUnmarshalPkt0size-4 100000000 22.7 ns/op 8 B/op 1 allocs/op
BenchmarkUnmarshalPkt1len-4 30000000 45.2 ns/op 48 B/op 1 allocs/op
BenchmarkUnmarshalPktcommon-4 20000000 112 ns/op 96 B/op 2 allocs/op
```
### Marshal
```
BenchmarkMarshalPkt0size-4 300000000 4.25 ns/op 0 B/op 0 allocs/op
BenchmarkMarshalPkt1len-4 200000000 9.70 ns/op 0 B/op 0 allocs/op
BenchmarkMarshalPktcommon-4 200000000 9.81 ns/op 0 B/op 0 allocs/op
```
|
Java
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "UnrealEd.h"
#include "SoundMod.h"
DECLARE_LOG_CATEGORY_EXTERN(LogSoundModImporter, Verbose, All);
#include "SoundModImporterClasses.h"
|
Java
|
/**
* @license AngularJS v1.3.0-build.2480+sha.fb6062f
* (c) 2010-2014 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, angular, undefined) {'use strict';
/* jshint maxlen: false */
/**
* @ngdoc module
* @name ngAnimate
* @description
*
* # ngAnimate
*
* The `ngAnimate` module provides support for JavaScript, CSS3 transition and CSS3 keyframe animation hooks within existing core and custom directives.
*
*
* <div doc-module-components="ngAnimate"></div>
*
* # Usage
*
* To see animations in action, all that is required is to define the appropriate CSS classes
* or to register a JavaScript animation via the myModule.animation() function. The directives that support animation automatically are:
* `ngRepeat`, `ngInclude`, `ngIf`, `ngSwitch`, `ngShow`, `ngHide`, `ngView` and `ngClass`. Custom directives can take advantage of animation
* by using the `$animate` service.
*
* Below is a more detailed breakdown of the supported animation events provided by pre-existing ng directives:
*
* | Directive | Supported Animations |
* |---------------------------------------------------------- |----------------------------------------------------|
* | {@link ng.directive:ngRepeat#usage_animations ngRepeat} | enter, leave and move |
* | {@link ngRoute.directive:ngView#usage_animations ngView} | enter and leave |
* | {@link ng.directive:ngInclude#usage_animations ngInclude} | enter and leave |
* | {@link ng.directive:ngSwitch#usage_animations ngSwitch} | enter and leave |
* | {@link ng.directive:ngIf#usage_animations ngIf} | enter and leave |
* | {@link ng.directive:ngClass#usage_animations ngClass} | add and remove |
* | {@link ng.directive:ngShow#usage_animations ngShow & ngHide} | add and remove (the ng-hide class value) |
* | {@link ng.directive:form#usage_animations form} | add and remove (dirty, pristine, valid, invalid & all other validations) |
* | {@link ng.directive:ngModel#usage_animations ngModel} | add and remove (dirty, pristine, valid, invalid & all other validations) |
*
* You can find out more information about animations upon visiting each directive page.
*
* Below is an example of how to apply animations to a directive that supports animation hooks:
*
* ```html
* <style type="text/css">
* .slide.ng-enter, .slide.ng-leave {
* -webkit-transition:0.5s linear all;
* transition:0.5s linear all;
* }
*
* .slide.ng-enter { } /* starting animations for enter */
* .slide.ng-enter-active { } /* terminal animations for enter */
* .slide.ng-leave { } /* starting animations for leave */
* .slide.ng-leave-active { } /* terminal animations for leave */
* </style>
*
* <!--
* the animate service will automatically add .ng-enter and .ng-leave to the element
* to trigger the CSS transition/animations
* -->
* <ANY class="slide" ng-include="..."></ANY>
* ```
*
* Keep in mind that if an animation is running, any child elements cannot be animated until the parent element's
* animation has completed.
*
* <h2>CSS-defined Animations</h2>
* The animate service will automatically apply two CSS classes to the animated element and these two CSS classes
* are designed to contain the start and end CSS styling. Both CSS transitions and keyframe animations are supported
* and can be used to play along with this naming structure.
*
* The following code below demonstrates how to perform animations using **CSS transitions** with Angular:
*
* ```html
* <style type="text/css">
* /*
* The animate class is apart of the element and the ng-enter class
* is attached to the element once the enter animation event is triggered
* */
* .reveal-animation.ng-enter {
* -webkit-transition: 1s linear all; /* Safari/Chrome */
* transition: 1s linear all; /* All other modern browsers and IE10+ */
*
* /* The animation preparation code */
* opacity: 0;
* }
*
* /*
* Keep in mind that you want to combine both CSS
* classes together to avoid any CSS-specificity
* conflicts
* */
* .reveal-animation.ng-enter.ng-enter-active {
* /* The animation code itself */
* opacity: 1;
* }
* </style>
*
* <div class="view-container">
* <div ng-view class="reveal-animation"></div>
* </div>
* ```
*
* The following code below demonstrates how to perform animations using **CSS animations** with Angular:
*
* ```html
* <style type="text/css">
* .reveal-animation.ng-enter {
* -webkit-animation: enter_sequence 1s linear; /* Safari/Chrome */
* animation: enter_sequence 1s linear; /* IE10+ and Future Browsers */
* }
* @-webkit-keyframes enter_sequence {
* from { opacity:0; }
* to { opacity:1; }
* }
* @keyframes enter_sequence {
* from { opacity:0; }
* to { opacity:1; }
* }
* </style>
*
* <div class="view-container">
* <div ng-view class="reveal-animation"></div>
* </div>
* ```
*
* Both CSS3 animations and transitions can be used together and the animate service will figure out the correct duration and delay timing.
*
* Upon DOM mutation, the event class is added first (something like `ng-enter`), then the browser prepares itself to add
* the active class (in this case `ng-enter-active`) which then triggers the animation. The animation module will automatically
* detect the CSS code to determine when the animation ends. Once the animation is over then both CSS classes will be
* removed from the DOM. If a browser does not support CSS transitions or CSS animations then the animation will start and end
* immediately resulting in a DOM element that is at its final state. This final state is when the DOM element
* has no CSS transition/animation classes applied to it.
*
* <h3>CSS Staggering Animations</h3>
* A Staggering animation is a collection of animations that are issued with a slight delay in between each successive operation resulting in a
* curtain-like effect. The ngAnimate module, as of 1.2.0, supports staggering animations and the stagger effect can be
* performed by creating a **ng-EVENT-stagger** CSS class and attaching that class to the base CSS class used for
* the animation. The style property expected within the stagger class can either be a **transition-delay** or an
* **animation-delay** property (or both if your animation contains both transitions and keyframe animations).
*
* ```css
* .my-animation.ng-enter {
* /* standard transition code */
* -webkit-transition: 1s linear all;
* transition: 1s linear all;
* opacity:0;
* }
* .my-animation.ng-enter-stagger {
* /* this will have a 100ms delay between each successive leave animation */
* -webkit-transition-delay: 0.1s;
* transition-delay: 0.1s;
*
* /* in case the stagger doesn't work then these two values
* must be set to 0 to avoid an accidental CSS inheritance */
* -webkit-transition-duration: 0s;
* transition-duration: 0s;
* }
* .my-animation.ng-enter.ng-enter-active {
* /* standard transition styles */
* opacity:1;
* }
* ```
*
* Staggering animations work by default in ngRepeat (so long as the CSS class is defined). Outside of ngRepeat, to use staggering animations
* on your own, they can be triggered by firing multiple calls to the same event on $animate. However, the restrictions surrounding this
* are that each of the elements must have the same CSS className value as well as the same parent element. A stagger operation
* will also be reset if more than 10ms has passed after the last animation has been fired.
*
* The following code will issue the **ng-leave-stagger** event on the element provided:
*
* ```js
* var kids = parent.children();
*
* $animate.leave(kids[0]); //stagger index=0
* $animate.leave(kids[1]); //stagger index=1
* $animate.leave(kids[2]); //stagger index=2
* $animate.leave(kids[3]); //stagger index=3
* $animate.leave(kids[4]); //stagger index=4
*
* $timeout(function() {
* //stagger has reset itself
* $animate.leave(kids[5]); //stagger index=0
* $animate.leave(kids[6]); //stagger index=1
* }, 100, false);
* ```
*
* Stagger animations are currently only supported within CSS-defined animations.
*
* <h2>JavaScript-defined Animations</h2>
* In the event that you do not want to use CSS3 transitions or CSS3 animations or if you wish to offer animations on browsers that do not
* yet support CSS transitions/animations, then you can make use of JavaScript animations defined inside of your AngularJS module.
*
* ```js
* //!annotate="YourApp" Your AngularJS Module|Replace this or ngModule with the module that you used to define your application.
* var ngModule = angular.module('YourApp', ['ngAnimate']);
* ngModule.animation('.my-crazy-animation', function() {
* return {
* enter: function(element, done) {
* //run the animation here and call done when the animation is complete
* return function(cancelled) {
* //this (optional) function will be called when the animation
* //completes or when the animation is cancelled (the cancelled
* //flag will be set to true if cancelled).
* };
* },
* leave: function(element, done) { },
* move: function(element, done) { },
*
* //animation that can be triggered before the class is added
* beforeAddClass: function(element, className, done) { },
*
* //animation that can be triggered after the class is added
* addClass: function(element, className, done) { },
*
* //animation that can be triggered before the class is removed
* beforeRemoveClass: function(element, className, done) { },
*
* //animation that can be triggered after the class is removed
* removeClass: function(element, className, done) { }
* };
* });
* ```
*
* JavaScript-defined animations are created with a CSS-like class selector and a collection of events which are set to run
* a javascript callback function. When an animation is triggered, $animate will look for a matching animation which fits
* the element's CSS class attribute value and then run the matching animation event function (if found).
* In other words, if the CSS classes present on the animated element match any of the JavaScript animations then the callback function will
* be executed. It should be also noted that only simple, single class selectors are allowed (compound class selectors are not supported).
*
* Within a JavaScript animation, an object containing various event callback animation functions is expected to be returned.
* As explained above, these callbacks are triggered based on the animation event. Therefore if an enter animation is run,
* and the JavaScript animation is found, then the enter callback will handle that animation (in addition to the CSS keyframe animation
* or transition code that is defined via a stylesheet).
*
*/
angular.module('ngAnimate', ['ng'])
/**
* @ngdoc provider
* @name $animateProvider
* @description
*
* The `$animateProvider` allows developers to register JavaScript animation event handlers directly inside of a module.
* When an animation is triggered, the $animate service will query the $animate service to find any animations that match
* the provided name value.
*
* Requires the {@link ngAnimate `ngAnimate`} module to be installed.
*
* Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
*
*/
//this private service is only used within CSS-enabled animations
//IE8 + IE9 do not support rAF natively, but that is fine since they
//also don't support transitions and keyframes which means that the code
//below will never be used by the two browsers.
.factory('$$animateReflow', ['$$rAF', '$document', function($$rAF, $document) {
var bod = $document[0].body;
return function(fn) {
//the returned function acts as the cancellation function
return $$rAF(function() {
//the line below will force the browser to perform a repaint
//so that all the animated elements within the animation frame
//will be properly updated and drawn on screen. This is
//required to perform multi-class CSS based animations with
//Firefox. DO NOT REMOVE THIS LINE.
var a = bod.offsetWidth + 1;
fn();
});
};
}])
.config(['$provide', '$animateProvider', function($provide, $animateProvider) {
var noop = angular.noop;
var forEach = angular.forEach;
var selectors = $animateProvider.$$selectors;
var ELEMENT_NODE = 1;
var NG_ANIMATE_STATE = '$$ngAnimateState';
var NG_ANIMATE_CLASS_NAME = 'ng-animate';
var rootAnimateState = {running: true};
function extractElementNode(element) {
for(var i = 0; i < element.length; i++) {
var elm = element[i];
if(elm.nodeType == ELEMENT_NODE) {
return elm;
}
}
}
function stripCommentsFromElement(element) {
return angular.element(extractElementNode(element));
}
function isMatchingElement(elm1, elm2) {
return extractElementNode(elm1) == extractElementNode(elm2);
}
$provide.decorator('$animate', ['$delegate', '$injector', '$sniffer', '$rootElement', '$$asyncCallback', '$rootScope', '$document',
function($delegate, $injector, $sniffer, $rootElement, $$asyncCallback, $rootScope, $document) {
var globalAnimationCounter = 0;
$rootElement.data(NG_ANIMATE_STATE, rootAnimateState);
// disable animations during bootstrap, but once we bootstrapped, wait again
// for another digest until enabling animations. The reason why we digest twice
// is because all structural animations (enter, leave and move) all perform a
// post digest operation before animating. If we only wait for a single digest
// to pass then the structural animation would render its animation on page load.
// (which is what we're trying to avoid when the application first boots up.)
$rootScope.$$postDigest(function() {
$rootScope.$$postDigest(function() {
rootAnimateState.running = false;
});
});
var classNameFilter = $animateProvider.classNameFilter();
var isAnimatableClassName = !classNameFilter
? function() { return true; }
: function(className) {
return classNameFilter.test(className);
};
function lookup(name) {
if (name) {
var matches = [],
flagMap = {},
classes = name.substr(1).split('.');
//the empty string value is the default animation
//operation which performs CSS transition and keyframe
//animations sniffing. This is always included for each
//element animation procedure if the browser supports
//transitions and/or keyframe animations
if ($sniffer.transitions || $sniffer.animations) {
classes.push('');
}
for(var i=0; i < classes.length; i++) {
var klass = classes[i],
selectorFactoryName = selectors[klass];
if(selectorFactoryName && !flagMap[klass]) {
matches.push($injector.get(selectorFactoryName));
flagMap[klass] = true;
}
}
return matches;
}
}
function animationRunner(element, animationEvent, className) {
//transcluded directives may sometimes fire an animation using only comment nodes
//best to catch this early on to prevent any animation operations from occurring
var node = element[0];
if(!node) {
return;
}
var isSetClassOperation = animationEvent == 'setClass';
var isClassBased = isSetClassOperation ||
animationEvent == 'addClass' ||
animationEvent == 'removeClass';
var classNameAdd, classNameRemove;
if(angular.isArray(className)) {
classNameAdd = className[0];
classNameRemove = className[1];
className = classNameAdd + ' ' + classNameRemove;
}
var currentClassName = element.attr('class');
var classes = currentClassName + ' ' + className;
if(!isAnimatableClassName(classes)) {
return;
}
var beforeComplete = noop,
beforeCancel = [],
before = [],
afterComplete = noop,
afterCancel = [],
after = [];
var animationLookup = (' ' + classes).replace(/\s+/g,'.');
forEach(lookup(animationLookup), function(animationFactory) {
var created = registerAnimation(animationFactory, animationEvent);
if(!created && isSetClassOperation) {
registerAnimation(animationFactory, 'addClass');
registerAnimation(animationFactory, 'removeClass');
}
});
function registerAnimation(animationFactory, event) {
var afterFn = animationFactory[event];
var beforeFn = animationFactory['before' + event.charAt(0).toUpperCase() + event.substr(1)];
if(afterFn || beforeFn) {
if(event == 'leave') {
beforeFn = afterFn;
//when set as null then animation knows to skip this phase
afterFn = null;
}
after.push({
event : event, fn : afterFn
});
before.push({
event : event, fn : beforeFn
});
return true;
}
}
function run(fns, cancellations, allCompleteFn) {
var animations = [];
forEach(fns, function(animation) {
animation.fn && animations.push(animation);
});
var count = 0;
function afterAnimationComplete(index) {
if(cancellations) {
(cancellations[index] || noop)();
if(++count < animations.length) return;
cancellations = null;
}
allCompleteFn();
}
//The code below adds directly to the array in order to work with
//both sync and async animations. Sync animations are when the done()
//operation is called right away. DO NOT REFACTOR!
forEach(animations, function(animation, index) {
var progress = function() {
afterAnimationComplete(index);
};
switch(animation.event) {
case 'setClass':
cancellations.push(animation.fn(element, classNameAdd, classNameRemove, progress));
break;
case 'addClass':
cancellations.push(animation.fn(element, classNameAdd || className, progress));
break;
case 'removeClass':
cancellations.push(animation.fn(element, classNameRemove || className, progress));
break;
default:
cancellations.push(animation.fn(element, progress));
break;
}
});
if(cancellations && cancellations.length === 0) {
allCompleteFn();
}
}
return {
node : node,
event : animationEvent,
className : className,
isClassBased : isClassBased,
isSetClassOperation : isSetClassOperation,
before : function(allCompleteFn) {
beforeComplete = allCompleteFn;
run(before, beforeCancel, function() {
beforeComplete = noop;
allCompleteFn();
});
},
after : function(allCompleteFn) {
afterComplete = allCompleteFn;
run(after, afterCancel, function() {
afterComplete = noop;
allCompleteFn();
});
},
cancel : function() {
if(beforeCancel) {
forEach(beforeCancel, function(cancelFn) {
(cancelFn || noop)(true);
});
beforeComplete(true);
}
if(afterCancel) {
forEach(afterCancel, function(cancelFn) {
(cancelFn || noop)(true);
});
afterComplete(true);
}
}
};
}
/**
* @ngdoc service
* @name $animate
* @function
*
* @description
* The `$animate` service provides animation detection support while performing DOM operations (enter, leave and move) as well as during addClass and removeClass operations.
* When any of these operations are run, the $animate service
* will examine any JavaScript-defined animations (which are defined by using the $animateProvider provider object)
* as well as any CSS-defined animations against the CSS classes present on the element once the DOM operation is run.
*
* The `$animate` service is used behind the scenes with pre-existing directives and animation with these directives
* will work out of the box without any extra configuration.
*
* Requires the {@link ngAnimate `ngAnimate`} module to be installed.
*
* Please visit the {@link ngAnimate `ngAnimate`} module overview page learn more about how to use animations in your application.
*
*/
return {
/**
* @ngdoc method
* @name $animate#enter
* @function
*
* @description
* Appends the element to the parentElement element that resides in the document and then runs the enter animation. Once
* the animation is started, the following CSS classes will be present on the element for the duration of the animation:
*
* Below is a breakdown of each step that occurs during enter animation:
*
* | Animation Step | What the element class attribute looks like |
* |----------------------------------------------------------------------------------------------|---------------------------------------------|
* | 1. $animate.enter(...) is called | class="my-animation" |
* | 2. element is inserted into the parentElement element or beside the afterElement element | class="my-animation" |
* | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" |
* | 4. the .ng-enter class is added to the element | class="my-animation ng-animate ng-enter" |
* | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-enter" |
* | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-enter" |
* | 7. the .ng-enter-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" |
* | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-enter ng-enter-active" |
* | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
* | 10. The doneCallback() callback is fired (if provided) | class="my-animation" |
*
* @param {DOMElement} element the element that will be the focus of the enter animation
* @param {DOMElement} parentElement the parent element of the element that will be the focus of the enter animation
* @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the enter animation
* @param {function()=} doneCallback the callback function that will be called once the animation is complete
*/
enter : function(element, parentElement, afterElement, doneCallback) {
this.enabled(false, element);
$delegate.enter(element, parentElement, afterElement);
$rootScope.$$postDigest(function() {
element = stripCommentsFromElement(element);
performAnimation('enter', 'ng-enter', element, parentElement, afterElement, noop, doneCallback);
});
},
/**
* @ngdoc method
* @name $animate#leave
* @function
*
* @description
* Runs the leave animation operation and, upon completion, removes the element from the DOM. Once
* the animation is started, the following CSS classes will be added for the duration of the animation:
*
* Below is a breakdown of each step that occurs during leave animation:
*
* | Animation Step | What the element class attribute looks like |
* |----------------------------------------------------------------------------------------------|---------------------------------------------|
* | 1. $animate.leave(...) is called | class="my-animation" |
* | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" |
* | 3. the .ng-leave class is added to the element | class="my-animation ng-animate ng-leave" |
* | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-leave" |
* | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-leave" |
* | 6. the .ng-leave-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" |
* | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-leave ng-leave-active" |
* | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
* | 9. The element is removed from the DOM | ... |
* | 10. The doneCallback() callback is fired (if provided) | ... |
*
* @param {DOMElement} element the element that will be the focus of the leave animation
* @param {function()=} doneCallback the callback function that will be called once the animation is complete
*/
leave : function(element, doneCallback) {
cancelChildAnimations(element);
this.enabled(false, element);
$rootScope.$$postDigest(function() {
performAnimation('leave', 'ng-leave', stripCommentsFromElement(element), null, null, function() {
$delegate.leave(element);
}, doneCallback);
});
},
/**
* @ngdoc method
* @name $animate#move
* @function
*
* @description
* Fires the move DOM operation. Just before the animation starts, the animate service will either append it into the parentElement container or
* add the element directly after the afterElement element if present. Then the move animation will be run. Once
* the animation is started, the following CSS classes will be added for the duration of the animation:
*
* Below is a breakdown of each step that occurs during move animation:
*
* | Animation Step | What the element class attribute looks like |
* |----------------------------------------------------------------------------------------------|---------------------------------------------|
* | 1. $animate.move(...) is called | class="my-animation" |
* | 2. element is moved into the parentElement element or beside the afterElement element | class="my-animation" |
* | 3. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" |
* | 4. the .ng-move class is added to the element | class="my-animation ng-animate ng-move" |
* | 5. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate ng-move" |
* | 6. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate ng-move" |
* | 7. the .ng-move-active and .ng-animate-active classes is added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" |
* | 8. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active ng-move ng-move-active" |
* | 9. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
* | 10. The doneCallback() callback is fired (if provided) | class="my-animation" |
*
* @param {DOMElement} element the element that will be the focus of the move animation
* @param {DOMElement} parentElement the parentElement element of the element that will be the focus of the move animation
* @param {DOMElement} afterElement the sibling element (which is the previous element) of the element that will be the focus of the move animation
* @param {function()=} doneCallback the callback function that will be called once the animation is complete
*/
move : function(element, parentElement, afterElement, doneCallback) {
cancelChildAnimations(element);
this.enabled(false, element);
$delegate.move(element, parentElement, afterElement);
$rootScope.$$postDigest(function() {
element = stripCommentsFromElement(element);
performAnimation('move', 'ng-move', element, parentElement, afterElement, noop, doneCallback);
});
},
/**
* @ngdoc method
* @name $animate#addClass
*
* @description
* Triggers a custom animation event based off the className variable and then attaches the className value to the element as a CSS class.
* Unlike the other animation methods, the animate service will suffix the className value with {@type -add} in order to provide
* the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if no CSS transitions
* or keyframes are defined on the -add or base CSS class).
*
* Below is a breakdown of each step that occurs during addClass animation:
*
* | Animation Step | What the element class attribute looks like |
* |------------------------------------------------------------------------------------------------|---------------------------------------------|
* | 1. $animate.addClass(element, 'super') is called | class="my-animation" |
* | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation ng-animate" |
* | 3. the .super-add class are added to the element | class="my-animation ng-animate super-add" |
* | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation ng-animate super-add" |
* | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation ng-animate super-add" |
* | 6. the .super, .super-add-active and .ng-animate-active classes are added (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super super-add super-add-active" |
* | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation super super-add super-add-active" |
* | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation super" |
* | 9. The super class is kept on the element | class="my-animation super" |
* | 10. The doneCallback() callback is fired (if provided) | class="my-animation super" |
*
* @param {DOMElement} element the element that will be animated
* @param {string} className the CSS class that will be added to the element and then animated
* @param {function()=} doneCallback the callback function that will be called once the animation is complete
*/
addClass : function(element, className, doneCallback) {
element = stripCommentsFromElement(element);
performAnimation('addClass', className, element, null, null, function() {
$delegate.addClass(element, className);
}, doneCallback);
},
/**
* @ngdoc method
* @name $animate#removeClass
*
* @description
* Triggers a custom animation event based off the className variable and then removes the CSS class provided by the className value
* from the element. Unlike the other animation methods, the animate service will suffix the className value with {@type -remove} in
* order to provide the animate service the setup and active CSS classes in order to trigger the animation (this will be skipped if
* no CSS transitions or keyframes are defined on the -remove or base CSS classes).
*
* Below is a breakdown of each step that occurs during removeClass animation:
*
* | Animation Step | What the element class attribute looks like |
* |-----------------------------------------------------------------------------------------------|---------------------------------------------|
* | 1. $animate.removeClass(element, 'super') is called | class="my-animation super" |
* | 2. $animate runs any JavaScript-defined animations on the element | class="my-animation super ng-animate" |
* | 3. the .super-remove class are added to the element | class="my-animation super ng-animate super-remove"|
* | 4. $animate scans the element styles to get the CSS transition/animation duration and delay | class="my-animation super ng-animate super-remove" |
* | 5. $animate waits for 10ms (this performs a reflow) | class="my-animation super ng-animate super-remove" |
* | 6. the .super-remove-active and .ng-animate-active classes are added and .super is removed (this triggers the CSS transition/animation) | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" |
* | 7. $animate waits for X milliseconds for the animation to complete | class="my-animation ng-animate ng-animate-active super-remove super-remove-active" |
* | 8. The animation ends and all generated CSS classes are removed from the element | class="my-animation" |
* | 9. The doneCallback() callback is fired (if provided) | class="my-animation" |
*
*
* @param {DOMElement} element the element that will be animated
* @param {string} className the CSS class that will be animated and then removed from the element
* @param {function()=} doneCallback the callback function that will be called once the animation is complete
*/
removeClass : function(element, className, doneCallback) {
element = stripCommentsFromElement(element);
performAnimation('removeClass', className, element, null, null, function() {
$delegate.removeClass(element, className);
}, doneCallback);
},
/**
*
* @ngdoc function
* @name $animate#setClass
* @function
* @description Adds and/or removes the given CSS classes to and from the element.
* Once complete, the done() callback will be fired (if provided).
* @param {DOMElement} element the element which will it's CSS classes changed
* removed from it
* @param {string} add the CSS classes which will be added to the element
* @param {string} remove the CSS class which will be removed from the element
* @param {Function=} done the callback function (if provided) that will be fired after the
* CSS classes have been set on the element
*/
setClass : function(element, add, remove, doneCallback) {
element = stripCommentsFromElement(element);
performAnimation('setClass', [add, remove], element, null, null, function() {
$delegate.setClass(element, add, remove);
}, doneCallback);
},
/**
* @ngdoc method
* @name $animate#enabled
* @function
*
* @param {boolean=} value If provided then set the animation on or off.
* @param {DOMElement=} element If provided then the element will be used to represent the enable/disable operation
* @return {boolean} Current animation state.
*
* @description
* Globally enables/disables animations.
*
*/
enabled : function(value, element) {
switch(arguments.length) {
case 2:
if(value) {
cleanup(element);
} else {
var data = element.data(NG_ANIMATE_STATE) || {};
data.disabled = true;
element.data(NG_ANIMATE_STATE, data);
}
break;
case 1:
rootAnimateState.disabled = !value;
break;
default:
value = !rootAnimateState.disabled;
break;
}
return !!value;
}
};
/*
all animations call this shared animation triggering function internally.
The animationEvent variable refers to the JavaScript animation event that will be triggered
and the className value is the name of the animation that will be applied within the
CSS code. Element, parentElement and afterElement are provided DOM elements for the animation
and the onComplete callback will be fired once the animation is fully complete.
*/
function performAnimation(animationEvent, className, element, parentElement, afterElement, domOperation, doneCallback) {
var runner = animationRunner(element, animationEvent, className);
if(!runner) {
fireDOMOperation();
fireBeforeCallbackAsync();
fireAfterCallbackAsync();
closeAnimation();
return;
}
className = runner.className;
var elementEvents = angular.element._data(runner.node);
elementEvents = elementEvents && elementEvents.events;
if (!parentElement) {
parentElement = afterElement ? afterElement.parent() : element.parent();
}
var ngAnimateState = element.data(NG_ANIMATE_STATE) || {};
var runningAnimations = ngAnimateState.active || {};
var totalActiveAnimations = ngAnimateState.totalActive || 0;
var lastAnimation = ngAnimateState.last;
//only allow animations if the currently running animation is not structural
//or if there is no animation running at all
var skipAnimations = runner.isClassBased ?
ngAnimateState.disabled || (lastAnimation && !lastAnimation.isClassBased) :
false;
//skip the animation if animations are disabled, a parent is already being animated,
//the element is not currently attached to the document body or then completely close
//the animation if any matching animations are not found at all.
//NOTE: IE8 + IE9 should close properly (run closeAnimation()) in case an animation was found.
if (skipAnimations || animationsDisabled(element, parentElement)) {
fireDOMOperation();
fireBeforeCallbackAsync();
fireAfterCallbackAsync();
closeAnimation();
return;
}
var skipAnimation = false;
if(totalActiveAnimations > 0) {
var animationsToCancel = [];
if(!runner.isClassBased) {
if(animationEvent == 'leave' && runningAnimations['ng-leave']) {
skipAnimation = true;
} else {
//cancel all animations when a structural animation takes place
for(var klass in runningAnimations) {
animationsToCancel.push(runningAnimations[klass]);
cleanup(element, klass);
}
runningAnimations = {};
totalActiveAnimations = 0;
}
} else if(lastAnimation.event == 'setClass') {
animationsToCancel.push(lastAnimation);
cleanup(element, className);
}
else if(runningAnimations[className]) {
var current = runningAnimations[className];
if(current.event == animationEvent) {
skipAnimation = true;
} else {
animationsToCancel.push(current);
cleanup(element, className);
}
}
if(animationsToCancel.length > 0) {
forEach(animationsToCancel, function(operation) {
operation.cancel();
});
}
}
if(runner.isClassBased && !runner.isSetClassOperation && !skipAnimation) {
skipAnimation = (animationEvent == 'addClass') == element.hasClass(className); //opposite of XOR
}
if(skipAnimation) {
fireBeforeCallbackAsync();
fireAfterCallbackAsync();
fireDoneCallbackAsync();
return;
}
if(animationEvent == 'leave') {
//there's no need to ever remove the listener since the element
//will be removed (destroyed) after the leave animation ends or
//is cancelled midway
element.one('$destroy', function(e) {
var element = angular.element(this);
var state = element.data(NG_ANIMATE_STATE);
if(state) {
var activeLeaveAnimation = state.active['ng-leave'];
if(activeLeaveAnimation) {
activeLeaveAnimation.cancel();
cleanup(element, 'ng-leave');
}
}
});
}
//the ng-animate class does nothing, but it's here to allow for
//parent animations to find and cancel child animations when needed
element.addClass(NG_ANIMATE_CLASS_NAME);
var localAnimationCount = globalAnimationCounter++;
totalActiveAnimations++;
runningAnimations[className] = runner;
element.data(NG_ANIMATE_STATE, {
last : runner,
active : runningAnimations,
index : localAnimationCount,
totalActive : totalActiveAnimations
});
//first we run the before animations and when all of those are complete
//then we perform the DOM operation and run the next set of animations
fireBeforeCallbackAsync();
runner.before(function(cancelled) {
var data = element.data(NG_ANIMATE_STATE);
cancelled = cancelled ||
!data || !data.active[className] ||
(runner.isClassBased && data.active[className].event != animationEvent);
fireDOMOperation();
if(cancelled === true) {
closeAnimation();
} else {
fireAfterCallbackAsync();
runner.after(closeAnimation);
}
});
function fireDOMCallback(animationPhase) {
var eventName = '$animate:' + animationPhase;
if(elementEvents && elementEvents[eventName] && elementEvents[eventName].length > 0) {
$$asyncCallback(function() {
element.triggerHandler(eventName, {
event : animationEvent,
className : className
});
});
}
}
function fireBeforeCallbackAsync() {
fireDOMCallback('before');
}
function fireAfterCallbackAsync() {
fireDOMCallback('after');
}
function fireDoneCallbackAsync() {
fireDOMCallback('close');
if(doneCallback) {
$$asyncCallback(function() {
doneCallback();
});
}
}
//it is less complicated to use a flag than managing and canceling
//timeouts containing multiple callbacks.
function fireDOMOperation() {
if(!fireDOMOperation.hasBeenRun) {
fireDOMOperation.hasBeenRun = true;
domOperation();
}
}
function closeAnimation() {
if(!closeAnimation.hasBeenRun) {
closeAnimation.hasBeenRun = true;
var data = element.data(NG_ANIMATE_STATE);
if(data) {
/* only structural animations wait for reflow before removing an
animation, but class-based animations don't. An example of this
failing would be when a parent HTML tag has a ng-class attribute
causing ALL directives below to skip animations during the digest */
if(runner && runner.isClassBased) {
cleanup(element, className);
} else {
$$asyncCallback(function() {
var data = element.data(NG_ANIMATE_STATE) || {};
if(localAnimationCount == data.index) {
cleanup(element, className, animationEvent);
}
});
element.data(NG_ANIMATE_STATE, data);
}
}
fireDoneCallbackAsync();
}
}
}
function cancelChildAnimations(element) {
var node = extractElementNode(element);
if (node) {
var nodes = angular.isFunction(node.getElementsByClassName) ?
node.getElementsByClassName(NG_ANIMATE_CLASS_NAME) :
node.querySelectorAll('.' + NG_ANIMATE_CLASS_NAME);
forEach(nodes, function(element) {
element = angular.element(element);
var data = element.data(NG_ANIMATE_STATE);
if(data && data.active) {
forEach(data.active, function(runner) {
runner.cancel();
});
}
});
}
}
function cleanup(element, className) {
if(isMatchingElement(element, $rootElement)) {
if(!rootAnimateState.disabled) {
rootAnimateState.running = false;
rootAnimateState.structural = false;
}
} else if(className) {
var data = element.data(NG_ANIMATE_STATE) || {};
var removeAnimations = className === true;
if(!removeAnimations && data.active && data.active[className]) {
data.totalActive--;
delete data.active[className];
}
if(removeAnimations || !data.totalActive) {
element.removeClass(NG_ANIMATE_CLASS_NAME);
element.removeData(NG_ANIMATE_STATE);
}
}
}
function animationsDisabled(element, parentElement) {
if (rootAnimateState.disabled) return true;
if(isMatchingElement(element, $rootElement)) {
return rootAnimateState.disabled || rootAnimateState.running;
}
do {
//the element did not reach the root element which means that it
//is not apart of the DOM. Therefore there is no reason to do
//any animations on it
if(parentElement.length === 0) break;
var isRoot = isMatchingElement(parentElement, $rootElement);
var state = isRoot ? rootAnimateState : parentElement.data(NG_ANIMATE_STATE);
var result = state && (!!state.disabled || state.running || state.totalActive > 0);
if(isRoot || result) {
return result;
}
if(isRoot) return true;
}
while(parentElement = parentElement.parent());
return true;
}
}]);
$animateProvider.register('', ['$window', '$sniffer', '$timeout', '$$animateReflow',
function($window, $sniffer, $timeout, $$animateReflow) {
// Detect proper transitionend/animationend event names.
var CSS_PREFIX = '', TRANSITION_PROP, TRANSITIONEND_EVENT, ANIMATION_PROP, ANIMATIONEND_EVENT;
// If unprefixed events are not supported but webkit-prefixed are, use the latter.
// Otherwise, just use W3C names, browsers not supporting them at all will just ignore them.
// Note: Chrome implements `window.onwebkitanimationend` and doesn't implement `window.onanimationend`
// but at the same time dispatches the `animationend` event and not `webkitAnimationEnd`.
// Register both events in case `window.onanimationend` is not supported because of that,
// do the same for `transitionend` as Safari is likely to exhibit similar behavior.
// Also, the only modern browser that uses vendor prefixes for transitions/keyframes is webkit
// therefore there is no reason to test anymore for other vendor prefixes: http://caniuse.com/#search=transition
if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) {
CSS_PREFIX = '-webkit-';
TRANSITION_PROP = 'WebkitTransition';
TRANSITIONEND_EVENT = 'webkitTransitionEnd transitionend';
} else {
TRANSITION_PROP = 'transition';
TRANSITIONEND_EVENT = 'transitionend';
}
if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) {
CSS_PREFIX = '-webkit-';
ANIMATION_PROP = 'WebkitAnimation';
ANIMATIONEND_EVENT = 'webkitAnimationEnd animationend';
} else {
ANIMATION_PROP = 'animation';
ANIMATIONEND_EVENT = 'animationend';
}
var DURATION_KEY = 'Duration';
var PROPERTY_KEY = 'Property';
var DELAY_KEY = 'Delay';
var ANIMATION_ITERATION_COUNT_KEY = 'IterationCount';
var NG_ANIMATE_PARENT_KEY = '$$ngAnimateKey';
var NG_ANIMATE_CSS_DATA_KEY = '$$ngAnimateCSS3Data';
var NG_ANIMATE_BLOCK_CLASS_NAME = 'ng-animate-block-transitions';
var ELAPSED_TIME_MAX_DECIMAL_PLACES = 3;
var CLOSING_TIME_BUFFER = 1.5;
var ONE_SECOND = 1000;
var lookupCache = {};
var parentCounter = 0;
var animationReflowQueue = [];
var cancelAnimationReflow;
function afterReflow(element, callback) {
if(cancelAnimationReflow) {
cancelAnimationReflow();
}
animationReflowQueue.push(callback);
cancelAnimationReflow = $$animateReflow(function() {
forEach(animationReflowQueue, function(fn) {
fn();
});
animationReflowQueue = [];
cancelAnimationReflow = null;
lookupCache = {};
});
}
var closingTimer = null;
var closingTimestamp = 0;
var animationElementQueue = [];
function animationCloseHandler(element, totalTime) {
var node = extractElementNode(element);
element = angular.element(node);
//this item will be garbage collected by the closing
//animation timeout
animationElementQueue.push(element);
//but it may not need to cancel out the existing timeout
//if the timestamp is less than the previous one
var futureTimestamp = Date.now() + (totalTime * 1000);
if(futureTimestamp <= closingTimestamp) {
return;
}
$timeout.cancel(closingTimer);
closingTimestamp = futureTimestamp;
closingTimer = $timeout(function() {
closeAllAnimations(animationElementQueue);
animationElementQueue = [];
}, totalTime, false);
}
function closeAllAnimations(elements) {
forEach(elements, function(element) {
var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);
if(elementData) {
(elementData.closeAnimationFn || noop)();
}
});
}
function getElementAnimationDetails(element, cacheKey) {
var data = cacheKey ? lookupCache[cacheKey] : null;
if(!data) {
var transitionDuration = 0;
var transitionDelay = 0;
var animationDuration = 0;
var animationDelay = 0;
var transitionDelayStyle;
var animationDelayStyle;
var transitionDurationStyle;
var transitionPropertyStyle;
//we want all the styles defined before and after
forEach(element, function(element) {
if (element.nodeType == ELEMENT_NODE) {
var elementStyles = $window.getComputedStyle(element) || {};
transitionDurationStyle = elementStyles[TRANSITION_PROP + DURATION_KEY];
transitionDuration = Math.max(parseMaxTime(transitionDurationStyle), transitionDuration);
transitionPropertyStyle = elementStyles[TRANSITION_PROP + PROPERTY_KEY];
transitionDelayStyle = elementStyles[TRANSITION_PROP + DELAY_KEY];
transitionDelay = Math.max(parseMaxTime(transitionDelayStyle), transitionDelay);
animationDelayStyle = elementStyles[ANIMATION_PROP + DELAY_KEY];
animationDelay = Math.max(parseMaxTime(animationDelayStyle), animationDelay);
var aDuration = parseMaxTime(elementStyles[ANIMATION_PROP + DURATION_KEY]);
if(aDuration > 0) {
aDuration *= parseInt(elementStyles[ANIMATION_PROP + ANIMATION_ITERATION_COUNT_KEY], 10) || 1;
}
animationDuration = Math.max(aDuration, animationDuration);
}
});
data = {
total : 0,
transitionPropertyStyle: transitionPropertyStyle,
transitionDurationStyle: transitionDurationStyle,
transitionDelayStyle: transitionDelayStyle,
transitionDelay: transitionDelay,
transitionDuration: transitionDuration,
animationDelayStyle: animationDelayStyle,
animationDelay: animationDelay,
animationDuration: animationDuration
};
if(cacheKey) {
lookupCache[cacheKey] = data;
}
}
return data;
}
function parseMaxTime(str) {
var maxValue = 0;
var values = angular.isString(str) ?
str.split(/\s*,\s*/) :
[];
forEach(values, function(value) {
maxValue = Math.max(parseFloat(value) || 0, maxValue);
});
return maxValue;
}
function getCacheKey(element) {
var parentElement = element.parent();
var parentID = parentElement.data(NG_ANIMATE_PARENT_KEY);
if(!parentID) {
parentElement.data(NG_ANIMATE_PARENT_KEY, ++parentCounter);
parentID = parentCounter;
}
return parentID + '-' + extractElementNode(element).className;
}
function animateSetup(animationEvent, element, className, calculationDecorator) {
var cacheKey = getCacheKey(element);
var eventCacheKey = cacheKey + ' ' + className;
var itemIndex = lookupCache[eventCacheKey] ? ++lookupCache[eventCacheKey].total : 0;
var stagger = {};
if(itemIndex > 0) {
var staggerClassName = className + '-stagger';
var staggerCacheKey = cacheKey + ' ' + staggerClassName;
var applyClasses = !lookupCache[staggerCacheKey];
applyClasses && element.addClass(staggerClassName);
stagger = getElementAnimationDetails(element, staggerCacheKey);
applyClasses && element.removeClass(staggerClassName);
}
/* the animation itself may need to add/remove special CSS classes
* before calculating the anmation styles */
calculationDecorator = calculationDecorator ||
function(fn) { return fn(); };
element.addClass(className);
var formerData = element.data(NG_ANIMATE_CSS_DATA_KEY) || {};
var timings = calculationDecorator(function() {
return getElementAnimationDetails(element, eventCacheKey);
});
var transitionDuration = timings.transitionDuration;
var animationDuration = timings.animationDuration;
if(transitionDuration === 0 && animationDuration === 0) {
element.removeClass(className);
return false;
}
element.data(NG_ANIMATE_CSS_DATA_KEY, {
running : formerData.running || 0,
itemIndex : itemIndex,
stagger : stagger,
timings : timings,
closeAnimationFn : noop
});
//temporarily disable the transition so that the enter styles
//don't animate twice (this is here to avoid a bug in Chrome/FF).
var isCurrentlyAnimating = formerData.running > 0 || animationEvent == 'setClass';
if(transitionDuration > 0) {
blockTransitions(element, className, isCurrentlyAnimating);
}
//staggering keyframe animations work by adjusting the `animation-delay` CSS property
//on the given element, however, the delay value can only calculated after the reflow
//since by that time $animate knows how many elements are being animated. Therefore,
//until the reflow occurs the element needs to be blocked (where the keyframe animation
//is set to `none 0s`). This blocking mechanism should only be set for when a stagger
//animation is detected and when the element item index is greater than 0.
if(animationDuration > 0 && stagger.animationDelay > 0 && stagger.animationDuration === 0) {
blockKeyframeAnimations(element);
}
return true;
}
function isStructuralAnimation(className) {
return className == 'ng-enter' || className == 'ng-move' || className == 'ng-leave';
}
function blockTransitions(element, className, isAnimating) {
if(isStructuralAnimation(className) || !isAnimating) {
extractElementNode(element).style[TRANSITION_PROP + PROPERTY_KEY] = 'none';
} else {
element.addClass(NG_ANIMATE_BLOCK_CLASS_NAME);
}
}
function blockKeyframeAnimations(element) {
extractElementNode(element).style[ANIMATION_PROP] = 'none 0s';
}
function unblockTransitions(element, className) {
var prop = TRANSITION_PROP + PROPERTY_KEY;
var node = extractElementNode(element);
if(node.style[prop] && node.style[prop].length > 0) {
node.style[prop] = '';
}
element.removeClass(NG_ANIMATE_BLOCK_CLASS_NAME);
}
function unblockKeyframeAnimations(element) {
var prop = ANIMATION_PROP;
var node = extractElementNode(element);
if(node.style[prop] && node.style[prop].length > 0) {
node.style[prop] = '';
}
}
function animateRun(animationEvent, element, className, activeAnimationComplete) {
var node = extractElementNode(element);
var elementData = element.data(NG_ANIMATE_CSS_DATA_KEY);
if(node.className.indexOf(className) == -1 || !elementData) {
activeAnimationComplete();
return;
}
var activeClassName = '';
forEach(className.split(' '), function(klass, i) {
activeClassName += (i > 0 ? ' ' : '') + klass + '-active';
});
var stagger = elementData.stagger;
var timings = elementData.timings;
var itemIndex = elementData.itemIndex;
var maxDuration = Math.max(timings.transitionDuration, timings.animationDuration);
var maxDelay = Math.max(timings.transitionDelay, timings.animationDelay);
var maxDelayTime = maxDelay * ONE_SECOND;
var startTime = Date.now();
var css3AnimationEvents = ANIMATIONEND_EVENT + ' ' + TRANSITIONEND_EVENT;
var style = '', appliedStyles = [];
if(timings.transitionDuration > 0) {
var propertyStyle = timings.transitionPropertyStyle;
if(propertyStyle.indexOf('all') == -1) {
style += CSS_PREFIX + 'transition-property: ' + propertyStyle + ';';
style += CSS_PREFIX + 'transition-duration: ' + timings.transitionDurationStyle + ';';
appliedStyles.push(CSS_PREFIX + 'transition-property');
appliedStyles.push(CSS_PREFIX + 'transition-duration');
}
}
if(itemIndex > 0) {
if(stagger.transitionDelay > 0 && stagger.transitionDuration === 0) {
var delayStyle = timings.transitionDelayStyle;
style += CSS_PREFIX + 'transition-delay: ' +
prepareStaggerDelay(delayStyle, stagger.transitionDelay, itemIndex) + '; ';
appliedStyles.push(CSS_PREFIX + 'transition-delay');
}
if(stagger.animationDelay > 0 && stagger.animationDuration === 0) {
style += CSS_PREFIX + 'animation-delay: ' +
prepareStaggerDelay(timings.animationDelayStyle, stagger.animationDelay, itemIndex) + '; ';
appliedStyles.push(CSS_PREFIX + 'animation-delay');
}
}
if(appliedStyles.length > 0) {
//the element being animated may sometimes contain comment nodes in
//the jqLite object, so we're safe to use a single variable to house
//the styles since there is always only one element being animated
var oldStyle = node.getAttribute('style') || '';
node.setAttribute('style', oldStyle + ' ' + style);
}
element.on(css3AnimationEvents, onAnimationProgress);
element.addClass(activeClassName);
elementData.closeAnimationFn = function() {
onEnd();
activeAnimationComplete();
};
var staggerTime = itemIndex * (Math.max(stagger.animationDelay, stagger.transitionDelay) || 0);
var animationTime = (maxDelay + maxDuration) * CLOSING_TIME_BUFFER;
var totalTime = (staggerTime + animationTime) * ONE_SECOND;
elementData.running++;
animationCloseHandler(element, totalTime);
return onEnd;
// This will automatically be called by $animate so
// there is no need to attach this internally to the
// timeout done method.
function onEnd(cancelled) {
element.off(css3AnimationEvents, onAnimationProgress);
element.removeClass(activeClassName);
animateClose(element, className);
var node = extractElementNode(element);
for (var i in appliedStyles) {
node.style.removeProperty(appliedStyles[i]);
}
}
function onAnimationProgress(event) {
event.stopPropagation();
var ev = event.originalEvent || event;
var timeStamp = ev.$manualTimeStamp || ev.timeStamp || Date.now();
/* Firefox (or possibly just Gecko) likes to not round values up
* when a ms measurement is used for the animation */
var elapsedTime = parseFloat(ev.elapsedTime.toFixed(ELAPSED_TIME_MAX_DECIMAL_PLACES));
/* $manualTimeStamp is a mocked timeStamp value which is set
* within browserTrigger(). This is only here so that tests can
* mock animations properly. Real events fallback to event.timeStamp,
* or, if they don't, then a timeStamp is automatically created for them.
* We're checking to see if the timeStamp surpasses the expected delay,
* but we're using elapsedTime instead of the timeStamp on the 2nd
* pre-condition since animations sometimes close off early */
if(Math.max(timeStamp - startTime, 0) >= maxDelayTime && elapsedTime >= maxDuration) {
activeAnimationComplete();
}
}
}
function prepareStaggerDelay(delayStyle, staggerDelay, index) {
var style = '';
forEach(delayStyle.split(','), function(val, i) {
style += (i > 0 ? ',' : '') +
(index * staggerDelay + parseInt(val, 10)) + 's';
});
return style;
}
function animateBefore(animationEvent, element, className, calculationDecorator) {
if(animateSetup(animationEvent, element, className, calculationDecorator)) {
return function(cancelled) {
cancelled && animateClose(element, className);
};
}
}
function animateAfter(animationEvent, element, className, afterAnimationComplete) {
if(element.data(NG_ANIMATE_CSS_DATA_KEY)) {
return animateRun(animationEvent, element, className, afterAnimationComplete);
} else {
animateClose(element, className);
afterAnimationComplete();
}
}
function animate(animationEvent, element, className, animationComplete) {
//If the animateSetup function doesn't bother returning a
//cancellation function then it means that there is no animation
//to perform at all
var preReflowCancellation = animateBefore(animationEvent, element, className);
if(!preReflowCancellation) {
animationComplete();
return;
}
//There are two cancellation functions: one is before the first
//reflow animation and the second is during the active state
//animation. The first function will take care of removing the
//data from the element which will not make the 2nd animation
//happen in the first place
var cancel = preReflowCancellation;
afterReflow(element, function() {
unblockTransitions(element, className);
unblockKeyframeAnimations(element);
//once the reflow is complete then we point cancel to
//the new cancellation function which will remove all of the
//animation properties from the active animation
cancel = animateAfter(animationEvent, element, className, animationComplete);
});
return function(cancelled) {
(cancel || noop)(cancelled);
};
}
function animateClose(element, className) {
element.removeClass(className);
var data = element.data(NG_ANIMATE_CSS_DATA_KEY);
if(data) {
if(data.running) {
data.running--;
}
if(!data.running || data.running === 0) {
element.removeData(NG_ANIMATE_CSS_DATA_KEY);
}
}
}
return {
enter : function(element, animationCompleted) {
return animate('enter', element, 'ng-enter', animationCompleted);
},
leave : function(element, animationCompleted) {
return animate('leave', element, 'ng-leave', animationCompleted);
},
move : function(element, animationCompleted) {
return animate('move', element, 'ng-move', animationCompleted);
},
beforeSetClass : function(element, add, remove, animationCompleted) {
var className = suffixClasses(remove, '-remove') + ' ' +
suffixClasses(add, '-add');
var cancellationMethod = animateBefore('setClass', element, className, function(fn) {
/* when classes are removed from an element then the transition style
* that is applied is the transition defined on the element without the
* CSS class being there. This is how CSS3 functions outside of ngAnimate.
* http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */
var klass = element.attr('class');
element.removeClass(remove);
element.addClass(add);
var timings = fn();
element.attr('class', klass);
return timings;
});
if(cancellationMethod) {
afterReflow(element, function() {
unblockTransitions(element, className);
unblockKeyframeAnimations(element);
animationCompleted();
});
return cancellationMethod;
}
animationCompleted();
},
beforeAddClass : function(element, className, animationCompleted) {
var cancellationMethod = animateBefore('addClass', element, suffixClasses(className, '-add'), function(fn) {
/* when a CSS class is added to an element then the transition style that
* is applied is the transition defined on the element when the CSS class
* is added at the time of the animation. This is how CSS3 functions
* outside of ngAnimate. */
element.addClass(className);
var timings = fn();
element.removeClass(className);
return timings;
});
if(cancellationMethod) {
afterReflow(element, function() {
unblockTransitions(element, className);
unblockKeyframeAnimations(element);
animationCompleted();
});
return cancellationMethod;
}
animationCompleted();
},
setClass : function(element, add, remove, animationCompleted) {
remove = suffixClasses(remove, '-remove');
add = suffixClasses(add, '-add');
var className = remove + ' ' + add;
return animateAfter('setClass', element, className, animationCompleted);
},
addClass : function(element, className, animationCompleted) {
return animateAfter('addClass', element, suffixClasses(className, '-add'), animationCompleted);
},
beforeRemoveClass : function(element, className, animationCompleted) {
var cancellationMethod = animateBefore('removeClass', element, suffixClasses(className, '-remove'), function(fn) {
/* when classes are removed from an element then the transition style
* that is applied is the transition defined on the element without the
* CSS class being there. This is how CSS3 functions outside of ngAnimate.
* http://plnkr.co/edit/j8OzgTNxHTb4n3zLyjGW?p=preview */
var klass = element.attr('class');
element.removeClass(className);
var timings = fn();
element.attr('class', klass);
return timings;
});
if(cancellationMethod) {
afterReflow(element, function() {
unblockTransitions(element, className);
unblockKeyframeAnimations(element);
animationCompleted();
});
return cancellationMethod;
}
animationCompleted();
},
removeClass : function(element, className, animationCompleted) {
return animateAfter('removeClass', element, suffixClasses(className, '-remove'), animationCompleted);
}
};
function suffixClasses(classes, suffix) {
var className = '';
classes = angular.isArray(classes) ? classes : classes.split(/\s+/);
forEach(classes, function(klass, i) {
if(klass && klass.length > 0) {
className += (i > 0 ? ' ' : '') + klass + suffix;
}
});
return className;
}
}]);
}]);
})(window, window.angular);
|
Java
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 3: Perfectly Spherical Houses in a Vacuum ---
Santa is delivering presents to an infinite two-dimensional grid of houses.
He begins by delivering a present to the house at his starting location, and
then an elf at the North Pole calls him via radio and tells him where to move
next. Moves are always exactly one house to the north (^), south (v), east (>),
or west (<). After each move, he delivers another present to the house at his
new location.
However, the elf back at the north pole has had a little too much eggnog, and
so his directions are a little off, and Santa ends up visiting some houses more
than once. How many houses receive at least one present?
For example:
- > delivers presents to 2 houses: one at the starting location, and one to the
east.
- ^>v< delivers presents to 4 houses in a square, including twice to the
house at his starting/ending location.
- ^v^v^v^v^v delivers a bunch of presents
to some very lucky children at only 2 houses.
--- Part Two ---
The next year, to speed up the process, Santa creates a robot version of
himself, Robo-Santa, to deliver presents with him.
Santa and Robo-Santa start at the same location (delivering two presents to the
same starting house), then take turns moving based on instructions from the
elf, who is eggnoggedly reading from the same script as the previous year.
This year, how many houses receive at least one present?
For example:
- ^v delivers presents to 3 houses, because Santa goes north, and then Robo-Santa
goes south.
- ^>v< now delivers presents to 3 houses, and Santa and Robo-Santa
end up back where they started.
- ^v^v^v^v^v now delivers presents to 11 houses,
with Santa going one direction and Robo-Santa going the other.
"""
import sys
import click
def update_point(move, point):
"""Returns new point representing position after move"""
moves = {
'^': (0, -1),
'<': (-1, 0),
'v': (0, 1),
'>': (1, 0),
}
return (point[0]+moves.get(move, (0, 0))[0],
point[1]+moves.get(move, (0, 0))[1])
def map_single_delivery(text):
point = (0, 0)
points = set({point})
for move in text:
point = update_point(move, point)
points.add(point)
return points
def number_of_houses_covered(text, robo_santa=False):
return len(map_single_delivery(text)) if not robo_santa else \
len(map_multiple_deliveries(text))
def split_directions(directions):
lists = ('', '')
try:
lists = directions[0::2], directions[1::2]
except IndexError:
pass
return lists
def map_multiple_deliveries(text):
directions = split_directions(text)
points = map_single_delivery(directions[0])
return points.union(map_single_delivery(directions[1]))
def calculate_solution_1(text):
return number_of_houses_covered(text)
def calculate_solution_2(text):
return number_of_houses_covered(text, robo_santa=True)
@click.command()
@click.option('--source_file', default='data/03.txt',
help='source data file for problem')
def main(source_file):
"""Simple solution to adventofcode problem 3."""
data = ''
with open(source_file) as source:
data = source.read()
print('Santa gave at least one present to {} houses.'.format(
number_of_houses_covered(data)))
if __name__ == "__main__":
sys.exit(main())
|
Java
|
/**
* @file
* @brief test for access of http://embox.googlecode.com/files/ext2_users.img
*
* @author Anton Kozlov
* @date 18.02.2013
*/
#include <stdint.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <security/smac/smac.h>
#include <fs/vfs.h>
#include <fs/fsop.h>
#include <fs/flags.h>
#include <kernel/task.h>
#include <sys/xattr.h>
#include <embox/test.h>
#include <kernel/task/resource/security.h>
EMBOX_TEST_SUITE("smac tests with classic modes allows all access");
TEST_SETUP_SUITE(setup_suite);
TEST_TEARDOWN(clear_id);
TEST_TEARDOWN_SUITE(teardown_suite);
#define FS_NAME "ext2"
#define FS_DEV "/dev/hda"
#define FS_DIR "/tmp"
#define FILE_H "/tmp/file_high"
#define FILE_L "/tmp/file_low"
#define HIGH "high_label"
#define LOW "low_label"
static const char *high_static = HIGH;
static const char *low_static = LOW;
static const char *smac_star = "*";
#define SMAC_BACKUP_LEN 1024
static char buf[SMAC_BACKUP_LEN];
static struct smac_env *backup;
static struct smac_env test_env = {
.n = 2,
.entries = {
{HIGH, LOW, FS_MAY_READ },
{LOW, HIGH, FS_MAY_WRITE},
},
};
static mode_t root_backup_mode;
static int setup_suite(void) {
int res;
if (0 != (res = smac_getenv(buf, SMAC_BACKUP_LEN, &backup))) {
return res;
}
if (0 != (res = smac_setenv(&test_env))) {
return res;
}
root_backup_mode = vfs_get_root()->mode;
vfs_get_root()->mode = S_IFDIR | 0777;
if ((res = mount(FS_DEV, FS_DIR, FS_NAME))) {
return res;
}
return 0;
}
static int teardown_suite(void) {
// int res;
vfs_get_root()->mode = root_backup_mode;
return smac_setenv(backup);
}
static int clear_id(void) {
struct smac_task *smac_task = (struct smac_task *) task_self_resource_security();
strcpy(smac_task->label, "smac_admin");
return 0;
}
TEST_CASE("Low subject shouldn't read high object") {
int fd;
smac_labelset(low_static);
test_assert_equal(-1, fd = open(FILE_H, O_RDWR));
test_assert_equal(EACCES, errno);
test_assert_equal(-1, fd = open(FILE_H, O_RDONLY));
test_assert_equal(EACCES, errno);
}
TEST_CASE("High subject shouldn't write low object") {
int fd;
smac_labelset(high_static);
test_assert_equal(-1, fd = open(FILE_L, O_RDWR));
test_assert_equal(EACCES, errno);
test_assert_equal(-1, fd = open(FILE_L, O_WRONLY));
test_assert_equal(EACCES, errno);
}
TEST_CASE("High subject should be able r/w high object") {
int fd;
smac_labelset(high_static);
test_assert_not_equal(-1, fd = open(FILE_H, O_RDWR));
close(fd);
}
TEST_CASE("Low subject should be able r/w low object") {
int fd;
smac_labelset(low_static);
test_assert_not_equal(-1, fd = open(FILE_L, O_RDWR));
close(fd);
}
TEST_CASE("High subject shouldn't be able change high object label") {
smac_labelset(high_static);
test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_equal(EACCES, errno);
}
TEST_CASE("Low subject shouldn't be able change high object label") {
smac_labelset(low_static);
test_assert_equal(-1, setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_equal(EACCES, errno);
}
TEST_CASE("smac admin should be able change high object label") {
smac_labelset(smac_admin);
test_assert_zero(setxattr(FILE_H, smac_xattrkey, smac_star,
strlen(smac_star), 0));
test_assert_zero(setxattr(FILE_H, smac_xattrkey, high_static,
strlen(high_static), 0));
}
|
Java
|
package adf.launcher.connect;
import adf.agent.office.OfficeAmbulance;
import adf.control.ControlAmbulance;
import adf.launcher.AbstractLoader;
import adf.launcher.ConfigKey;
import rescuecore2.components.ComponentConnectionException;
import rescuecore2.components.ComponentLauncher;
import rescuecore2.config.Config;
import rescuecore2.connection.ConnectionException;
public class ConnectorAmbulanceCentre implements Connector
{
@Override
public void connect(ComponentLauncher launcher, Config config, AbstractLoader loader)
{
int count = config.getIntValue(ConfigKey.KEY_AMBULANCE_CENTRE_COUNT, 0);
int connected = 0;
if (count == 0)
{
return;
}
/*
String classStr = config.getValue(ConfigKey.KEY_AMBULANCE_CENTRE_NAME);
if (classStr == null)
{
System.out.println("[ERROR] Cannot Load AmbulanceCentre Control !!");
return;
}
System.out.println("[START] Connect AmbulanceCentre (teamName:" + classStr + ")");
System.out.println("[INFO ] Load AmbulanceCentre (teamName:" + classStr + ")");
*/
try
{
if (loader.getControlAmbulance() == null)
{
System.out.println("[ERROR ] Cannot Load AmbulanceCentre Control !!");
return;
}
for (int i = 0; i != count; ++i)
{
ControlAmbulance controlAmbulance = loader.getControlAmbulance();
boolean isPrecompute = config.getBooleanValue(ConfigKey.KEY_PRECOMPUTE, false);
launcher.connect(new OfficeAmbulance(controlAmbulance, isPrecompute));
//System.out.println(name);
connected++;
}
}
catch (ComponentConnectionException | InterruptedException | ConnectionException e)
{
//e.printStackTrace();
System.out.println("[ERROR ] Cannot Load AmbulanceCentre Control !!");
}
System.out.println("[FINISH] Connect AmbulanceCentre (success:" + connected + ")");
}
}
|
Java
|
<div ui-content-for="title">
<span>Detectors</span>
</div>
<div class="scrollable">
<div class="scrollable-content" ui-scroll-bottom="bottomReached()">
<div class="list-group">
<a ng-repeat="detector in detectors" href=""" class="list-group-item">
{{detector.name}} <i class="fa fa-chevron-right pull-right" ng-hide="{{detector.filters}}"></i>
<ui-switch ng-click="toggle(detector)"
ng-model="isToggled(detector)"></ui-switch>
</a>
</div>
<div id="alert_msg">Did not find the services directory service! Please implement this!</div>
</div>
</div>
</div>
|
Java
|
class SwiProlog < Formula
desc "ISO/Edinburgh-style Prolog interpreter"
homepage "http://www.swi-prolog.org/"
url "http://www.swi-prolog.org/download/stable/src/swipl-7.4.2.tar.gz"
sha256 "7f17257da334bc1e7a35e9cf5cb8fca01d82f1ea406c7ace76e9062af8f0df8b"
bottle do
sha256 "a03a0bde74e00d2c40b0a7735d46383bef5200dca08077b637e67d99cc0cb1aa" => :high_sierra
sha256 "ba534d0cc2cceb366ef8d19c1f1bb41441930fc1416c0491cf4233ed170ca23f" => :sierra
sha256 "ad17932306bca2156e865b80697ccf7c497ff03f6da6d8cf37eb7c966b581ba8" => :el_capitan
sha256 "ff7f400d368f44da8372423df94000e7b4cb84780a5b53936ff414a993db299b" => :yosemite
end
devel do
url "http://www.swi-prolog.org/download/devel/src/swipl-7.7.1.tar.gz"
sha256 "fda2c8b6b606ff199ea8a6f019008aa8272b7c349cb9312ccd5944153509503a"
end
head do
url "https://github.com/SWI-Prolog/swipl-devel.git"
depends_on "autoconf" => :build
end
option "with-lite", "Disable all packages"
option "with-jpl", "Enable JPL (Java Prolog Bridge)"
option "with-xpce", "Enable XPCE (Prolog Native GUI Library)"
deprecated_option "lite" => "with-lite"
depends_on "pkg-config" => :build
depends_on "readline"
depends_on "gmp"
depends_on "openssl"
depends_on "libarchive" => :optional
if build.with? "xpce"
depends_on :x11
depends_on "jpeg"
end
def install
if build.with? "libarchive"
ENV["ARPREFIX"] = Formula["libarchive"].opt_prefix
else
ENV.append "DISABLE_PKGS", "archive"
end
args = ["--prefix=#{libexec}", "--mandir=#{man}"]
ENV.append "DISABLE_PKGS", "jpl" if build.without? "jpl"
ENV.append "DISABLE_PKGS", "xpce" if build.without? "xpce"
# SWI-Prolog's Makefiles don't add CPPFLAGS to the compile command, but do
# include CIFLAGS. Setting it here. Also, they clobber CFLAGS, so including
# the Homebrew-generated CFLAGS into COFLAGS here.
ENV["CIFLAGS"] = ENV.cppflags
ENV["COFLAGS"] = ENV.cflags
# Build the packages unless --with-lite option specified
args << "--with-world" if build.without? "lite"
# './prepare' prompts the user to build documentation
# (which requires other modules). '3' is the option
# to ignore documentation.
system "echo 3 | ./prepare" if build.head?
system "./configure", *args
system "make"
system "make", "install"
bin.write_exec_script Dir["#{libexec}/bin/*"]
end
test do
(testpath/"test.pl").write <<-EOS.undent
test :-
write('Homebrew').
EOS
assert_equal "Homebrew", shell_output("#{bin}/swipl -s #{testpath}/test.pl -g test -t halt")
end
end
|
Java
|
/******************************************************************************
* The MIT License
* Copyright (c) 2007 Novell Inc., www.novell.com
*
* 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.
*******************************************************************************/
// Authors:
// Thomas Wiest (twiest@novell.com)
// Rusty Howell (rhowell@novell.com)
//
// (C) Novell Inc.
using System;
using System.Collections.Generic;
using System.Text;
namespace System.Management.Internal
{
internal class CimTable
{
public CimTable()
{
throw new Exception("Not yet implemented");
}
}
}
|
Java
|
#
# Autogenerated by Thrift Compiler (0.8.0)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
require 5.6.0;
use strict;
use warnings;
use Thrift;
use EDAMUserStore::Types;
# HELPER FUNCTIONS AND STRUCTURES
package EDAMUserStore::UserStore_checkVersion_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_checkVersion_args->mk_accessors( qw( clientName edamVersionMajor edamVersionMinor ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{clientName} = undef;
$self->{edamVersionMajor} = 1;
$self->{edamVersionMinor} = 21;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{clientName}) {
$self->{clientName} = $vals->{clientName};
}
if (defined $vals->{edamVersionMajor}) {
$self->{edamVersionMajor} = $vals->{edamVersionMajor};
}
if (defined $vals->{edamVersionMinor}) {
$self->{edamVersionMinor} = $vals->{edamVersionMinor};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_checkVersion_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{clientName});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::I16) {
$xfer += $input->readI16(\$self->{edamVersionMajor});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^3$/ && do{ if ($ftype == TType::I16) {
$xfer += $input->readI16(\$self->{edamVersionMinor});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_checkVersion_args');
if (defined $self->{clientName}) {
$xfer += $output->writeFieldBegin('clientName', TType::STRING, 1);
$xfer += $output->writeString($self->{clientName});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{edamVersionMajor}) {
$xfer += $output->writeFieldBegin('edamVersionMajor', TType::I16, 2);
$xfer += $output->writeI16($self->{edamVersionMajor});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{edamVersionMinor}) {
$xfer += $output->writeFieldBegin('edamVersionMinor', TType::I16, 3);
$xfer += $output->writeI16($self->{edamVersionMinor});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_checkVersion_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_checkVersion_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_checkVersion_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::BOOL) {
$xfer += $input->readBool(\$self->{success});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_checkVersion_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::BOOL, 0);
$xfer += $output->writeBool($self->{success});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getBootstrapInfo_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getBootstrapInfo_args->mk_accessors( qw( locale ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{locale} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{locale}) {
$self->{locale} = $vals->{locale};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getBootstrapInfo_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{locale});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getBootstrapInfo_args');
if (defined $self->{locale}) {
$xfer += $output->writeFieldBegin('locale', TType::STRING, 1);
$xfer += $output->writeString($self->{locale});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getBootstrapInfo_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getBootstrapInfo_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getBootstrapInfo_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::BootstrapInfo();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getBootstrapInfo_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_authenticate_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_authenticate_args->mk_accessors( qw( username password consumerKey consumerSecret ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{username} = undef;
$self->{password} = undef;
$self->{consumerKey} = undef;
$self->{consumerSecret} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{username}) {
$self->{username} = $vals->{username};
}
if (defined $vals->{password}) {
$self->{password} = $vals->{password};
}
if (defined $vals->{consumerKey}) {
$self->{consumerKey} = $vals->{consumerKey};
}
if (defined $vals->{consumerSecret}) {
$self->{consumerSecret} = $vals->{consumerSecret};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_authenticate_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{username});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{password});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^3$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{consumerKey});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^4$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{consumerSecret});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_authenticate_args');
if (defined $self->{username}) {
$xfer += $output->writeFieldBegin('username', TType::STRING, 1);
$xfer += $output->writeString($self->{username});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{password}) {
$xfer += $output->writeFieldBegin('password', TType::STRING, 2);
$xfer += $output->writeString($self->{password});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{consumerKey}) {
$xfer += $output->writeFieldBegin('consumerKey', TType::STRING, 3);
$xfer += $output->writeString($self->{consumerKey});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{consumerSecret}) {
$xfer += $output->writeFieldBegin('consumerSecret', TType::STRING, 4);
$xfer += $output->writeString($self->{consumerSecret});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_authenticate_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_authenticate_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_authenticate_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::AuthenticationResult();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_authenticate_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_refreshAuthentication_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_refreshAuthentication_args->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_refreshAuthentication_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_refreshAuthentication_args');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_refreshAuthentication_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_refreshAuthentication_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_refreshAuthentication_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::AuthenticationResult();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_refreshAuthentication_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getUser_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getUser_args->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getUser_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getUser_args');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getUser_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getUser_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getUser_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMTypes::User();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getUser_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getPublicUserInfo_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getPublicUserInfo_args->mk_accessors( qw( username ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{username} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{username}) {
$self->{username} = $vals->{username};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getPublicUserInfo_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{username});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getPublicUserInfo_args');
if (defined $self->{username}) {
$xfer += $output->writeFieldBegin('username', TType::STRING, 1);
$xfer += $output->writeString($self->{username});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getPublicUserInfo_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getPublicUserInfo_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{notFoundException} = undef;
$self->{systemException} = undef;
$self->{userException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{notFoundException}) {
$self->{notFoundException} = $vals->{notFoundException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getPublicUserInfo_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::PublicUserInfo();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{notFoundException} = new EDAMErrors::EDAMNotFoundException();
$xfer += $self->{notFoundException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^3$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getPublicUserInfo_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{notFoundException}) {
$xfer += $output->writeFieldBegin('notFoundException', TType::STRUCT, 1);
$xfer += $self->{notFoundException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 3);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getPremiumInfo_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getPremiumInfo_args->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getPremiumInfo_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getPremiumInfo_args');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getPremiumInfo_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getPremiumInfo_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getPremiumInfo_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRUCT) {
$self->{success} = new EDAMUserStore::PremiumInfo();
$xfer += $self->{success}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getPremiumInfo_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRUCT, 0);
$xfer += $self->{success}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getNoteStoreUrl_args;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getNoteStoreUrl_args->mk_accessors( qw( authenticationToken ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{authenticationToken} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{authenticationToken}) {
$self->{authenticationToken} = $vals->{authenticationToken};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getNoteStoreUrl_args';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^1$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{authenticationToken});
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getNoteStoreUrl_args');
if (defined $self->{authenticationToken}) {
$xfer += $output->writeFieldBegin('authenticationToken', TType::STRING, 1);
$xfer += $output->writeString($self->{authenticationToken});
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStore_getNoteStoreUrl_result;
use base qw(Class::Accessor);
EDAMUserStore::UserStore_getNoteStoreUrl_result->mk_accessors( qw( success ) );
sub new {
my $classname = shift;
my $self = {};
my $vals = shift || {};
$self->{success} = undef;
$self->{userException} = undef;
$self->{systemException} = undef;
if (UNIVERSAL::isa($vals,'HASH')) {
if (defined $vals->{success}) {
$self->{success} = $vals->{success};
}
if (defined $vals->{userException}) {
$self->{userException} = $vals->{userException};
}
if (defined $vals->{systemException}) {
$self->{systemException} = $vals->{systemException};
}
}
return bless ($self, $classname);
}
sub getName {
return 'UserStore_getNoteStoreUrl_result';
}
sub read {
my ($self, $input) = @_;
my $xfer = 0;
my $fname;
my $ftype = 0;
my $fid = 0;
$xfer += $input->readStructBegin(\$fname);
while (1)
{
$xfer += $input->readFieldBegin(\$fname, \$ftype, \$fid);
if ($ftype == TType::STOP) {
last;
}
SWITCH: for($fid)
{
/^0$/ && do{ if ($ftype == TType::STRING) {
$xfer += $input->readString(\$self->{success});
} else {
$xfer += $input->skip($ftype);
}
last; };
/^1$/ && do{ if ($ftype == TType::STRUCT) {
$self->{userException} = new EDAMErrors::EDAMUserException();
$xfer += $self->{userException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
/^2$/ && do{ if ($ftype == TType::STRUCT) {
$self->{systemException} = new EDAMErrors::EDAMSystemException();
$xfer += $self->{systemException}->read($input);
} else {
$xfer += $input->skip($ftype);
}
last; };
$xfer += $input->skip($ftype);
}
$xfer += $input->readFieldEnd();
}
$xfer += $input->readStructEnd();
return $xfer;
}
sub write {
my ($self, $output) = @_;
my $xfer = 0;
$xfer += $output->writeStructBegin('UserStore_getNoteStoreUrl_result');
if (defined $self->{success}) {
$xfer += $output->writeFieldBegin('success', TType::STRING, 0);
$xfer += $output->writeString($self->{success});
$xfer += $output->writeFieldEnd();
}
if (defined $self->{userException}) {
$xfer += $output->writeFieldBegin('userException', TType::STRUCT, 1);
$xfer += $self->{userException}->write($output);
$xfer += $output->writeFieldEnd();
}
if (defined $self->{systemException}) {
$xfer += $output->writeFieldBegin('systemException', TType::STRUCT, 2);
$xfer += $self->{systemException}->write($output);
$xfer += $output->writeFieldEnd();
}
$xfer += $output->writeFieldStop();
$xfer += $output->writeStructEnd();
return $xfer;
}
package EDAMUserStore::UserStoreIf;
use strict;
sub checkVersion{
my $self = shift;
my $clientName = shift;
my $edamVersionMajor = shift;
my $edamVersionMinor = shift;
die 'implement interface';
}
sub getBootstrapInfo{
my $self = shift;
my $locale = shift;
die 'implement interface';
}
sub authenticate{
my $self = shift;
my $username = shift;
my $password = shift;
my $consumerKey = shift;
my $consumerSecret = shift;
die 'implement interface';
}
sub refreshAuthentication{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
sub getUser{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
sub getPublicUserInfo{
my $self = shift;
my $username = shift;
die 'implement interface';
}
sub getPremiumInfo{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
sub getNoteStoreUrl{
my $self = shift;
my $authenticationToken = shift;
die 'implement interface';
}
package EDAMUserStore::UserStoreRest;
use strict;
sub new {
my ($classname, $impl) = @_;
my $self ={ impl => $impl };
return bless($self,$classname);
}
sub checkVersion{
my ($self, $request) = @_;
my $clientName = ($request->{'clientName'}) ? $request->{'clientName'} : undef;
my $edamVersionMajor = ($request->{'edamVersionMajor'}) ? $request->{'edamVersionMajor'} : undef;
my $edamVersionMinor = ($request->{'edamVersionMinor'}) ? $request->{'edamVersionMinor'} : undef;
return $self->{impl}->checkVersion($clientName, $edamVersionMajor, $edamVersionMinor);
}
sub getBootstrapInfo{
my ($self, $request) = @_;
my $locale = ($request->{'locale'}) ? $request->{'locale'} : undef;
return $self->{impl}->getBootstrapInfo($locale);
}
sub authenticate{
my ($self, $request) = @_;
my $username = ($request->{'username'}) ? $request->{'username'} : undef;
my $password = ($request->{'password'}) ? $request->{'password'} : undef;
my $consumerKey = ($request->{'consumerKey'}) ? $request->{'consumerKey'} : undef;
my $consumerSecret = ($request->{'consumerSecret'}) ? $request->{'consumerSecret'} : undef;
return $self->{impl}->authenticate($username, $password, $consumerKey, $consumerSecret);
}
sub refreshAuthentication{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->refreshAuthentication($authenticationToken);
}
sub getUser{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->getUser($authenticationToken);
}
sub getPublicUserInfo{
my ($self, $request) = @_;
my $username = ($request->{'username'}) ? $request->{'username'} : undef;
return $self->{impl}->getPublicUserInfo($username);
}
sub getPremiumInfo{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->getPremiumInfo($authenticationToken);
}
sub getNoteStoreUrl{
my ($self, $request) = @_;
my $authenticationToken = ($request->{'authenticationToken'}) ? $request->{'authenticationToken'} : undef;
return $self->{impl}->getNoteStoreUrl($authenticationToken);
}
package EDAMUserStore::UserStoreClient;
use base qw(EDAMUserStore::UserStoreIf);
sub new {
my ($classname, $input, $output) = @_;
my $self = {};
$self->{input} = $input;
$self->{output} = defined $output ? $output : $input;
$self->{seqid} = 0;
return bless($self,$classname);
}
sub checkVersion{
my $self = shift;
my $clientName = shift;
my $edamVersionMajor = shift;
my $edamVersionMinor = shift;
$self->send_checkVersion($clientName, $edamVersionMajor, $edamVersionMinor);
return $self->recv_checkVersion();
}
sub send_checkVersion{
my $self = shift;
my $clientName = shift;
my $edamVersionMajor = shift;
my $edamVersionMinor = shift;
$self->{output}->writeMessageBegin('checkVersion', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_checkVersion_args();
$args->{clientName} = $clientName;
$args->{edamVersionMajor} = $edamVersionMajor;
$args->{edamVersionMinor} = $edamVersionMinor;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_checkVersion{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_checkVersion_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
die "checkVersion failed: unknown result";
}
sub getBootstrapInfo{
my $self = shift;
my $locale = shift;
$self->send_getBootstrapInfo($locale);
return $self->recv_getBootstrapInfo();
}
sub send_getBootstrapInfo{
my $self = shift;
my $locale = shift;
$self->{output}->writeMessageBegin('getBootstrapInfo', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_getBootstrapInfo_args();
$args->{locale} = $locale;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getBootstrapInfo{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_getBootstrapInfo_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
die "getBootstrapInfo failed: unknown result";
}
sub authenticate{
my $self = shift;
my $username = shift;
my $password = shift;
my $consumerKey = shift;
my $consumerSecret = shift;
$self->send_authenticate($username, $password, $consumerKey, $consumerSecret);
return $self->recv_authenticate();
}
sub send_authenticate{
my $self = shift;
my $username = shift;
my $password = shift;
my $consumerKey = shift;
my $consumerSecret = shift;
$self->{output}->writeMessageBegin('authenticate', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_authenticate_args();
$args->{username} = $username;
$args->{password} = $password;
$args->{consumerKey} = $consumerKey;
$args->{consumerSecret} = $consumerSecret;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_authenticate{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_authenticate_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "authenticate failed: unknown result";
}
sub refreshAuthentication{
my $self = shift;
my $authenticationToken = shift;
$self->send_refreshAuthentication($authenticationToken);
return $self->recv_refreshAuthentication();
}
sub send_refreshAuthentication{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('refreshAuthentication', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_refreshAuthentication_args();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_refreshAuthentication{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_refreshAuthentication_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "refreshAuthentication failed: unknown result";
}
sub getUser{
my $self = shift;
my $authenticationToken = shift;
$self->send_getUser($authenticationToken);
return $self->recv_getUser();
}
sub send_getUser{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('getUser', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_getUser_args();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getUser{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_getUser_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "getUser failed: unknown result";
}
sub getPublicUserInfo{
my $self = shift;
my $username = shift;
$self->send_getPublicUserInfo($username);
return $self->recv_getPublicUserInfo();
}
sub send_getPublicUserInfo{
my $self = shift;
my $username = shift;
$self->{output}->writeMessageBegin('getPublicUserInfo', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_getPublicUserInfo_args();
$args->{username} = $username;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getPublicUserInfo{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_getPublicUserInfo_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{notFoundException}) {
die $result->{notFoundException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
if (defined $result->{userException}) {
die $result->{userException};
}
die "getPublicUserInfo failed: unknown result";
}
sub getPremiumInfo{
my $self = shift;
my $authenticationToken = shift;
$self->send_getPremiumInfo($authenticationToken);
return $self->recv_getPremiumInfo();
}
sub send_getPremiumInfo{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('getPremiumInfo', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_getPremiumInfo_args();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getPremiumInfo{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_getPremiumInfo_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "getPremiumInfo failed: unknown result";
}
sub getNoteStoreUrl{
my $self = shift;
my $authenticationToken = shift;
$self->send_getNoteStoreUrl($authenticationToken);
return $self->recv_getNoteStoreUrl();
}
sub send_getNoteStoreUrl{
my $self = shift;
my $authenticationToken = shift;
$self->{output}->writeMessageBegin('getNoteStoreUrl', TMessageType::CALL, $self->{seqid});
my $args = new EDAMUserStore::UserStore_getNoteStoreUrl_args();
$args->{authenticationToken} = $authenticationToken;
$args->write($self->{output});
$self->{output}->writeMessageEnd();
$self->{output}->getTransport()->flush();
}
sub recv_getNoteStoreUrl{
my $self = shift;
my $rseqid = 0;
my $fname;
my $mtype = 0;
$self->{input}->readMessageBegin(\$fname, \$mtype, \$rseqid);
if ($mtype == TMessageType::EXCEPTION) {
my $x = new TApplicationException();
$x->read($self->{input});
$self->{input}->readMessageEnd();
die $x;
}
my $result = new EDAMUserStore::UserStore_getNoteStoreUrl_result();
$result->read($self->{input});
$self->{input}->readMessageEnd();
if (defined $result->{success} ) {
return $result->{success};
}
if (defined $result->{userException}) {
die $result->{userException};
}
if (defined $result->{systemException}) {
die $result->{systemException};
}
die "getNoteStoreUrl failed: unknown result";
}
package EDAMUserStore::UserStoreProcessor;
use strict;
sub new {
my ($classname, $handler) = @_;
my $self = {};
$self->{handler} = $handler;
return bless ($self, $classname);
}
sub process {
my ($self, $input, $output) = @_;
my $rseqid = 0;
my $fname = undef;
my $mtype = 0;
$input->readMessageBegin(\$fname, \$mtype, \$rseqid);
my $methodname = 'process_'.$fname;
if (!$self->can($methodname)) {
$input->skip(TType::STRUCT);
$input->readMessageEnd();
my $x = new TApplicationException('Function '.$fname.' not implemented.', TApplicationException::UNKNOWN_METHOD);
$output->writeMessageBegin($fname, TMessageType::EXCEPTION, $rseqid);
$x->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
return;
}
$self->$methodname($rseqid, $input, $output);
return 1;
}
sub process_checkVersion {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_checkVersion_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_checkVersion_result();
$result->{success} = $self->{handler}->checkVersion($args->clientName, $args->edamVersionMajor, $args->edamVersionMinor);
$output->writeMessageBegin('checkVersion', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_getBootstrapInfo {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_getBootstrapInfo_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_getBootstrapInfo_result();
$result->{success} = $self->{handler}->getBootstrapInfo($args->locale);
$output->writeMessageBegin('getBootstrapInfo', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_authenticate {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_authenticate_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_authenticate_result();
eval {
$result->{success} = $self->{handler}->authenticate($args->username, $args->password, $args->consumerKey, $args->consumerSecret);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('authenticate', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_refreshAuthentication {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_refreshAuthentication_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_refreshAuthentication_result();
eval {
$result->{success} = $self->{handler}->refreshAuthentication($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('refreshAuthentication', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_getUser {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_getUser_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_getUser_result();
eval {
$result->{success} = $self->{handler}->getUser($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('getUser', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_getPublicUserInfo {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_getPublicUserInfo_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_getPublicUserInfo_result();
eval {
$result->{success} = $self->{handler}->getPublicUserInfo($args->username);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMNotFoundException') ){
$result->{notFoundException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}
$output->writeMessageBegin('getPublicUserInfo', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_getPremiumInfo {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_getPremiumInfo_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_getPremiumInfo_result();
eval {
$result->{success} = $self->{handler}->getPremiumInfo($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('getPremiumInfo', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
sub process_getNoteStoreUrl {
my ($self, $seqid, $input, $output) = @_;
my $args = new EDAMUserStore::UserStore_getNoteStoreUrl_args();
$args->read($input);
$input->readMessageEnd();
my $result = new EDAMUserStore::UserStore_getNoteStoreUrl_result();
eval {
$result->{success} = $self->{handler}->getNoteStoreUrl($args->authenticationToken);
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMUserException') ){
$result->{userException} = $@;
}; if( UNIVERSAL::isa($@,'EDAMErrors::EDAMSystemException') ){
$result->{systemException} = $@;
}
$output->writeMessageBegin('getNoteStoreUrl', TMessageType::REPLY, $seqid);
$result->write($output);
$output->writeMessageEnd();
$output->getTransport()->flush();
}
1;
|
Java
|
// Copyright 2010 Google Inc. All Rights Reserved.
// Refactored from contributions of various authors in strings/strutil.cc
//
// This file contains string processing functions related to
// numeric values.
#define __STDC_FORMAT_MACROS 1
#include "strings/numbers.h"
#include <memory>
#include <cassert>
#include <ctype.h>
#include <errno.h>
#include <float.h> // for DBL_DIG and FLT_DIG
#include <math.h> // for HUGE_VAL
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits>
using std::numeric_limits;
#include <string>
using std::string;
#include "base/int128.h"
#include "base/integral_types.h"
#include "base/logging.h"
#include "strings/stringprintf.h"
#include "strings/strtoint.h"
#include "strings/ascii_ctype.h"
// Reads a <double> in *text, which may not be whitespace-initiated.
// *len is the length, or -1 if text is '\0'-terminated, which is more
// efficient. Sets *text to the end of the double, and val to the
// converted value, and the length of the double is subtracted from
// *len. <double> may also be a '?', in which case val will be
// unchanged. Returns true upon success. If initial_minus is
// non-NULL, then *initial_minus will indicate whether the first
// symbol seen was a '-', which will be ignored. Similarly, if
// final_period is non-NULL, then *final_period will indicate whether
// the last symbol seen was a '.', which will be ignored. This is
// useful in case that an initial '-' or final '.' would have another
// meaning (as a separator, e.g.).
static inline bool EatADouble(const char** text, int* len, bool allow_question,
double* val, bool* initial_minus,
bool* final_period) {
const char* pos = *text;
int rem = *len; // remaining length, or -1 if null-terminated
if (pos == NULL || rem == 0)
return false;
if (allow_question && (*pos == '?')) {
*text = pos + 1;
if (rem != -1)
*len = rem - 1;
return true;
}
if (initial_minus) {
if ((*initial_minus = (*pos == '-'))) { // Yes, we want assignment.
if (rem == 1)
return false;
++pos;
if (rem != -1)
--rem;
}
}
// a double has to begin one of these (we don't allow 'inf' or whitespace)
// this also serves as an optimization.
if (!strchr("-+.0123456789", *pos))
return false;
// strtod is evil in that the second param is a non-const char**
char* end_nonconst;
double retval;
if (rem == -1) {
retval = strtod(pos, &end_nonconst);
} else {
// not '\0'-terminated & no obvious terminator found. must copy.
std::unique_ptr<char[]> buf(new char[rem + 1]);
memcpy(buf.get(), pos, rem);
buf[rem] = '\0';
retval = strtod(buf.get(), &end_nonconst);
end_nonconst = const_cast<char*>(pos) + (end_nonconst - buf.get());
}
if (pos == end_nonconst)
return false;
if (final_period) {
*final_period = (end_nonconst[-1] == '.');
if (*final_period) {
--end_nonconst;
}
}
*text = end_nonconst;
*val = retval;
if (rem != -1)
*len = rem - (end_nonconst - pos);
return true;
}
// If update, consume one of acceptable_chars from string *text of
// length len and return that char, or '\0' otherwise. If len is -1,
// *text is null-terminated. If update is false, don't alter *text and
// *len. If null_ok, then update must be false, and, if text has no
// more chars, then return '\1' (arbitrary nonzero).
static inline char EatAChar(const char** text, int* len,
const char* acceptable_chars,
bool update, bool null_ok) {
assert(!(update && null_ok));
if ((*len == 0) || (**text == '\0'))
return (null_ok ? '\1' : '\0'); // if null_ok, we're in predicate mode.
if (strchr(acceptable_chars, **text)) {
char result = **text;
if (update) {
++(*text);
if (*len != -1)
--(*len);
}
return result;
}
return '\0'; // no match; no update
}
// Parse an expression in 'text' of the form: <comparator><double> or
// <double><sep><double> See full comments in header file.
bool ParseDoubleRange(const char* text, int len, const char** end,
double* from, double* to, bool* is_currency,
const DoubleRangeOptions& opts) {
const double from_default = opts.dont_modify_unbounded ? *from : -HUGE_VAL;
if (!opts.dont_modify_unbounded) {
*from = -HUGE_VAL;
*to = HUGE_VAL;
}
if (opts.allow_currency && (is_currency != NULL))
*is_currency = false;
assert(len >= -1);
assert(opts.separators && (*opts.separators != '\0'));
// these aren't valid separators
assert(strlen(opts.separators) ==
strcspn(opts.separators, "+0123456789eE$"));
assert(opts.num_required_bounds <= 2);
// Handle easier cases of comparators (<, >) first
if (opts.allow_comparators) {
char comparator = EatAChar(&text, &len, "<>", true, false);
if (comparator) {
double* dest = (comparator == '>') ? from : to;
EatAChar(&text, &len, "=", true, false);
if (opts.allow_currency && EatAChar(&text, &len, "$", true, false))
if (is_currency != NULL)
*is_currency = true;
if (!EatADouble(&text, &len, opts.allow_unbounded_markers, dest, NULL,
NULL))
return false;
*end = text;
return EatAChar(&text, &len, opts.acceptable_terminators, false,
opts.null_terminator_ok);
}
}
bool seen_dollar = (opts.allow_currency &&
EatAChar(&text, &len, "$", true, false));
// If we see a '-', two things could be happening: -<to> or
// <from>... where <from> is negative. Treat initial minus sign as a
// separator if '-' is a valid separator.
// Similarly, we prepare for the possibility of seeing a '.' at the
// end of the number, in case '.' (which really means '..') is a
// separator.
bool initial_minus_sign = false;
bool final_period = false;
bool* check_initial_minus = (strchr(opts.separators, '-') && !seen_dollar
&& (opts.num_required_bounds < 2)) ?
(&initial_minus_sign) : NULL;
bool* check_final_period = strchr(opts.separators, '.') ? (&final_period)
: NULL;
bool double_seen = EatADouble(&text, &len, opts.allow_unbounded_markers,
from, check_initial_minus, check_final_period);
// if 2 bounds required, must see a double (or '?' if allowed)
if ((opts.num_required_bounds == 2) && !double_seen) return false;
if (seen_dollar && !double_seen) {
--text;
if (len != -1)
++len;
seen_dollar = false;
}
// If we're here, we've read the first double and now expect a
// separator and another <double>.
char separator = EatAChar(&text, &len, opts.separators, true, false);
if (separator == '.') {
// seen one '.' as separator; must check for another; perhaps set seplen=2
if (EatAChar(&text, &len, ".", true, false)) {
if (final_period) {
// We may have three periods in a row. The first is part of the
// first number, the others are a separator. Policy: 234...567
// is "234." to "567", not "234" to ".567".
EatAChar(&text, &len, ".", true, false);
}
} else if (!EatAChar(&text, &len, opts.separators, true, false)) {
// just one '.' and no other separator; uneat the first '.' we saw
--text;
if (len != -1)
++len;
separator = '\0';
}
}
// By now, we've consumed whatever separator there may have been,
// and separator is true iff there was one.
if (!separator) {
if (final_period) // final period now considered part of first double
EatAChar(&text, &len, ".", true, false);
if (initial_minus_sign && double_seen) {
*to = *from;
*from = from_default;
} else if (opts.require_separator ||
(opts.num_required_bounds > 0 && !double_seen) ||
(opts.num_required_bounds > 1) ) {
return false;
}
} else {
if (initial_minus_sign && double_seen)
*from = -(*from);
// read second <double>
bool second_dollar_seen = (seen_dollar
|| (opts.allow_currency && !double_seen))
&& EatAChar(&text, &len, "$", true, false);
bool second_double_seen = EatADouble(
&text, &len, opts.allow_unbounded_markers, to, NULL, NULL);
if (opts.num_required_bounds > uint32(double_seen) + uint32(second_double_seen))
return false;
if (second_dollar_seen && !second_double_seen) {
--text;
if (len != -1)
++len;
second_dollar_seen = false;
}
seen_dollar = seen_dollar || second_dollar_seen;
}
if (seen_dollar && (is_currency != NULL))
*is_currency = true;
// We're done. But we have to check that the next char is a proper
// terminator.
*end = text;
char terminator = EatAChar(&text, &len, opts.acceptable_terminators, false,
opts.null_terminator_ok);
if (terminator == '.')
--(*end);
return terminator;
}
// ----------------------------------------------------------------------
// ConsumeStrayLeadingZeroes
// Eliminates all leading zeroes (unless the string itself is composed
// of nothing but zeroes, in which case one is kept: 0...0 becomes 0).
// --------------------------------------------------------------------
void ConsumeStrayLeadingZeroes(string *const str) {
const string::size_type len(str->size());
if (len > 1 && (*str)[0] == '0') {
const char
*const begin(str->c_str()),
*const end(begin + len),
*ptr(begin + 1);
while (ptr != end && *ptr == '0') {
++ptr;
}
string::size_type remove(ptr - begin);
DCHECK_GT(ptr, begin);
if (remove == len) {
--remove; // if they are all zero, leave one...
}
str->erase(0, remove);
}
}
// ----------------------------------------------------------------------
// ParseLeadingInt32Value()
// ParseLeadingUInt32Value()
// A simple parser for [u]int32 values. Returns the parsed value
// if a valid value is found; else returns deflt
// This cannot handle decimal numbers with leading 0s.
// --------------------------------------------------------------------
int32 ParseLeadingInt32Value(StringPiece str, int32 deflt) {
if (str.empty()) return deflt;
using std::numeric_limits;
char *error = NULL;
long value = strtol(str.data(), &error, 0);
// Limit long values to int32 min/max. Needed for lp64; no-op on 32 bits.
if (value > numeric_limits<int32>::max()) {
value = numeric_limits<int32>::max();
} else if (value < numeric_limits<int32>::min()) {
value = numeric_limits<int32>::min();
}
return (error == str.data()) ? deflt : value;
}
uint32 ParseLeadingUInt32Value(StringPiece str, uint32 deflt) {
using std::numeric_limits;
if (str.empty()) return deflt;
if (numeric_limits<unsigned long>::max() == numeric_limits<uint32>::max()) {
// When long is 32 bits, we can use strtoul.
char *error = NULL;
const uint32 value = strtoul(str.data(), &error, 0);
return (error == str.data()) ? deflt : value;
} else {
// When long is 64 bits, we must use strto64 and handle limits
// by hand. The reason we cannot use a 64-bit strtoul is that
// it would be impossible to differentiate "-2" (that should wrap
// around to the value UINT_MAX-1) from a string with ULONG_MAX-1
// (that should be pegged to UINT_MAX due to overflow).
char *error = NULL;
int64 value = strto64(str.data(), &error, 0);
if (value > numeric_limits<uint32>::max() ||
value < -static_cast<int64>(numeric_limits<uint32>::max())) {
value = numeric_limits<uint32>::max();
}
// Within these limits, truncation to 32 bits handles negatives correctly.
return (error == str.data()) ? deflt : value;
}
}
// ----------------------------------------------------------------------
// ParseLeadingDec32Value
// ParseLeadingUDec32Value
// A simple parser for [u]int32 values. Returns the parsed value
// if a valid value is found; else returns deflt
// The string passed in is treated as *10 based*.
// This can handle strings with leading 0s.
// --------------------------------------------------------------------
int32 ParseLeadingDec32Value(StringPiece str, int32 deflt) {
using std::numeric_limits;
char *error = NULL;
long value = strtol(str.data(), &error, 10);
// Limit long values to int32 min/max. Needed for lp64; no-op on 32 bits.
if (value > numeric_limits<int32>::max()) {
value = numeric_limits<int32>::max();
} else if (value < numeric_limits<int32>::min()) {
value = numeric_limits<int32>::min();
}
return (error == str.data()) ? deflt : value;
}
uint32 ParseLeadingUDec32Value(StringPiece str, uint32 deflt) {
using std::numeric_limits;
if (numeric_limits<unsigned long>::max() == numeric_limits<uint32>::max()) {
// When long is 32 bits, we can use strtoul.
char *error = NULL;
const uint32 value = strtoul(str.data(), &error, 10);
return (error == str.begin()) ? deflt : value;
} else {
// When long is 64 bits, we must use strto64 and handle limits
// by hand. The reason we cannot use a 64-bit strtoul is that
// it would be impossible to differentiate "-2" (that should wrap
// around to the value UINT_MAX-1) from a string with ULONG_MAX-1
// (that should be pegged to UINT_MAX due to overflow).
char *error = NULL;
int64 value = strto64(str.data(), &error, 10);
if (value > numeric_limits<uint32>::max() ||
value < -static_cast<int64>(numeric_limits<uint32>::max())) {
value = numeric_limits<uint32>::max();
}
// Within these limits, truncation to 32 bits handles negatives correctly.
return (error == str.data()) ? deflt : value;
}
}
// ----------------------------------------------------------------------
// ParseLeadingUInt64Value
// ParseLeadingInt64Value
// ParseLeadingHex64Value
// A simple parser for 64-bit values. Returns the parsed value if a
// valid integer is found; else returns deflt
// UInt64 and Int64 cannot handle decimal numbers with leading 0s.
// --------------------------------------------------------------------
uint64 ParseLeadingUInt64Value(StringPiece str, uint64 deflt) {
char *error = NULL;
const uint64 value = strtou64(str.data(), &error, 0);
return (error == str.data()) ? deflt : value;
}
int64 ParseLeadingInt64Value(StringPiece str, int64 deflt) {
char *error = NULL;
const int64 value = strto64(str.data(), &error, 0);
return (error == str.data()) ? deflt : value;
}
uint64 ParseLeadingHex64Value(StringPiece str, uint64 deflt) {
char *error = NULL;
const uint64 value = strtou64(str.data(), &error, 16);
return (error == str.data()) ? deflt : value;
}
// ----------------------------------------------------------------------
// ParseLeadingDec64Value
// ParseLeadingUDec64Value
// A simple parser for [u]int64 values. Returns the parsed value
// if a valid value is found; else returns deflt
// The string passed in is treated as *10 based*.
// This can handle strings with leading 0s.
// --------------------------------------------------------------------
int64 ParseLeadingDec64Value(StringPiece str, int64 deflt) {
char *error = NULL;
const int64 value = strto64(str.data(), &error, 10);
return (error == str.data()) ? deflt : value;
}
uint64 ParseLeadingUDec64Value(StringPiece str, uint64 deflt) {
char *error = NULL;
const uint64 value = strtou64(str.data(), &error, 10);
return (error == str.data()) ? deflt : value;
}
// ----------------------------------------------------------------------
// ParseLeadingDoubleValue()
// A simple parser for double values. Returns the parsed value
// if a valid value is found; else returns deflt
// --------------------------------------------------------------------
double ParseLeadingDoubleValue(const char *str, double deflt) {
char *error = NULL;
errno = 0;
const double value = strtod(str, &error);
if (errno != 0 || // overflow/underflow happened
error == str) { // no valid parse
return deflt;
} else {
return value;
}
}
// ----------------------------------------------------------------------
// ParseLeadingBoolValue()
// A recognizer of boolean string values. Returns the parsed value
// if a valid value is found; else returns deflt. This skips leading
// whitespace, is case insensitive, and recognizes these forms:
// 0/1, false/true, no/yes, n/y
// --------------------------------------------------------------------
bool ParseLeadingBoolValue(const char *str, bool deflt) {
static const int kMaxLen = 5;
char value[kMaxLen + 1];
// Skip whitespace
while (ascii_isspace(*str)) {
++str;
}
int len = 0;
for (; len <= kMaxLen && ascii_isalnum(*str); ++str)
value[len++] = ascii_tolower(*str);
if (len == 0 || len > kMaxLen)
return deflt;
value[len] = '\0';
switch (len) {
case 1:
if (value[0] == '0' || value[0] == 'n')
return false;
if (value[0] == '1' || value[0] == 'y')
return true;
break;
case 2:
if (!strcmp(value, "no"))
return false;
break;
case 3:
if (!strcmp(value, "yes"))
return true;
break;
case 4:
if (!strcmp(value, "true"))
return true;
break;
case 5:
if (!strcmp(value, "false"))
return false;
break;
}
return deflt;
}
// ----------------------------------------------------------------------
// FpToString()
// FloatToString()
// IntToString()
// Convert various types to their string representation, possibly padded
// with spaces, using snprintf format specifiers.
// ----------------------------------------------------------------------
string FpToString(Fprint fp) {
char buf[17];
snprintf(buf, sizeof(buf), "%016" PRIu64 "x", fp);
return string(buf);
}
namespace {
// Represents integer values of digits.
// Uses 36 to indicate an invalid character since we support
// bases up to 36.
static const int8 kAsciiToInt[256] = {
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, // 16 36s.
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
36, 36, 36, 36, 36, 36, 36,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 36, 36, 36, 36, 36,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36,
36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36 };
// Parse the sign and optional hex or oct prefix in range
// [*start_ptr, *end_ptr).
inline bool safe_parse_sign_and_base(const char** start_ptr /*inout*/,
const char** end_ptr /*inout*/,
int* base_ptr /*inout*/,
bool* negative_ptr /*output*/) {
const char* start = *start_ptr;
const char* end = *end_ptr;
int base = *base_ptr;
// Consume whitespace.
while (start < end && ascii_isspace(start[0])) {
++start;
}
while (start < end && ascii_isspace(end[-1])) {
--end;
}
if (start >= end) {
return false;
}
// Consume sign.
*negative_ptr = (start[0] == '-');
if (*negative_ptr || start[0] == '+') {
++start;
if (start >= end) {
return false;
}
}
// Consume base-dependent prefix.
// base 0: "0x" -> base 16, "0" -> base 8, default -> base 10
// base 16: "0x" -> base 16
// Also validate the base.
if (base == 0) {
if (end - start >= 2 && start[0] == '0' &&
(start[1] == 'x' || start[1] == 'X')) {
base = 16;
start += 2;
} else if (end - start >= 1 && start[0] == '0') {
base = 8;
start += 1;
} else {
base = 10;
}
} else if (base == 16) {
if (end - start >= 2 && start[0] == '0' &&
(start[1] == 'x' || start[1] == 'X')) {
start += 2;
}
} else if (base >= 2 && base <= 36) {
// okay
} else {
return false;
}
*start_ptr = start;
*end_ptr = end;
*base_ptr = base;
return true;
}
// Consume digits.
//
// The classic loop:
//
// for each digit
// value = value * base + digit
// value *= sign
//
// The classic loop needs overflow checking. It also fails on the most
// negative integer, -2147483648 in 32-bit two's complement representation.
//
// My improved loop:
//
// if (!negative)
// for each digit
// value = value * base
// value = value + digit
// else
// for each digit
// value = value * base
// value = value - digit
//
// Overflow checking becomes simple.
template<typename IntType>
inline bool safe_parse_positive_int(
const char* start, const char* end, int base, IntType* value_p) {
IntType value = 0;
const IntType vmax = std::numeric_limits<IntType>::max();
assert(vmax > 0);
// assert(vmax >= base);
const IntType vmax_over_base = vmax / base;
// loop over digits
// loop body is interleaved for perf, not readability
for (; start < end; ++start) {
unsigned char c = static_cast<unsigned char>(start[0]);
int digit = kAsciiToInt[c];
if (value > vmax_over_base) return false;
value *= base;
if (digit >= base) return false;
if (value > vmax - digit) return false;
value += digit;
}
*value_p = value;
return true;
}
template<typename IntType>
inline bool safe_parse_negative_int(
const char* start, const char* end, int base, IntType* value_p) {
IntType value = 0;
const IntType vmin = std::numeric_limits<IntType>::min();
assert(vmin < 0);
IntType vmin_over_base = vmin / base;
// 2003 c++ standard [expr.mul]
// "... the sign of the remainder is implementation-defined."
// Although (vmin/base)*base + vmin%base is always vmin.
// 2011 c++ standard tightens the spec but we cannot rely on it.
if (vmin % base > 0) {
vmin_over_base += 1;
}
// loop over digits
// loop body is interleaved for perf, not readability
for (; start < end; ++start) {
unsigned char c = static_cast<unsigned char>(start[0]);
int digit = kAsciiToInt[c];
if (value < vmin_over_base) return false;
value *= base;
if (digit >= base) return false;
if (value < vmin + digit) return false;
value -= digit;
}
*value_p = value;
return true;
}
// Input format based on POSIX.1-2008 strtol
// http://pubs.opengroup.org/onlinepubs/9699919799/functions/strtol.html
template<typename IntType>
bool safe_int_internal(const char* start, const char* end, int base,
IntType* value_p) {
bool negative;
if (!safe_parse_sign_and_base(&start, &end, &base, &negative)) {
return false;
}
if (!negative) {
return safe_parse_positive_int(start, end, base, value_p);
} else {
return safe_parse_negative_int(start, end, base, value_p);
}
}
template<typename IntType>
inline bool safe_uint_internal(const char* start, const char* end, int base,
IntType* value_p) {
bool negative;
if (!safe_parse_sign_and_base(&start, &end, &base, &negative) || negative) {
return false;
}
return safe_parse_positive_int(start, end, base, value_p);
}
} // anonymous namespace
bool safe_strto32_base(StringPiece str,
int32* v, int base) {
return safe_int_internal<int32>(str.begin(), str.end(), base, v);
}
bool safe_strto64_base(StringPiece str,
int64* v, int base) {
return safe_int_internal<int64>(str.begin(), str.end(), base, v);
}
bool safe_strto32(StringPiece str, int32* value) {
return safe_int_internal<int32>(str.begin(), str.end(), 10, value);
}
bool safe_strtou32(StringPiece str, uint32* value) {
return safe_uint_internal<uint32>(str.begin(), str.end(), 10, value);
}
bool safe_strto64(StringPiece str, int64* value) {
return safe_int_internal<int64>(str.begin(), str.end(), 10, value);
}
bool safe_strtou64(StringPiece str, uint64* value) {
return safe_uint_internal<uint64>(str.begin(), str.end(), 10, value);
}
bool safe_strtou32_base(StringPiece str,
uint32* value, int base) {
return safe_uint_internal<uint32>(str.begin(), str.end(), base, value);
}
bool safe_strtou64_base(StringPiece str,
uint64* value, int base) {
return safe_uint_internal<uint64>(str.begin(), str.end(), base, value);
}
// ----------------------------------------------------------------------
// u64tostr_base36()
// Converts unsigned number to string representation in base-36.
// --------------------------------------------------------------------
size_t u64tostr_base36(uint64 number, size_t buf_size, char* buffer) {
CHECK_GT(buf_size, 0);
CHECK(buffer);
static const char kAlphabet[] = "0123456789abcdefghijklmnopqrstuvwxyz";
buffer[buf_size - 1] = '\0';
size_t result_size = 1;
do {
if (buf_size == result_size) { // Ran out of space.
return 0;
}
int remainder = number % 36;
number /= 36;
buffer[buf_size - result_size - 1] = kAlphabet[remainder];
result_size++;
} while (number);
memmove(buffer, buffer + buf_size - result_size, result_size);
return result_size - 1;
}
bool safe_strtof(StringPiece str, float* value) {
char* endptr;
*value = strtof(str.data(), &endptr);
if (endptr != str.data()) {
while (endptr < str.end() && ascii_isspace(*endptr)) ++endptr;
}
// Ignore range errors from strtod/strtof.
// The values it returns on underflow and
// overflow are the right fallback in a
// robust setting.
return !str.empty() && endptr == str.end();
}
bool safe_strtod(StringPiece str, double* value) {
char* endptr;
*value = strtod(str.data(), &endptr);
if (endptr != str.data()) {
while (endptr < str.end() && ascii_isspace(*endptr)) ++endptr;
}
// Ignore range errors from strtod. The values it
// returns on underflow and overflow are the right
// fallback in a robust setting.
return !str.empty() && endptr == str.end();
}
uint64 atoi_kmgt(const char* s) {
char* endptr;
uint64 n = strtou64(s, &endptr, 10);
uint64 scale = 1;
char c = *endptr;
if (c != '\0') {
c = ascii_toupper(c);
switch (c) {
case 'K':
scale = GG_ULONGLONG(1) << 10;
break;
case 'M':
scale = GG_ULONGLONG(1) << 20;
break;
case 'G':
scale = GG_ULONGLONG(1) << 30;
break;
case 'T':
scale = GG_ULONGLONG(1) << 40;
break;
default:
LOG(FATAL) << "Invalid mnemonic: `" << c << "';"
<< " should be one of `K', `M', `G', and `T'.";
}
}
return n * scale;
}
// ----------------------------------------------------------------------
// FastIntToBuffer()
// FastInt64ToBuffer()
// FastHexToBuffer()
// FastHex64ToBuffer()
// FastHex32ToBuffer()
// FastTimeToBuffer()
// These are intended for speed. FastHexToBuffer() assumes the
// integer is non-negative. FastHexToBuffer() puts output in
// hex rather than decimal. FastTimeToBuffer() puts the output
// into RFC822 format. If time is 0, uses the current time.
//
// FastHex64ToBuffer() puts a 64-bit unsigned value in hex-format,
// padded to exactly 16 bytes (plus one byte for '\0')
//
// FastHex32ToBuffer() puts a 32-bit unsigned value in hex-format,
// padded to exactly 8 bytes (plus one byte for '\0')
//
// All functions take the output buffer as an arg. FastInt()
// uses at most 22 bytes, FastTime() uses exactly 30 bytes.
// They all return a pointer to the beginning of the output,
// which may not be the beginning of the input buffer. (Though
// for FastTimeToBuffer(), we guarantee that it is.)
// ----------------------------------------------------------------------
char *FastInt64ToBuffer(int64 i, char* buffer) {
FastInt64ToBufferLeft(i, buffer);
return buffer;
}
// Offset into buffer where FastInt32ToBuffer places the end of string
// null character. Also used by FastInt32ToBufferLeft
static const int kFastInt32ToBufferOffset = 11;
char *FastInt32ToBuffer(int32 i, char* buffer) {
FastInt32ToBufferLeft(i, buffer);
return buffer;
}
char *FastHexToBuffer(int i, char* buffer) {
CHECK_GE(i, 0) << "FastHexToBuffer() wants non-negative integers, not " << i;
static const char *hexdigits = "0123456789abcdef";
char *p = buffer + 21;
*p-- = '\0';
do {
*p-- = hexdigits[i & 15]; // mod by 16
i >>= 4; // divide by 16
} while (i > 0);
return p + 1;
}
char *InternalFastHexToBuffer(uint64 value, char* buffer, int num_byte) {
static const char *hexdigits = "0123456789abcdef";
buffer[num_byte] = '\0';
for (int i = num_byte - 1; i >= 0; i--) {
buffer[i] = hexdigits[value & 0xf];
value >>= 4;
}
return buffer;
}
char *FastHex64ToBuffer(uint64 value, char* buffer) {
return InternalFastHexToBuffer(value, buffer, 16);
}
char *FastHex32ToBuffer(uint32 value, char* buffer) {
return InternalFastHexToBuffer(value, buffer, 8);
}
const char two_ASCII_digits[100][2] = {
{'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'},
{'0', '5'}, {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'},
{'1', '0'}, {'1', '1'}, {'1', '2'}, {'1', '3'}, {'1', '4'},
{'1', '5'}, {'1', '6'}, {'1', '7'}, {'1', '8'}, {'1', '9'},
{'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'}, {'2', '4'},
{'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'},
{'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'},
{'3', '5'}, {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'},
{'4', '0'}, {'4', '1'}, {'4', '2'}, {'4', '3'}, {'4', '4'},
{'4', '5'}, {'4', '6'}, {'4', '7'}, {'4', '8'}, {'4', '9'},
{'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'}, {'5', '4'},
{'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'},
{'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'},
{'6', '5'}, {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'},
{'7', '0'}, {'7', '1'}, {'7', '2'}, {'7', '3'}, {'7', '4'},
{'7', '5'}, {'7', '6'}, {'7', '7'}, {'7', '8'}, {'7', '9'},
{'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'}, {'8', '4'},
{'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'},
{'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'},
{'9', '5'}, {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}
};
static inline void PutTwoDigits(int i, char* p) {
DCHECK_GE(i, 0);
DCHECK_LT(i, 100);
p[0] = two_ASCII_digits[i][0];
p[1] = two_ASCII_digits[i][1];
}
// ----------------------------------------------------------------------
// FastInt32ToBufferLeft()
// FastUInt32ToBufferLeft()
// FastInt64ToBufferLeft()
// FastUInt64ToBufferLeft()
//
// Like the Fast*ToBuffer() functions above, these are intended for speed.
// Unlike the Fast*ToBuffer() functions, however, these functions write
// their output to the beginning of the buffer (hence the name, as the
// output is left-aligned). The caller is responsible for ensuring that
// the buffer has enough space to hold the output.
//
// Returns a pointer to the end of the string (i.e. the null character
// terminating the string).
// ----------------------------------------------------------------------
char* FastUInt32ToBufferLeft(uint32 u, char* buffer) {
int digits;
const char *ASCII_digits = NULL;
// The idea of this implementation is to trim the number of divides to as few
// as possible by using multiplication and subtraction rather than mod (%),
// and by outputting two digits at a time rather than one.
// The huge-number case is first, in the hopes that the compiler will output
// that case in one branch-free block of code, and only output conditional
// branches into it from below.
if (u >= 1000000000) { // >= 1,000,000,000
digits = u / 100000000; // 100,000,000
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
sublt100_000_000:
u -= digits * 100000000; // 100,000,000
lt100_000_000:
digits = u / 1000000; // 1,000,000
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
sublt1_000_000:
u -= digits * 1000000; // 1,000,000
lt1_000_000:
digits = u / 10000; // 10,000
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
sublt10_000:
u -= digits * 10000; // 10,000
lt10_000:
digits = u / 100;
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
sublt100:
u -= digits * 100;
lt100:
digits = u;
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
done:
*buffer = 0;
return buffer;
}
if (u < 100) {
digits = u;
if (u >= 10) goto lt100;
*buffer++ = '0' + digits;
goto done;
}
if (u < 10000) { // 10,000
if (u >= 1000) goto lt10_000;
digits = u / 100;
*buffer++ = '0' + digits;
goto sublt100;
}
if (u < 1000000) { // 1,000,000
if (u >= 100000) goto lt1_000_000;
digits = u / 10000; // 10,000
*buffer++ = '0' + digits;
goto sublt10_000;
}
if (u < 100000000) { // 100,000,000
if (u >= 10000000) goto lt100_000_000;
digits = u / 1000000; // 1,000,000
*buffer++ = '0' + digits;
goto sublt1_000_000;
}
// we already know that u < 1,000,000,000
digits = u / 100000000; // 100,000,000
*buffer++ = '0' + digits;
goto sublt100_000_000;
}
char* FastInt32ToBufferLeft(int32 i, char* buffer) {
uint32 u = i;
if (i < 0) {
*buffer++ = '-';
// We need to do the negation in modular (i.e., "unsigned")
// arithmetic; MSVC++ apprently warns for plain "-u", so
// we write the equivalent expression "0 - u" instead.
u = 0 - u;
}
return FastUInt32ToBufferLeft(u, buffer);
}
char* FastUInt64ToBufferLeft(uint64 u64, char* buffer) {
int digits;
const char *ASCII_digits = NULL;
uint32 u = static_cast<uint32>(u64);
if (u == u64) return FastUInt32ToBufferLeft(u, buffer);
uint64 top_11_digits = u64 / 1000000000;
buffer = FastUInt64ToBufferLeft(top_11_digits, buffer);
u = u64 - (top_11_digits * 1000000000);
digits = u / 10000000; // 10,000,000
DCHECK_LT(digits, 100);
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
u -= digits * 10000000; // 10,000,000
digits = u / 100000; // 100,000
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
u -= digits * 100000; // 100,000
digits = u / 1000; // 1,000
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
u -= digits * 1000; // 1,000
digits = u / 10;
ASCII_digits = two_ASCII_digits[digits];
buffer[0] = ASCII_digits[0];
buffer[1] = ASCII_digits[1];
buffer += 2;
u -= digits * 10;
digits = u;
*buffer++ = '0' + digits;
*buffer = 0;
return buffer;
}
char* FastInt64ToBufferLeft(int64 i, char* buffer) {
uint64 u = i;
if (i < 0) {
*buffer++ = '-';
u = 0 - u;
}
return FastUInt64ToBufferLeft(u, buffer);
}
int HexDigitsPrefix(const char* buf, int num_digits) {
for (int i = 0; i < num_digits; i++)
if (!ascii_isxdigit(buf[i]))
return 0; // This also detects end of string as '\0' is not xdigit.
return 1;
}
// ----------------------------------------------------------------------
// AutoDigitStrCmp
// AutoDigitLessThan
// StrictAutoDigitLessThan
// autodigit_less
// autodigit_greater
// strict_autodigit_less
// strict_autodigit_greater
// These are like less<string> and greater<string>, except when a
// run of digits is encountered at corresponding points in the two
// arguments. Such digit strings are compared numerically instead
// of lexicographically. Therefore if you sort by
// "autodigit_less", some machine names might get sorted as:
// exaf1
// exaf2
// exaf10
// When using "strict" comparison (AutoDigitStrCmp with the strict flag
// set to true, or the strict version of the other functions),
// strings that represent equal numbers will not be considered equal if
// the string representations are not identical. That is, "01" < "1" in
// strict mode, but "01" == "1" otherwise.
// ----------------------------------------------------------------------
int AutoDigitStrCmp(const char* a, int alen,
const char* b, int blen,
bool strict) {
int aindex = 0;
int bindex = 0;
while ((aindex < alen) && (bindex < blen)) {
if (isdigit(a[aindex]) && isdigit(b[bindex])) {
// Compare runs of digits. Instead of extracting numbers, we
// just skip leading zeroes, and then get the run-lengths. This
// allows us to handle arbitrary precision numbers. We remember
// how many zeroes we found so that we can differentiate between
// "1" and "01" in strict mode.
// Skip leading zeroes, but remember how many we found
int azeroes = aindex;
int bzeroes = bindex;
while ((aindex < alen) && (a[aindex] == '0')) aindex++;
while ((bindex < blen) && (b[bindex] == '0')) bindex++;
azeroes = aindex - azeroes;
bzeroes = bindex - bzeroes;
// Count digit lengths
int astart = aindex;
int bstart = bindex;
while ((aindex < alen) && isdigit(a[aindex])) aindex++;
while ((bindex < blen) && isdigit(b[bindex])) bindex++;
if (aindex - astart < bindex - bstart) {
// a has shorter run of digits: so smaller
return -1;
} else if (aindex - astart > bindex - bstart) {
// a has longer run of digits: so larger
return 1;
} else {
// Same lengths, so compare digit by digit
for (int i = 0; i < aindex-astart; i++) {
if (a[astart+i] < b[bstart+i]) {
return -1;
} else if (a[astart+i] > b[bstart+i]) {
return 1;
}
}
// Equal: did one have more leading zeroes?
if (strict && azeroes != bzeroes) {
if (azeroes > bzeroes) {
// a has more leading zeroes: a < b
return -1;
} else {
// b has more leading zeroes: a > b
return 1;
}
}
// Equal: so continue scanning
}
} else if (a[aindex] < b[bindex]) {
return -1;
} else if (a[aindex] > b[bindex]) {
return 1;
} else {
aindex++;
bindex++;
}
}
if (aindex < alen) {
// b is prefix of a
return 1;
} else if (bindex < blen) {
// a is prefix of b
return -1;
} else {
// a is equal to b
return 0;
}
}
bool AutoDigitLessThan(const char* a, int alen, const char* b, int blen) {
return AutoDigitStrCmp(a, alen, b, blen, false) < 0;
}
bool StrictAutoDigitLessThan(const char* a, int alen,
const char* b, int blen) {
return AutoDigitStrCmp(a, alen, b, blen, true) < 0;
}
// ----------------------------------------------------------------------
// SimpleDtoa()
// SimpleFtoa()
// DoubleToBuffer()
// FloatToBuffer()
// We want to print the value without losing precision, but we also do
// not want to print more digits than necessary. This turns out to be
// trickier than it sounds. Numbers like 0.2 cannot be represented
// exactly in binary. If we print 0.2 with a very large precision,
// e.g. "%.50g", we get "0.2000000000000000111022302462515654042363167".
// On the other hand, if we set the precision too low, we lose
// significant digits when printing numbers that actually need them.
// It turns out there is no precision value that does the right thing
// for all numbers.
//
// Our strategy is to first try printing with a precision that is never
// over-precise, then parse the result with strtod() to see if it
// matches. If not, we print again with a precision that will always
// give a precise result, but may use more digits than necessary.
//
// An arguably better strategy would be to use the algorithm described
// in "How to Print Floating-Point Numbers Accurately" by Steele &
// White, e.g. as implemented by David M. Gay's dtoa(). It turns out,
// however, that the following implementation is about as fast as
// DMG's code. Furthermore, DMG's code locks mutexes, which means it
// will not scale well on multi-core machines. DMG's code is slightly
// more accurate (in that it will never use more digits than
// necessary), but this is probably irrelevant for most users.
//
// Rob Pike and Ken Thompson also have an implementation of dtoa() in
// third_party/fmt/fltfmt.cc. Their implementation is similar to this
// one in that it makes guesses and then uses strtod() to check them.
// Their implementation is faster because they use their own code to
// generate the digits in the first place rather than use snprintf(),
// thus avoiding format string parsing overhead. However, this makes
// it considerably more complicated than the following implementation,
// and it is embedded in a larger library. If speed turns out to be
// an issue, we could re-implement this in terms of their
// implementation.
// ----------------------------------------------------------------------
string SimpleDtoa(double value) {
char buffer[kDoubleToBufferSize];
return DoubleToBuffer(value, buffer);
}
string SimpleFtoa(float value) {
char buffer[kFloatToBufferSize];
return FloatToBuffer(value, buffer);
}
char* DoubleToBuffer(double value, char* buffer) {
// DBL_DIG is 15 for IEEE-754 doubles, which are used on almost all
// platforms these days. Just in case some system exists where DBL_DIG
// is significantly larger -- and risks overflowing our buffer -- we have
// this assert.
COMPILE_ASSERT(DBL_DIG < 20, DBL_DIG_is_too_big);
int snprintf_result =
snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG, value);
// The snprintf should never overflow because the buffer is significantly
// larger than the precision we asked for.
DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize);
if (strtod(buffer, NULL) != value) {
snprintf_result =
snprintf(buffer, kDoubleToBufferSize, "%.*g", DBL_DIG+2, value);
// Should never overflow; see above.
DCHECK(snprintf_result > 0 && snprintf_result < kDoubleToBufferSize);
}
return buffer;
}
char* FloatToBuffer(float value, char* buffer) {
// FLT_DIG is 6 for IEEE-754 floats, which are used on almost all
// platforms these days. Just in case some system exists where FLT_DIG
// is significantly larger -- and risks overflowing our buffer -- we have
// this assert.
COMPILE_ASSERT(FLT_DIG < 10, FLT_DIG_is_too_big);
int snprintf_result =
snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG, value);
// The snprintf should never overflow because the buffer is significantly
// larger than the precision we asked for.
DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize);
float parsed_value;
if (!safe_strtof(buffer, &parsed_value) || parsed_value != value) {
snprintf_result =
snprintf(buffer, kFloatToBufferSize, "%.*g", FLT_DIG+2, value);
// Should never overflow; see above.
DCHECK(snprintf_result > 0 && snprintf_result < kFloatToBufferSize);
}
return buffer;
}
// ----------------------------------------------------------------------
// SimpleItoaWithCommas()
// Description: converts an integer to a string.
// Puts commas every 3 spaces.
// Faster than printf("%d")?
//
// Return value: string
// ----------------------------------------------------------------------
string SimpleItoaWithCommas(int32 i) {
// 10 digits, 3 commas, and sign are good for 32-bit or smaller ints.
// Longest is -2,147,483,648.
char local[14];
char *p = local + sizeof(local);
// Need to use uint32 instead of int32 to correctly handle
// -2,147,483,648.
uint32 n = i;
if (i < 0)
n = 0 - n; // negate the unsigned value to avoid overflow
*--p = '0' + n % 10; // this case deals with the number "0"
n /= 10;
while (n) {
*--p = '0' + n % 10;
n /= 10;
if (n == 0) break;
*--p = '0' + n % 10;
n /= 10;
if (n == 0) break;
*--p = ',';
*--p = '0' + n % 10;
n /= 10;
// For this unrolling, we check if n == 0 in the main while loop
}
if (i < 0)
*--p = '-';
return string(p, local + sizeof(local));
}
// We need this overload because otherwise SimpleItoaWithCommas(5U) wouldn't
// compile.
string SimpleItoaWithCommas(uint32 i) {
// 10 digits and 3 commas are good for 32-bit or smaller ints.
// Longest is 4,294,967,295.
char local[13];
char *p = local + sizeof(local);
*--p = '0' + i % 10; // this case deals with the number "0"
i /= 10;
while (i) {
*--p = '0' + i % 10;
i /= 10;
if (i == 0) break;
*--p = '0' + i % 10;
i /= 10;
if (i == 0) break;
*--p = ',';
*--p = '0' + i % 10;
i /= 10;
// For this unrolling, we check if i == 0 in the main while loop
}
return string(p, local + sizeof(local));
}
string SimpleItoaWithCommas(int64 i) {
// 19 digits, 6 commas, and sign are good for 64-bit or smaller ints.
char local[26];
char *p = local + sizeof(local);
// Need to use uint64 instead of int64 to correctly handle
// -9,223,372,036,854,775,808.
uint64 n = i;
if (i < 0)
n = 0 - n;
*--p = '0' + n % 10; // this case deals with the number "0"
n /= 10;
while (n) {
*--p = '0' + n % 10;
n /= 10;
if (n == 0) break;
*--p = '0' + n % 10;
n /= 10;
if (n == 0) break;
*--p = ',';
*--p = '0' + n % 10;
n /= 10;
// For this unrolling, we check if n == 0 in the main while loop
}
if (i < 0)
*--p = '-';
return string(p, local + sizeof(local));
}
// We need this overload because otherwise SimpleItoaWithCommas(5ULL) wouldn't
// compile.
string SimpleItoaWithCommas(uint64 i) {
// 20 digits and 6 commas are good for 64-bit or smaller ints.
// Longest is 18,446,744,073,709,551,615.
char local[26];
char *p = local + sizeof(local);
*--p = '0' + i % 10; // this case deals with the number "0"
i /= 10;
while (i) {
*--p = '0' + i % 10;
i /= 10;
if (i == 0) break;
*--p = '0' + i % 10;
i /= 10;
if (i == 0) break;
*--p = ',';
*--p = '0' + i % 10;
i /= 10;
// For this unrolling, we check if i == 0 in the main while loop
}
return string(p, local + sizeof(local));
}
// ----------------------------------------------------------------------
// ItoaKMGT()
// Description: converts an integer to a string
// Truncates values to a readable unit: K, G, M or T
// Opposite of atoi_kmgt()
// e.g. 100 -> "100" 1500 -> "1500" 4000 -> "3K" 57185920 -> "45M"
//
// Return value: string
// ----------------------------------------------------------------------
string ItoaKMGT(int64 i) {
const char *sign = "", *suffix = "";
if (i < 0) {
// We lose some accuracy if the caller passes LONG_LONG_MIN, but
// that's OK as this function is only for human readability
if (i == std::numeric_limits<int64>::min()) i++;
sign = "-";
i = -i;
}
int64 val;
if ((val = (i >> 40)) > 1) {
suffix = "T";
} else if ((val = (i >> 30)) > 1) {
suffix = "G";
} else if ((val = (i >> 20)) > 1) {
suffix = "M";
} else if ((val = (i >> 10)) > 1) {
suffix = "K";
} else {
val = i;
}
return StringPrintf("%s%" PRId64 "d%s", sign, val, suffix);
}
// DEPRECATED(wadetregaskis).
// These are non-inline because some BUILD files turn on -Wformat-non-literal.
string FloatToString(float f, const char* format) {
return StringPrintf(format, f);
}
string IntToString(int i, const char* format) {
return StringPrintf(format, i);
}
string Int64ToString(int64 i64, const char* format) {
return StringPrintf(format, i64);
}
string UInt64ToString(uint64 ui64, const char* format) {
return StringPrintf(format, ui64);
}
// DEPRECATED(wadetregaskis). Just call StringPrintf.
string FloatToString(float f) {
return StringPrintf("%7f", f);
}
// DEPRECATED(wadetregaskis). Just call StringPrintf.
string IntToString(int i) {
return StringPrintf("%7d", i);
}
// DEPRECATED(wadetregaskis). Just call StringPrintf.
string Int64ToString(int64 i64) {
return StringPrintf("%7" PRId64, i64);
}
// DEPRECATED(wadetregaskis). Just call StringPrintf.
string UInt64ToString(uint64 ui64) {
return StringPrintf("%7" PRIu64, ui64);
}
|
Java
|
require "language/haskell"
class Ghc < Formula
include Language::Haskell::Cabal
desc "Glorious Glasgow Haskell Compilation System"
homepage "https://haskell.org/ghc/"
url "https://downloads.haskell.org/~ghc/8.6.3/ghc-8.6.3-src.tar.xz"
sha256 "9f9e37b7971935d88ba80426c36af14b1e0b3ec1d9c860f44a4391771bc07f23"
bottle do
sha256 "9415b057d996a9d4d27f61edf2e31b3f11fb511661313d9f266fa029254c9088" => :mojave
sha256 "b16adbcf90f33bf12162855bd2f2308d5f4656cbb2f533a8cb6a0ed48519be83" => :high_sierra
sha256 "c469d291be7683a759ac950c11226d080994b9e4d44f9f784ab81d0f0483b498" => :sierra
end
head do
url "https://git.haskell.org/ghc.git", :branch => "ghc-8.6"
depends_on "autoconf" => :build
depends_on "automake" => :build
depends_on "libtool" => :build
resource "cabal" do
url "https://hackage.haskell.org/package/cabal-install-2.4.0.0/cabal-install-2.4.0.0.tar.gz"
sha256 "1329e9564b736b0cfba76d396204d95569f080e7c54fe355b6d9618e3aa0bef6"
end
end
depends_on "python" => :build
depends_on "sphinx-doc" => :build
resource "gmp" do
url "https://ftp.gnu.org/gnu/gmp/gmp-6.1.2.tar.xz"
mirror "https://gmplib.org/download/gmp/gmp-6.1.2.tar.xz"
mirror "https://ftpmirror.gnu.org/gmp/gmp-6.1.2.tar.xz"
sha256 "87b565e89a9a684fe4ebeeddb8399dce2599f9c9049854ca8c0dfbdea0e21912"
end
# https://www.haskell.org/ghc/download_ghc_8_0_1#macosx_x86_64
# "This is a distribution for Mac OS X, 10.7 or later."
resource "binary" do
url "https://downloads.haskell.org/~ghc/8.4.4/ghc-8.4.4-x86_64-apple-darwin.tar.xz"
sha256 "28dc89ebd231335337c656f4c5ead2ae2a1acc166aafe74a14f084393c5ef03a"
end
def install
ENV["CC"] = ENV.cc
ENV["LD"] = "ld"
# Build a static gmp rather than in-tree gmp, otherwise all ghc-compiled
# executables link to Homebrew's GMP.
gmp = libexec/"integer-gmp"
# GMP *does not* use PIC by default without shared libs so --with-pic
# is mandatory or else you'll get "illegal text relocs" errors.
resource("gmp").stage do
system "./configure", "--prefix=#{gmp}", "--with-pic", "--disable-shared",
"--build=#{Hardware.oldest_cpu}-apple-darwin#{`uname -r`.to_i}"
system "make"
system "make", "check"
system "make", "install"
end
args = ["--with-gmp-includes=#{gmp}/include",
"--with-gmp-libraries=#{gmp}/lib"]
# As of Xcode 7.3 (and the corresponding CLT) `nm` is a symlink to `llvm-nm`
# and the old `nm` is renamed `nm-classic`. Building with the new `nm`, a
# segfault occurs with the following error:
# make[1]: * [compiler/stage2/dll-split.stamp] Segmentation fault: 11
# Upstream is aware of the issue and is recommending the use of nm-classic
# until Apple restores POSIX compliance:
# https://ghc.haskell.org/trac/ghc/ticket/11744
# https://ghc.haskell.org/trac/ghc/ticket/11823
# https://mail.haskell.org/pipermail/ghc-devs/2016-April/011862.html
# LLVM itself has already fixed the bug: llvm-mirror/llvm@ae7cf585
# rdar://25311883 and rdar://25299678
if DevelopmentTools.clang_build_version >= 703 && DevelopmentTools.clang_build_version < 800
args << "--with-nm=#{`xcrun --find nm-classic`.chomp}"
end
resource("binary").stage do
binary = buildpath/"binary"
system "./configure", "--prefix=#{binary}", *args
ENV.deparallelize { system "make", "install" }
ENV.prepend_path "PATH", binary/"bin"
end
if build.head?
resource("cabal").stage do
system "sh", "bootstrap.sh", "--sandbox"
(buildpath/"bootstrap-tools/bin").install ".cabal-sandbox/bin/cabal"
end
ENV.prepend_path "PATH", buildpath/"bootstrap-tools/bin"
cabal_sandbox do
cabal_install "--only-dependencies", "happy", "alex"
cabal_install "--prefix=#{buildpath}/bootstrap-tools", "happy", "alex"
end
system "./boot"
end
system "./configure", "--prefix=#{prefix}", *args
system "make"
ENV.deparallelize { system "make", "install" }
Dir.glob(lib/"*/package.conf.d/package.cache") { |f| rm f }
end
def post_install
system "#{bin}/ghc-pkg", "recache"
end
test do
(testpath/"hello.hs").write('main = putStrLn "Hello Homebrew"')
system "#{bin}/runghc", testpath/"hello.hs"
end
end
|
Java
|
using System;
using System.Text;
using Microsoft.Extensions.Configuration;
using NLog.Common;
using NLog.Config;
using NLog.LayoutRenderers;
namespace NLog.Extensions.Logging
{
/// <summary>
/// Layout renderer that can lookup values from Microsoft Extension Configuration Container (json, xml, ini)
/// </summary>
/// <remarks>Not to be confused with NLog.AppConfig that includes ${appsetting}</remarks>
/// <example>
/// Example: appsettings.json
/// {
/// "Mode":"Prod",
/// "Options":{
/// "StorageConnectionString":"UseDevelopmentStorage=true",
/// }
/// }
///
/// Config Setting Lookup:
/// ${configsetting:name=Mode} = "Prod"
/// ${configsetting:name=Options.StorageConnectionString} = "UseDevelopmentStorage=true"
/// ${configsetting:name=Options.TableName:default=MyTable} = "MyTable"
///
/// Config Setting Lookup Cached:
/// ${configsetting:cached=True:name=Mode}
/// </example>
[LayoutRenderer("configsetting")]
[ThreadAgnostic]
[ThreadSafe]
public class ConfigSettingLayoutRenderer : LayoutRenderer
{
/// <summary>
/// Global Configuration Container
/// </summary>
public static IConfiguration DefaultConfiguration { get; set; }
///<summary>
/// Item in the setting container
///</summary>
[RequiredParameter]
[DefaultParameter]
public string Item
{
get => _item;
set
{
_item = value;
_itemLookup = value?.Replace(".", ":");
}
}
private string _item;
private string _itemLookup;
/// <summary>
/// Name of the Item
/// </summary>
[Obsolete("Replaced by Item-property")]
public string Name { get => Item; set => Item = value; }
///<summary>
/// The default value to render if the setting value is null.
///</summary>
public string Default { get; set; }
/// <inheritdoc/>
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (string.IsNullOrEmpty(_itemLookup))
return;
string value = null;
var configurationRoot = DefaultConfiguration;
if (configurationRoot != null)
{
value = configurationRoot[_itemLookup];
}
else
{
#if NETCORE1_0
InternalLogger.Debug("Missing DefaultConfiguration. Remember to provide IConfiguration when calling AddNLog");
#else
InternalLogger.Debug("Missing DefaultConfiguration. Remember to register IConfiguration by calling UseNLog");
#endif
}
builder.Append(value ?? Default);
}
}
}
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.