code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * 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; } }
skynav/ttt
ttt-ttv/src/main/java/com/xfsi/xav/validation/images/jpeg/JpegInputStream.java
Java
bsd-2-clause
3,933
<!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 &mdash; 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> &raquo;</li> <li><a href="index.html" >The Varnish Users Guide</a> &raquo;</li> <li><a href="running.html" accesskey="U">Starting and running Varnish</a> &raquo;</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 &quot;active&quot; 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&gt; 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&gt; 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&gt; 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 &quot;purges&quot; 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&gt; ban req.url ~ "logo.*[.]png"</pre> </div> <p>should do that, and yes, that is a regular expression.</p> <p>We call this &quot;banning&quot; 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&gt; 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&gt; 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">&gt;</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">&gt;</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> &raquo;</li> <li><a href="index.html" >The Varnish Users Guide</a> &raquo;</li> <li><a href="running.html" >Starting and running Varnish</a> &raquo;</li> </ul> </div> <div class="footer"> &copy; Copyright 2010-2014, Varnish Software AS. Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.1.3. </div> </body> </html>
reesun/varnish-cache-4.0.0
doc/sphinx/build/html/users-guide/run_cli.html
HTML
bsd-2-clause
12,089
// 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
smcpeak/earthshape
src/earthshape/EarthShape.java
Java
bsd-2-clause
118,405
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,'']]] ];
bplainia/galaxyLightingSystem
doxygen/html/search/files_4.js
JavaScript
bsd-2-clause
228
/* 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 }; } } } }
jlewin/agg-sharp
PolygonMesh/Processors/FaceBspTree.cs
C#
bsd-2-clause
8,877
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"); } } } }
rose-a/LabVIEW-CLI
C Sharp Source/LabVIEW CLI/Program.cs
C#
bsd-2-clause
7,352
from celery.task import Task import requests class StracksFlushTask(Task): def run(self, url, data): requests.post(url + "/", data=data)
Stracksapp/stracks_api
stracks_api/tasks.py
Python
bsd-2-clause
152
/* * 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); } }
geronimo-iia/ferox
ferox-math/src/main/java/com/ferox/math/bounds/Frustum.java
Java
bsd-2-clause
28,685
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
spatial-reasoning/zeno
src/Convert/LRChirotope.hs
Haskell
bsd-2-clause
1,839
### 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.
davidkun/linspecer
tips.md
Markdown
bsd-2-clause
762
var files = [ [ "Code", "dir_a44bec13de8698b1b3f25058862347f8.html", "dir_a44bec13de8698b1b3f25058862347f8" ] ];
crurik/GrapeFS
Doxygen/html/files.js
JavaScript
bsd-2-clause
116
{-# 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
kcharter/brc-solver
BRC/Solver/Error.hs
Haskell
bsd-2-clause
565
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); } }
hydai/Cocoon
Cocoon/src/cocoonClient/Panels/StatusPanel.java
Java
bsd-2-clause
3,759
<!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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</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&lt;<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>&gt;</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&lt;<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>&gt;</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&lt;<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>&gt;</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">&nbsp;</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>&nbsp;</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>&nbsp;</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">&nbsp;</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&nbsp;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&nbsp;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&nbsp;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&nbsp;<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&nbsp;<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&nbsp;<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>[]&nbsp;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()) &nbsp; 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&nbsp;<a href="../../../org/jetel/component/Trash.Mode.html" title="enum in org.jetel.component">Trash.Mode</a>&nbsp;valueOf(java.lang.String&nbsp;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:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li><a href="#enum_constant_summary">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#method_summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#enum_constant_detail">Enum Constants</a>&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</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 &#169; 2002-2015 Javlin a.s.</address> </small></p> </body> </html>
chris-watson/chpl-api
chpl/chpl-etl/javadoc/org/jetel/component/Trash.Mode.html
HTML
bsd-2-clause
12,175
/** * 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 { }
osxhacker/angular-codegen
src/main/scala/com/iteamsolutions/angular/models/atom/Link.scala
Scala
bsd-2-clause
419
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); } } }
f1nalspace/leverman-devlog
lman/src/de/lman/Leverman.java
Java
bsd-2-clause
11,052
{-# 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]
listx/netherworld
src/NW/Monster.hs
Haskell
bsd-2-clause
338
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; } } }
highsource/jaxb2-basics
basic/src/main/java/org/jvnet/jaxb2_commons/plugin/mergeable/MergeablePlugin.java
Java
bsd-2-clause
10,727
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; } } }
EIDSS/EIDSS-Legacy
EIDSS v6.1/bv.winclient/Core/TranslationTool/PropertyGrid.cs
C#
bsd-2-clause
4,672
# -*- 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), ), ]
praekeltfoundation/mc2-freebasics
freebasics/migrations/0007_freebasicscontroller_postgres_db_url.py
Python
bsd-2-clause
442
// 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); }
ASMlover/study
cplusplus/wren_cc/compiler.hh
C++
bsd-2-clause
1,647
<?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()); } }
hpeide/silverstripe-shop
src/ORM/FieldType/ShopCountry.php
PHP
bsd-2-clause
819
<!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>
laeotropic/HTTP-Proxy
deps/asio-1.10.1/doc/examples/diffs/futures/daytime_client.cpp.html
HTML
bsd-2-clause
1,721
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
fdr/pg_corrupt
pg_corrupt/excise.py
Python
bsd-2-clause
506
<?php /* vim: set expandtab tabstop=4 shiftwidth=4: */ // +----------------------------------------------------------------------+ // | Artisan Smarty | // +----------------------------------------------------------------------+ // | PHP Version 4 | // +----------------------------------------------------------------------+ // | Copyright 2004-2005 ARTISAN PROJECT All rights reserved. | // +----------------------------------------------------------------------+ // | Authors: Akito<[email protected]> | // +----------------------------------------------------------------------+ // /** * 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: */ ?>
EpubBuilder/EpubBuilder
Smarty/plugins/modifier.count_sentences.php
PHP
bsd-2-clause
1,355
/* * 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) } }
tototoshi/slick-joda-mapper
src/main/scala/com/github/tototoshi/slick/converter/JodaSqlTypeCoverter.scala
Scala
bsd-2-clause
3,374
# 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
snltd/wavefront-cli
lib/wavefront-cli/subcommands/import.rb
Ruby
bsd-2-clause
1,786
/* * 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; }
ASMlover/study
self-lang/klang/lexer.c
C
bsd-2-clause
8,418
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)
congpc/DjangoExample
mysite/polls/tests.py
Python
bsd-2-clause
5,010
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
grhawk/homebrew-core
Formula/get_iplayer.rb
Ruby
bsd-2-clause
2,242
/* * (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); } }
Rohde-Schwarz-Cybersecurity/botan
src/lib/asn1/asn1_print.cpp
C++
bsd-2-clause
8,549
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; } }
Drafigon/WildGraphs
src/operations/O_RelaxEdge.java
Java
bsd-2-clause
590
/* * 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); }
matt2048/optee_os
core/drivers/ps2mouse.c
C
bsd-2-clause
4,633
# Gearman [![License](http://img.shields.io/badge/license-Simplified_BSD-blue.svg?style=flat)](LICENSE.txt) [![Go Doc](http://img.shields.io/badge/godoc-gearman-blue.svg?style=flat)](http://godoc.org/github.com/nathanaelle/gearman) [![Build Status](https://travis-ci.org/nathanaelle/gearman.svg?branch=master)](https://travis-ci.org/nathanaelle/gearman) [![Go Report Card](https://goreportcard.com/badge/github.com/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 ```
nathanaelle/gearman
ReadMe.markdown
Markdown
bsd-2-clause
2,769
// 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"
PopCap/GameIdea
Engine/Plugins/Runtime/SoundMod/Source/SoundModImporter/Private/SoundModImporterPrivatePCH.h
C
bsd-2-clause
223
/** * @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 { } /&#42; starting animations for enter &#42;/ * .slide.ng-enter-active { } /&#42; terminal animations for enter &#42;/ * .slide.ng-leave { } /&#42; starting animations for leave &#42;/ * .slide.ng-leave-active { } /&#42; terminal animations for leave &#42;/ * </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"> * /&#42; * 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 * &#42;/ * .reveal-animation.ng-enter { * -webkit-transition: 1s linear all; /&#42; Safari/Chrome &#42;/ * transition: 1s linear all; /&#42; All other modern browsers and IE10+ &#42;/ * * /&#42; The animation preparation code &#42;/ * opacity: 0; * } * * /&#42; * Keep in mind that you want to combine both CSS * classes together to avoid any CSS-specificity * conflicts * &#42;/ * .reveal-animation.ng-enter.ng-enter-active { * /&#42; The animation code itself &#42;/ * 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; /&#42; Safari/Chrome &#42;/ * animation: enter_sequence 1s linear; /&#42; IE10+ and Future Browsers &#42;/ * } * &#64-webkit-keyframes enter_sequence { * from { opacity:0; } * to { opacity:1; } * } * &#64keyframes 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 { * /&#42; standard transition code &#42;/ * -webkit-transition: 1s linear all; * transition: 1s linear all; * opacity:0; * } * .my-animation.ng-enter-stagger { * /&#42; this will have a 100ms delay between each successive leave animation &#42;/ * -webkit-transition-delay: 0.1s; * transition-delay: 0.1s; * * /&#42; in case the stagger doesn't work then these two values * must be set to 0 to avoid an accidental CSS inheritance &#42;/ * -webkit-transition-duration: 0s; * transition-duration: 0s; * } * .my-animation.ng-enter.ng-enter-active { * /&#42; standard transition styles &#42;/ * 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);
sabhiram/nodejs-scaffolding
app/public/js/angular-animate.js
JavaScript
bsd-2-clause
74,308
#!/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())
MattJDavidson/python-adventofcode
advent/problem_03.py
Python
bsd-2-clause
3,424
/** * @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)); }
Kefir0192/embox
src/tests/security/smac.c
C
bsd-2-clause
3,457
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 + ")"); } }
tkmnet/RCRS-ADF
modules/core/src/main/java/adf/launcher/connect/ConnectorAmbulanceCentre.java
Java
bsd-2-clause
1,801
<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>
tcardoso2/t-motion-detector-cli
public/site/detectors.html
HTML
bsd-2-clause
614
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
bfontaine/homebrew-core
Formula/swi-prolog.rb
Ruby
bsd-2-clause
2,633
/****************************************************************************** * 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 ([email protected]) // Rusty Howell ([email protected]) // // (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"); } } }
brunolauze/System.Management
System.Management/System.Management.Internal/CimDataTypes/CimTable.cs
C#
bsd-2-clause
1,669
# # 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;
nobuoka/evernote-sdk-perl
lib/EDAMUserStore/UserStore.pm
Perl
bsd-2-clause
58,040
// 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); }
romange/beeri
strings/numbers.cc
C++
bsd-2-clause
49,536
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
jdubois/homebrew-core
Formula/ghc.rb
Ruby
bsd-2-clause
4,374
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); } } }
NLog/NLog.Framework.Logging
src/NLog.Extensions.Logging/LayoutRenderers/ConfigSettingLayoutRenderer.cs
C#
bsd-2-clause
2,889
# pylint:disable=line-too-long import logging from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64 from .. import SIM_PROCEDURES as P from . import SimLibrary _l = logging.getLogger(name=__name__) lib = SimLibrary() lib.set_default_cc('X86', SimCCStdcall) lib.set_default_cc('AMD64', SimCCMicrosoftAMD64) lib.set_library_names("aclui.dll") prototypes = \ { # 'CreateSecurityPage': SimTypeFunction([SimTypeBottom(label="ISecurityInformation")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["psi"]), # 'EditSecurity': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi"]), # 'EditSecurityAdvanced': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation"), SimTypeInt(signed=False, label="SI_PAGE_TYPE")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi", "uSIPage"]), } lib.set_prototypes(prototypes)
angr/angr
angr/procedures/definitions/win32_aclui.py
Python
bsd-2-clause
1,451
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>RMedia.GetOffset</title> <link href="css/style.css" rel="stylesheet" type="text/css"> <meta http-equiv="Content-Type" content="text/html;charset=utf-8" > </head> <body bgcolor="#ffffff"> <table border="0" width="100%" bgcolor="#F0F0FF"> <tr> <td>Concept Framework 2.2 documentation</td> <td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td> </tr> </table> <h2><a href="RMedia.html">RMedia</a>.GetOffset</h2> <table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"> <tr bgcolor="#f0f0f0"> <td><i>Name</i></td> <td><i>Type</i></td> <td><i>Access</i></td> <td><i>Version</i></td> <td><i>Deprecated</i></td> </tr> <tr bgcolor="#fafafa"> <td><b>GetOffset</b></td> <td>function</td> <td>public</td> <td>version 1</td> <td>no</td> </tr> </table> <br /> <b>Prototype:</b><br /> <table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>public function GetOffset()</b></td></tr></table> <br /> <br /> <b>Description:</b><br /> <table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"> <tr><td> TODO: Document this </td></tr> </table> <br /> <b>Returns:</b><br /> // TO DO <br /> <br /> <!-- <p> <a href="http://validator.w3.org/check?uri=referer"><img src="http://www.w3.org/Icons/valid-html40" alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a> <a href="http://jigsaw.w3.org/css-validator/"> <img style="border:0;width:88px;height:31px" src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!" border="0"/> </a> </p> --> <table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Devronium Autodocumenter Alpha, generation time: Sun Jan 27 18:15:28 2013 GMT</td><td align="right">(c)2013 <a href="http://www.devronium.com">Devronium Applications</a></td></tr></table> </body> </html>
Devronium/ConceptApplicationServer
core/server/Samples/CIDE/Help/RMedia.GetOffset.html
HTML
bsd-2-clause
2,194
require_relative 'model' Record.where(version: 10606).delete_all
panjia1983/channel_backward
benchmarks/needle_steering/06clear_records6.rb
Ruby
bsd-2-clause
65
# -*- coding: utf-8 -*- """ femagtools.plot ~~~~~~~~~~~~~~~ Creating plots """ import numpy as np import scipy.interpolate as ip import logging try: import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm from mpl_toolkits.mplot3d import Axes3D matplotlibversion = matplotlib.__version__ except ImportError: # ModuleNotFoundError: matplotlibversion = 0 logger = logging.getLogger("femagtools.plot") def _create_3d_axis(): """creates a subplot with 3d projection if one does not already exist""" from matplotlib.projections import get_projection_class from matplotlib import _pylab_helpers create_axis = True if _pylab_helpers.Gcf.get_active() is not None: if isinstance(plt.gca(), get_projection_class('3d')): create_axis = False if create_axis: plt.figure() plt.subplot(111, projection='3d') def _plot_surface(ax, x, y, z, labels, azim=None): """helper function for surface plots""" # ax.tick_params(axis='both', which='major', pad=-3) assert np.size(x) > 1 and np.size(y) > 1 and np.size(z) > 1 if azim is not None: ax.azim = azim X, Y = np.meshgrid(x, y) Z = np.ma.masked_invalid(z) ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.viridis, alpha=0.85, vmin=np.nanmin(z), vmax=np.nanmax(z), linewidth=0, antialiased=True) # edgecolor=(0, 0, 0, 0)) # ax.set_xticks(xticks) # ax.set_yticks(yticks) # ax.set_zticks(zticks) ax.set_xlabel(labels[0]) ax.set_ylabel(labels[1]) ax.set_title(labels[2]) # plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0) def __phasor_plot(ax, up, idq, uxdq): uref = max(up, uxdq[0]) uxd = uxdq[0]/uref uxq = uxdq[1]/uref u1d, u1q = (uxd, 1+uxq) u1 = np.sqrt(u1d**2 + u1q**2)*uref i1 = np.linalg.norm(idq) i1d, i1q = (idq[0]/i1, idq[1]/i1) qhw = 6 # width arrow head qhl = 15 # length arrow head qlw = 2 # line width qts = 10 # textsize # Length of the Current adjust to Ud: Initally 0.9, Maier(Oswald) = 0.5 curfac = max(0.9, 1.5*i1q/up) def label_line(ax, X, Y, U, V, label, color='k', size=8): """Add a label to a line, at the proper angle. Arguments --------- line : matplotlib.lines.Line2D object, label : str x : float x-position to place center of text (in data coordinated y : float y-position to place center of text (in data coordinates) color : str size : float """ x1, x2 = X, X + U y1, y2 = Y, Y + V if y2 == 0: y2 = y1 if x2 == 0: x2 = x1 x = (x1 + x2) / 2 y = (y1 + y2) / 2 slope_degrees = np.rad2deg(np.angle(U + V * 1j)) if slope_degrees < 0: slope_degrees += 180 if 90 < slope_degrees <= 270: slope_degrees += 180 x_offset = np.sin(np.deg2rad(slope_degrees)) y_offset = np.cos(np.deg2rad(slope_degrees)) bbox_props = dict(boxstyle="Round4, pad=0.1", fc="white", lw=0) text = ax.annotate(label, xy=(x, y), xytext=(x_offset * 10, y_offset * 8), textcoords='offset points', size=size, color=color, horizontalalignment='center', verticalalignment='center', fontfamily='monospace', fontweight='bold', bbox=bbox_props) text.set_rotation(slope_degrees) return text if ax == 0: ax = plt.gca() ax.axes.xaxis.set_ticklabels([]) ax.axes.yaxis.set_ticklabels([]) # ax.set_aspect('equal') ax.set_title( r'$U_1$={0} V, $I_1$={1} A, $U_p$={2} V'.format( round(u1, 1), round(i1, 1), round(up, 1)), fontsize=14) up /= uref ax.quiver(0, 0, 0, up, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw/2, headlength=qhl/2, headaxislength=qhl/2, width=qlw*2, color='k') label_line(ax, 0, 0, 0, up, '$U_p$', 'k', qts) ax.quiver(0, 0, u1d, u1q, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='r') label_line(ax, 0, 0, u1d, u1q, '$U_1$', 'r', qts) ax.quiver(0, 1, uxd, 0, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g') label_line(ax, 0, 1, uxd, 0, '$U_d$', 'g', qts) ax.quiver(uxd, 1, 0, uxq, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g') label_line(ax, uxd, 1, 0, uxq, '$U_q$', 'g', qts) ax.quiver(0, 0, curfac*i1d, curfac*i1q, angles='xy', scale_units='xy', scale=1, units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='b') label_line(ax, 0, 0, curfac*i1d, curfac*i1q, '$I_1$', 'b', qts) xmin, xmax = (min(0, uxd, i1d), max(0, i1d, uxd)) ymin, ymax = (min(0, i1q, 1-uxq), max(1, i1q, 1+uxq)) ax.set_xlim([xmin-0.1, xmax+0.1]) ax.set_ylim([ymin-0.1, ymax+0.1]) ax.grid(True) def i1beta_phasor(up, i1, beta, r1, xd, xq, ax=0): """creates a phasor plot up: internal voltage i1: current beta: angle i1 vs up [deg] r1: resistance xd: reactance in direct axis xq: reactance in quadrature axis""" i1d, i1q = (i1*np.sin(beta/180*np.pi), i1*np.cos(beta/180*np.pi)) uxdq = ((r1*i1d - xq*i1q), (r1*i1q + xd*i1d)) __phasor_plot(ax, up, (i1d, i1q), uxdq) def iqd_phasor(up, iqd, uqd, ax=0): """creates a phasor plot up: internal voltage iqd: current uqd: terminal voltage""" uxdq = (uqd[1]/np.sqrt(2), (uqd[0]/np.sqrt(2)-up)) __phasor_plot(ax, up, (iqd[1]/np.sqrt(2), iqd[0]/np.sqrt(2)), uxdq) def phasor(bch, ax=0): """create phasor plot from bch""" f1 = bch.machine['p']*bch.dqPar['speed'] w1 = 2*np.pi*f1 xd = w1*bch.dqPar['ld'][-1] xq = w1*bch.dqPar['lq'][-1] r1 = bch.machine['r1'] i1beta_phasor(bch.dqPar['up'][-1], bch.dqPar['i1'][-1], bch.dqPar['beta'][-1], r1, xd, xq, ax) def airgap(airgap, ax=0): """creates plot of flux density in airgap""" if ax == 0: ax = plt.gca() ax.set_title('Airgap Flux Density [T]') ax.plot(airgap['pos'], airgap['B'], label='Max {:4.2f} T'.format(max(airgap['B']))) ax.plot(airgap['pos'], airgap['B_fft'], label='Base Ampl {:4.2f} T'.format(airgap['Bamp'])) ax.set_xlabel('Position/°') ax.legend() ax.grid(True) def airgap_fft(airgap, bmin=1e-2, ax=0): """plot airgap harmonics""" unit = 'T' if ax == 0: ax = plt.gca() ax.set_title('Airgap Flux Density Harmonics / {}'.format(unit)) ax.grid(True) order, fluxdens = np.array([(n, b) for n, b in zip(airgap['nue'], airgap['B_nue']) if b > bmin]).T try: markerline1, stemlines1, _ = ax.stem(order, fluxdens, '-.', basefmt=" ", use_line_collection=True) ax.set_xticks(order) except ValueError: # empty sequence pass def torque(pos, torque, ax=0): """creates plot from torque vs position""" k = 20 alpha = np.linspace(pos[0], pos[-1], k*len(torque)) f = ip.interp1d(pos, torque, kind='quadratic') unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if ax == 0: ax = plt.gca() ax.set_title('Torque / {}'.format(unit)) ax.grid(True) ax.plot(pos, [scale*t for t in torque], 'go') ax.plot(alpha, scale*f(alpha)) if np.min(torque) > 0 and np.max(torque) > 0: ax.set_ylim(bottom=0) elif np.min(torque) < 0 and np.max(torque) < 0: ax.set_ylim(top=0) def torque_fft(order, torque, ax=0): """plot torque harmonics""" unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if ax == 0: ax = plt.gca() ax.set_title('Torque Harmonics / {}'.format(unit)) ax.grid(True) try: bw = 2.5E-2*max(order) ax.bar(order, [scale*t for t in torque], width=bw, align='center') ax.set_xlim(left=-bw/2) except ValueError: # empty sequence pass def force(title, pos, force, xlabel='', ax=0): """plot force vs position""" unit = 'N' scale = 1 if min(force) < -9.9e3 or max(force) > 9.9e3: scale = 1e-3 unit = 'kN' if ax == 0: ax = plt.gca() ax.set_title('{} / {}'.format(title, unit)) ax.grid(True) ax.plot(pos, [scale*f for f in force]) if xlabel: ax.set_xlabel(xlabel) if min(force) > 0: ax.set_ylim(bottom=0) def force_fft(order, force, ax=0): """plot force harmonics""" unit = 'N' scale = 1 if min(force) < -9.9e3 or max(force) > 9.9e3: scale = 1e-3 unit = 'kN' if ax == 0: ax = plt.gca() ax.set_title('Force Harmonics / {}'.format(unit)) ax.grid(True) try: bw = 2.5E-2*max(order) ax.bar(order, [scale*t for t in force], width=bw, align='center') ax.set_xlim(left=-bw/2) except ValueError: # empty sequence pass def forcedens(title, pos, fdens, ax=0): """plot force densities""" if ax == 0: ax = plt.gca() ax.set_title(title) ax.grid(True) ax.plot(pos, [1e-3*ft for ft in fdens[0]], label='F tang') ax.plot(pos, [1e-3*fn for fn in fdens[1]], label='F norm') ax.legend() ax.set_xlabel('Pos / deg') ax.set_ylabel('Force Density / kN/m²') def forcedens_surface(fdens, ax=0): if ax == 0: _create_3d_axis() ax = plt.gca() xpos = [p for p in fdens.positions[0]['X']] ypos = [p['position'] for p in fdens.positions] z = 1e-3*np.array([p['FN'] for p in fdens.positions]) _plot_surface(ax, xpos, ypos, z, (u'Rotor pos/°', u'Pos/°', u'F N / kN/m²')) def forcedens_fft(title, fdens, ax=0): """plot force densities FFT Args: title: plot title fdens: force density object """ if ax == 0: ax = plt.axes(projection="3d") F = 1e-3*fdens.fft() fmin = 0.2 num_bars = F.shape[0] + 1 _xx, _yy = np.meshgrid(np.arange(1, num_bars), np.arange(1, num_bars)) z_size = F[F > fmin] x_pos, y_pos = _xx[F > fmin], _yy[F > fmin] z_pos = np.zeros_like(z_size) x_size = 2 y_size = 2 ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size) ax.view_init(azim=120) ax.set_xlim(0, num_bars+1) ax.set_ylim(0, num_bars+1) ax.set_title(title) ax.set_xlabel('M') ax.set_ylabel('N') ax.set_zlabel('kN/m²') def winding_flux(pos, flux, ax=0): """plot flux vs position""" if ax == 0: ax = plt.gca() ax.set_title('Winding Flux / Vs') ax.grid(True) for p, f in zip(pos, flux): ax.plot(p, f) def winding_current(pos, current, ax=0): """plot winding currents""" if ax == 0: ax = plt.gca() ax.set_title('Winding Currents / A') ax.grid(True) for p, i in zip(pos, current): ax.plot(p, i) def voltage(title, pos, voltage, ax=0): """plot voltage vs. position""" if ax == 0: ax = plt.gca() ax.set_title('{} / V'.format(title)) ax.grid(True) ax.plot(pos, voltage) def voltage_fft(title, order, voltage, ax=0): """plot FFT harmonics of voltage""" if ax == 0: ax = plt.gca() ax.set_title('{} / V'.format(title)) ax.grid(True) if max(order) < 5: order += [5] voltage += [0] try: bw = 2.5E-2*max(order) ax.bar(order, voltage, width=bw, align='center') except ValueError: # empty sequence pass def mcv_hbj(mcv, log=True, ax=0): """plot H, B, J of mcv dict""" import femagtools.mcv MUE0 = 4e-7*np.pi ji = [] csiz = len(mcv['curve']) if ax == 0: ax = plt.gca() ax.set_title(mcv['name']) for k, c in enumerate(mcv['curve']): bh = [(bi, hi*1e-3) for bi, hi in zip(c['bi'], c['hi'])] try: if csiz == 1 and mcv['ctype'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV): ji = [b-MUE0*h*1e3 for b, h in bh] except Exception: pass bi, hi = zip(*bh) label = 'Flux Density' if csiz > 1: label = 'Flux Density ({0}°)'.format(mcv.mc1_angle[k]) if log: ax.semilogx(hi, bi, label=label) if ji: ax.semilogx(hi, ji, label='Polarisation') else: ax.plot(hi, bi, label=label) if ji: ax.plot(hi, ji, label='Polarisation') ax.set_xlabel('H / kA/m') ax.set_ylabel('T') if ji or csiz > 1: ax.legend(loc='lower right') ax.grid() def mcv_muer(mcv, ax=0): """plot rel. permeability vs. B of mcv dict""" MUE0 = 4e-7*np.pi bi, ur = zip(*[(bx, bx/hx/MUE0) for bx, hx in zip(mcv['curve'][0]['bi'], mcv['curve'][0]['hi']) if not hx == 0]) if ax == 0: ax = plt.gca() ax.plot(bi, ur) ax.set_xlabel('B / T') ax.set_title('rel. Permeability') ax.grid() def mtpa(pmrel, i1max, title='', projection='', ax=0): """create a line or surface plot with torque and mtpa curve""" nsamples = 10 i1 = np.linspace(0, i1max, nsamples) iopt = np.array([pmrel.mtpa(x) for x in i1]).T iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) if projection == '3d': nsamples = 50 else: if iqmin == 0: iqmin = 0.1*iqmax id = np.linspace(idmin, idmax, nsamples) iq = np.linspace(iqmin, iqmax, nsamples) torque_iqd = np.array( [[pmrel.torque_iqd(x, y) for y in id] for x in iq]) if projection == '3d': ax = idq_torque(id, iq, torque_iqd, ax) ax.plot(iopt[1], iopt[0], iopt[2], color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format( np.max(iopt[2][-1]))) else: if ax == 0: ax = plt.gca() ax.set_aspect('equal') x, y = np.meshgrid(id, iq) CS = ax.contour(x, y, torque_iqd, 6, colors='k') ax.clabel(CS, fmt='%d', inline=1) ax.set_xlabel('Id/A') ax.set_ylabel('Iq/A') ax.plot(iopt[1], iopt[0], color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format( np.max(iopt[2][-1]))) ax.grid() if title: ax.set_title(title) ax.legend() def mtpv(pmrel, u1max, i1max, title='', projection='', ax=0): """create a line or surface plot with voltage and mtpv curve""" w1 = pmrel.w2_imax_umax(i1max, u1max) nsamples = 20 if projection == '3d': nsamples = 50 iqmax, idmax = pmrel.iqdmax(i1max) iqmin, idmin = pmrel.iqdmin(i1max) id = np.linspace(idmin, idmax, nsamples) iq = np.linspace(iqmin, iqmax, nsamples) u1_iqd = np.array( [[np.linalg.norm(pmrel.uqd(w1, iqx, idx))/np.sqrt(2) for idx in id] for iqx in iq]) u1 = np.mean(u1_iqd) imtpv = np.array([pmrel.mtpv(wx, u1, i1max) for wx in np.linspace(w1, 20*w1, nsamples)]).T if projection == '3d': torque_iqd = np.array( [[pmrel.torque_iqd(x, y) for y in id] for x in iq]) ax = idq_torque(id, iq, torque_iqd, ax) ax.plot(imtpv[1], imtpv[0], imtpv[2], color='red', linewidth=2) else: if ax == 0: ax = plt.gca() ax.set_aspect('equal') x, y = np.meshgrid(id, iq) CS = ax.contour(x, y, u1_iqd, 4, colors='b') # linestyles='dashed') ax.clabel(CS, fmt='%d', inline=1) ax.plot(imtpv[1], imtpv[0], color='red', linewidth=2, label='MTPV: {0:5.0f} Nm'.format(np.max(imtpv[2]))) # beta = np.arctan2(imtpv[1][0], imtpv[0][0]) # b = np.linspace(beta, 0) # ax.plot(np.sqrt(2)*i1max*np.sin(b), np.sqrt(2)*i1max*np.cos(b), 'r-') ax.grid() ax.legend() ax.set_xlabel('Id/A') ax.set_ylabel('Iq/A') if title: ax.set_title(title) def __get_linearForce_title_keys(lf): if 'force_r' in lf: return ['Force r', 'Force z'], ['force_r', 'force_z'] return ['Force x', 'Force y'], ['force_x', 'force_y'] def pmrelsim(bch, title=''): """creates a plot of a PM/Rel motor simulation""" cols = 2 rows = 4 if len(bch.flux['1']) > 1: rows += 1 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) tq = list(bch.torque_fft[-1]['torque']) order = list(bch.torque_fft[-1]['order']) if order and max(order) < 5: order += [15] tq += [0] torque_fft(order, tq) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def multcal(bch, title=''): """creates a plot of a MULT CAL simulation""" cols = 2 rows = 4 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) tq = list(bch.torque_fft[-1]['torque']) order = list(bch.torque_fft[-1]['order']) if order and max(order) < 5: order += [15] tq += [0] torque_fft(order, tq) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def fasttorque(bch, title=''): """creates a plot of a Fast Torque simulation""" cols = 2 rows = 4 if len(bch.flux['1']) > 1: rows += 1 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[-1]['angle'], bch.torque[-1]['torque']) plt.subplot(rows, cols, row+1) torque_fft(bch.torque_fft[-1]['order'], bch.torque_fft[-1]['torque']) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[-1]['angle'], bch.torque[-1]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[-1]['angle'], bch.torque[-1]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) flux = [bch.flux[k][-1] for k in bch.flux] pos = [f['displ'] for f in flux] winding_flux(pos, [f['flux_k'] for f in flux]) plt.subplot(rows, cols, row+2) winding_current(pos, [f['current_k'] for f in flux]) plt.subplot(rows, cols, row+3) voltage('Internal Voltage', bch.flux['1'][-1]['displ'], bch.flux['1'][-1]['voltage_dpsi']) plt.subplot(rows, cols, row+4) try: voltage_fft('Internal Voltage Harmonics', bch.flux_fft['1'][-1]['order'], bch.flux_fft['1'][-1]['voltage']) except: pass if len(bch.flux['1']) > 1: plt.subplot(rows, cols, row+5) voltage('No Load Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+6) try: voltage_fft('No Load Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) except: pass fig.tight_layout(h_pad=3.5) if title: fig.subplots_adjust(top=0.92) def cogging(bch, title=''): """creates a cogging plot""" cols = 2 rows = 3 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) if bch.torque: torque(bch.torque[0]['angle'], bch.torque[0]['torque']) plt.subplot(rows, cols, row+1) if bch.torque_fft: torque_fft(bch.torque_fft[0]['order'], bch.torque_fft[0]['torque']) plt.subplot(rows, cols, row+2) force('Force Fx', bch.torque[0]['angle'], bch.torque[0]['force_x']) plt.subplot(rows, cols, row+3) force('Force Fy', bch.torque[0]['angle'], bch.torque[0]['force_y']) row += 3 elif bch.linearForce: title, keys = __get_linearForce_title_keys(bch.linearForce[-1]) force(title[0], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[0]], 'Displt. / mm') plt.subplot(rows, cols, row+1) force_fft(bch.linearForce_fft[-2]['order'], bch.linearForce_fft[-2]['force']) plt.subplot(rows, cols, row+2) force(title[1], bch.linearForce[-1]['displ'], bch.linearForce[-1][keys[1]], 'Displt. / mm') plt.subplot(rows, cols, row+3) force_fft(bch.linearForce_fft[-1]['order'], bch.linearForce_fft[-1]['force']) row += 3 plt.subplot(rows, cols, row+1) voltage('Voltage', bch.flux['1'][0]['displ'], bch.flux['1'][0]['voltage_dpsi']) plt.subplot(rows, cols, row+2) voltage_fft('Voltage Harmonics', bch.flux_fft['1'][0]['order'], bch.flux_fft['1'][0]['voltage']) fig.tight_layout(h_pad=2) if title: fig.subplots_adjust(top=0.92) def transientsc(bch, title=''): """creates a transient short circuit plot""" cols = 1 rows = 2 htitle = 1.5 if title else 0 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 3*rows + htitle)) if title: fig.suptitle(title, fontsize=16) row = 1 plt.subplot(rows, cols, row) ax = plt.gca() ax.set_title('Currents / A') ax.grid(True) for i in ('ia', 'ib', 'ic'): ax.plot(bch.scData['time'], bch.scData[i], label=i) ax.set_xlabel('Time / s') ax.legend() row = 2 plt.subplot(rows, cols, row) ax = plt.gca() ax.set_title('Torque / Nm') ax.grid(True) ax.plot(bch.scData['time'], bch.scData['torque']) ax.set_xlabel('Time / s') fig.tight_layout(h_pad=2) if title: fig.subplots_adjust(top=0.92) def i1beta_torque(i1, beta, torque, title='', ax=0): """creates a surface plot of torque vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 210 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -60 unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' if title: _plot_surface(ax, i1, beta, scale*np.asarray(torque), (u'I1/A', u'Beta/°', title), azim=azim) else: _plot_surface(ax, i1, beta, scale*np.asarray(torque), (u'I1/A', u'Beta/°', u'Torque/{}'.format(unit)), azim=azim) def i1beta_ld(i1, beta, ld, ax=0): """creates a surface plot of ld vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, np.asarray(ld)*1e3, (u'I1/A', u'Beta/°', u'Ld/mH'), azim=60) def i1beta_lq(i1, beta, lq, ax=0): """creates a surface plot of ld vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 60 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -120 _plot_surface(ax, i1, beta, np.asarray(lq)*1e3, (u'I1/A', u'Beta/°', u'Lq/mH'), azim=azim) def i1beta_psim(i1, beta, psim, ax=0): """creates a surface plot of psim vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, psim, (u'I1/A', u'Beta/°', u'Psi m/Vs'), azim=60) def i1beta_up(i1, beta, up, ax=0): """creates a surface plot of up vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, i1, beta, up, (u'I1/A', u'Beta/°', u'Up/V'), azim=60) def i1beta_psid(i1, beta, psid, ax=0): """creates a surface plot of psid vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = -60 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = 60 _plot_surface(ax, i1, beta, psid, (u'I1/A', u'Beta/°', u'Psi d/Vs'), azim=azim) def i1beta_psiq(i1, beta, psiq, ax=0): """creates a surface plot of psiq vs i1, beta""" if ax == 0: _create_3d_axis() ax = plt.gca() azim = 210 if 0 < np.mean(beta) or -90 > np.mean(beta): azim = -60 _plot_surface(ax, i1, beta, psiq, (u'I1/A', u'Beta/°', u'Psi q/Vs'), azim=azim) def idq_torque(id, iq, torque, ax=0): """creates a surface plot of torque vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() unit = 'Nm' scale = 1 if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3: scale = 1e-3 unit = 'kNm' _plot_surface(ax, id, iq, scale*np.asarray(torque), (u'Id/A', u'Iq/A', u'Torque/{}'.format(unit)), azim=-60) return ax def idq_psid(id, iq, psid, ax=0): """creates a surface plot of psid vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psid, (u'Id/A', u'Iq/A', u'Psi d/Vs'), azim=210) def idq_psiq(id, iq, psiq, ax=0): """creates a surface plot of psiq vs id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psiq, (u'Id/A', u'Iq/A', u'Psi q/Vs'), azim=210) def idq_psim(id, iq, psim, ax=0): """creates a surface plot of psim vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, psim, (u'Id/A', u'Iq/A', u'Psi m [Vs]'), azim=120) def idq_ld(id, iq, ld, ax=0): """creates a surface plot of ld vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, np.asarray(ld)*1e3, (u'Id/A', u'Iq/A', u'L d/mH'), azim=120) def idq_lq(id, iq, lq, ax=0): """creates a surface plot of lq vs. id, iq""" if ax == 0: _create_3d_axis() ax = plt.gca() _plot_surface(ax, id, iq, np.asarray(lq)*1e3, (u'Id/A', u'Iq/A', u'L q/mH'), azim=120) def ldlq(bch): """creates the surface plots of a BCH reader object with a ld-lq identification""" beta = bch.ldq['beta'] i1 = bch.ldq['i1'] torque = bch.ldq['torque'] ld = np.array(bch.ldq['ld']) lq = np.array(bch.ldq['lq']) psid = bch.ldq['psid'] psiq = bch.ldq['psiq'] rows = 3 fig = plt.figure(figsize=(10, 4*rows)) fig.suptitle('Ld-Lq Identification {}'.format(bch.filename), fontsize=16) fig.add_subplot(rows, 2, 1, projection='3d') i1beta_torque(i1, beta, torque) fig.add_subplot(rows, 2, 2, projection='3d') i1beta_psid(i1, beta, psid) fig.add_subplot(rows, 2, 3, projection='3d') i1beta_psiq(i1, beta, psiq) fig.add_subplot(rows, 2, 4, projection='3d') try: i1beta_psim(i1, beta, bch.ldq['psim']) except: i1beta_up(i1, beta, bch.ldq['up']) fig.add_subplot(rows, 2, 5, projection='3d') i1beta_ld(i1, beta, ld) fig.add_subplot(rows, 2, 6, projection='3d') i1beta_lq(i1, beta, lq) def psidq(bch): """creates the surface plots of a BCH reader object with a psid-psiq identification""" id = bch.psidq['id'] iq = bch.psidq['iq'] torque = bch.psidq['torque'] ld = np.array(bch.psidq_ldq['ld']) lq = np.array(bch.psidq_ldq['lq']) psim = bch.psidq_ldq['psim'] psid = bch.psidq['psid'] psiq = bch.psidq['psiq'] rows = 3 fig = plt.figure(figsize=(10, 4*rows)) fig.suptitle('Psid-Psiq Identification {}'.format( bch.filename), fontsize=16) fig.add_subplot(rows, 2, 1, projection='3d') idq_torque(id, iq, torque) fig.add_subplot(rows, 2, 2, projection='3d') idq_psid(id, iq, psid) fig.add_subplot(rows, 2, 3, projection='3d') idq_psiq(id, iq, psiq) fig.add_subplot(rows, 2, 4, projection='3d') idq_psim(id, iq, psim) fig.add_subplot(rows, 2, 5, projection='3d') idq_ld(id, iq, ld) fig.add_subplot(rows, 2, 6, projection='3d') idq_lq(id, iq, lq) def felosses(losses, coeffs, title='', log=True, ax=0): """plot iron losses with steinmetz or jordan approximation Args: losses: dict with f, B, pfe values coeffs: list with steinmetz (cw, alpha, beta) or jordan (cw, alpha, ch, beta, gamma) coeffs title: title string log: log scale for x and y axes if True """ import femagtools.losscoeffs as lc if ax == 0: ax = plt.gca() fo = losses['fo'] Bo = losses['Bo'] B = plt.np.linspace(0.9*np.min(losses['B']), 1.1*0.9*np.max(losses['B'])) for i, f in enumerate(losses['f']): pfe = [p for p in np.array(losses['pfe'])[i] if p] if f > 0: if len(coeffs) == 5: ax.plot(B, lc.pfe_jordan(f, B, *coeffs, fo=fo, Bo=Bo)) elif len(coeffs) == 3: ax.plot(B, lc.pfe_steinmetz(f, B, *coeffs, fo=fo, Bo=Bo)) plt.plot(losses['B'][:len(pfe)], pfe, marker='o', label="{} Hz".format(f)) ax.set_title("Fe Losses/(W/kg) " + title) if log: ax.set_yscale('log') ax.set_xscale('log') ax.set_xlabel("Flux Density [T]") # plt.ylabel("Pfe [W/kg]") ax.legend() ax.grid(True) def spel(isa, with_axis=False, ax=0): """plot super elements of I7/ISA7 model Args: isa: Isa7 object """ from matplotlib.patches import Polygon if ax == 0: ax = plt.gca() ax.set_aspect('equal') for se in isa.superelements: ax.add_patch(Polygon([n.xy for nc in se.nodechains for n in nc.nodes], color=isa.color[se.color], lw=0)) ax.autoscale(enable=True) if not with_axis: ax.axis('off') def mesh(isa, with_axis=False, ax=0): """plot mesh of I7/ISA7 model Args: isa: Isa7 object """ from matplotlib.lines import Line2D if ax == 0: ax = plt.gca() ax.set_aspect('equal') for el in isa.elements: pts = [list(i) for i in zip(*[v.xy for v in el.vertices])] ax.add_line(Line2D(pts[0], pts[1], color='b', ls='-', lw=0.25)) # for nc in isa.nodechains: # pts = [list(i) for i in zip(*[(n.x, n.y) for n in nc.nodes])] # ax.add_line(Line2D(pts[0], pts[1], color="b", ls="-", lw=0.25, # marker=".", ms="2", mec="None")) # for nc in isa.nodechains: # if nc.nodemid is not None: # plt.plot(*nc.nodemid.xy, "rx") ax.autoscale(enable=True) if not with_axis: ax.axis('off') def _contour(ax, title, elements, values, label='', isa=None): from matplotlib.patches import Polygon from matplotlib.collections import PatchCollection if ax == 0: ax = plt.gca() ax.set_aspect('equal') ax.set_title(title, fontsize=18) if isa: for se in isa.superelements: ax.add_patch(Polygon([n.xy for nc in se.nodechains for n in nc.nodes], color='gray', alpha=0.1, lw=0)) valid_values = np.logical_not(np.isnan(values)) patches = np.array([Polygon([v.xy for v in e.vertices]) for e in elements])[valid_values] # , cmap=matplotlib.cm.jet, alpha=0.4) p = PatchCollection(patches, alpha=1.0, match_original=False) p.set_array(np.asarray(values)[valid_values]) ax.add_collection(p) cb = plt.colorbar(p) for patch in np.array([Polygon([v.xy for v in e.vertices], fc='white', alpha=1.0) for e in elements])[np.isnan(values)]: ax.add_patch(patch) if label: cb.set_label(label=label, fontsize=18) ax.autoscale(enable=True) ax.axis('off') def demag(isa, ax=0): """plot demag of NC/I7/ISA7 model Args: isa: Isa7/NC object """ emag = [e for e in isa.elements if e.is_magnet()] demag = np.array([e.demagnetization(isa.MAGN_TEMPERATURE) for e in emag]) _contour(ax, f'Demagnetization at {isa.MAGN_TEMPERATURE} °C', emag, demag, '-H / kA/m', isa) logger.info("Max demagnetization %f", np.max(demag)) def demag_pos(isa, pos, icur=-1, ibeta=-1, ax=0): """plot demag of NC/I7/ISA7 model at rotor position Args: isa: Isa7/NC object pos: rotor position in degree icur: cur amplitude index or last index if -1 ibeta: beta angle index or last index if -1 """ emag = [e for e in isa.elements if e.is_magnet()] demag = np.array([isa.demagnetization(e, icur, ibeta)[1] for e in emag]) for i, x in enumerate(isa.pos_el_fe_induction): if x >= pos/180*np.pi: break hpol = demag[:, i] hpol[hpol == 0] = np.nan _contour(ax, f'Demagnetization at Pos. {round(x/np.pi*180)}° ({isa.MAGN_TEMPERATURE} °C)', emag, hpol, '-H / kA/m', isa) logger.info("Max demagnetization %f kA/m", np.nanmax(hpol)) def flux_density(isa, subreg=[], ax=0): """plot flux density of NC/I7/ISA7 model Args: isa: Isa7/NC object """ if subreg: if isinstance(subreg, list): sr = subreg else: sr = [subreg] elements = [e for s in sr for se in isa.get_subregion(s).elements() for e in se] else: elements = [e for e in isa.elements] fluxd = np.array([np.linalg.norm(e.flux_density()) for e in elements]) _contour(ax, f'Flux Density T', elements, fluxd) logger.info("Max flux dens %f", np.max(fluxd)) def loss_density(isa, subreg=[], ax=0): """plot loss density of NC/I7/ISA7 model Args: isa: Isa7/NC object """ if subreg: if isinstance(subreg, list): sr = subreg else: sr = [subreg] elements = [e for s in sr for sre in isa.get_subregion(s).elements() for e in sre] else: elements = [e for e in isa.elements] lossd = np.array([e.loss_density*1e-3 for e in elements]) _contour(ax, 'Loss Density kW/m³', elements, lossd) def mmf(f, title='', ax=0): """plot magnetomotive force (mmf) of winding""" if ax == 0: ax = plt.gca() if title: ax.set_title(title) ax.plot(np.array(f['pos'])/np.pi*180, f['mmf']) ax.plot(np.array(f['pos_fft'])/np.pi*180, f['mmf_fft']) ax.set_xlabel('Position / Deg') phi = [f['alfa0']/np.pi*180, f['alfa0']/np.pi*180] y = [min(f['mmf_fft']), 1.1*max(f['mmf_fft'])] ax.plot(phi, y, '--') alfa0 = round(f['alfa0']/np.pi*180, 3) ax.text(phi[0]/2, y[0]+0.05, f"{alfa0}°", ha="center", va="bottom") ax.annotate(f"", xy=(phi[0], y[0]), xytext=(0, y[0]), arrowprops=dict(arrowstyle="->")) ax.grid() def mmf_fft(f, title='', mmfmin=1e-2, ax=0): """plot winding mmf harmonics""" if ax == 0: ax = plt.gca() if title: ax.set_title(title) else: ax.set_title('MMF Harmonics') ax.grid(True) order, mmf = np.array([(n, m) for n, m in zip(f['nue'], f['mmf_nue']) if m > mmfmin]).T try: markerline1, stemlines1, _ = ax.stem(order, mmf, '-.', basefmt=" ", use_line_collection=True) ax.set_xticks(order) except ValueError: # empty sequence pass def zoneplan(wdg, ax=0): """plot zone plan of winding wdg""" from matplotlib.patches import Rectangle upper, lower = wdg.zoneplan() Qb = len([n for l in upper for n in l]) from femagtools.windings import coil_color rh = 0.5 if lower: yl = rh ymax = 2*rh + 0.2 else: yl = 0 ymax = rh + 0.2 if ax == 0: ax = plt.gca() ax.axis('off') ax.set_xlim([-0.5, Qb-0.5]) ax.set_ylim([0, ymax]) ax.set_aspect(Qb/6+0.3) for i, p in enumerate(upper): for x in p: ax.add_patch(Rectangle((abs(x)-1.5, yl), 1, rh, facecolor=coil_color[i], edgecolor='white', fill=True)) s = f'+{i+1}' if x > 0 else f'-{i+1}' ax.text(abs(x)-1, yl+rh/2, s, color='black', ha="center", va="center") for i, p in enumerate(lower): for x in p: ax.add_patch(Rectangle((abs(x)-1.5, yl-rh), 1, rh, facecolor=coil_color[i], edgecolor='white', fill=True)) s = f'+{i+1}' if x > 0 else f'-{i+1}' ax.text(abs(x)-1, yl-rh/2, s, color='black', ha="center", va="center") yu = yl+rh step = 1 if Qb < 25 else 2 if lower: yl -= rh margin = 0.05 ax.text(-0.5, yu+margin, f'Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}', ha='left', va='bottom', size=15) for i in range(0, Qb, step): ax.text(i, yl-margin, f'{i+1}', ha="center", va="top") def winding_factors(wdg, n=8, ax=0): """plot winding factors""" ax = plt.gca() ax.set_title(f'Winding factors Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}') ax.grid(True) order, kwp, kwd, kw = np.array([(n, k1, k2, k3) for n, k1, k2, k3 in zip(wdg.kw_order(n), wdg.kwp(n), wdg.kwd(n), wdg.kw(n))]).T try: markerline1, stemlines1, _ = ax.stem(order-1, kwp, 'C1:', basefmt=" ", markerfmt='C1.', use_line_collection=True, label='Pitch') markerline2, stemlines2, _ = ax.stem(order+1, kwd, 'C2:', basefmt=" ", markerfmt='C2.', use_line_collection=True, label='Distribution') markerline3, stemlines3, _ = ax.stem(order, kw, 'C0-', basefmt=" ", markerfmt='C0o', use_line_collection=True, label='Total') ax.set_xticks(order) ax.legend() except ValueError: # empty sequence pass def winding(wdg, ax=0): """plot coils of windings wdg""" from matplotlib.patches import Rectangle from matplotlib.lines import Line2D from femagtools.windings import coil_color coil_len = 25 coil_height = 4 dslot = 8 arrow_head_length = 2 arrow_head_width = 2 if ax == 0: ax = plt.gca() z = wdg.zoneplan() xoff = 0 if z[-1]: xoff = 0.75 yd = dslot*wdg.yd mh = 2*coil_height/yd slots = sorted([abs(n) for m in z[0] for n in m]) smax = slots[-1]*dslot for n in slots: x = n*dslot ax.add_patch(Rectangle((x + dslot/4, 1), dslot / 2, coil_len - 2, fc="lightblue")) ax.text(x, coil_len / 2, str(n), horizontalalignment="center", verticalalignment="center", backgroundcolor="white", bbox=dict(boxstyle='circle,pad=0', fc="white", lw=0)) line_thickness = [0.6, 1.2] for i, layer in enumerate(z): b = -xoff if i else xoff lw = line_thickness[i] for m, mslots in enumerate(layer): for k in mslots: x = abs(k) * dslot + b xpoints = [] ypoints = [] if (i == 0 and (k > 0 or (k < 0 and wdg.l > 1))): # first layer, positive dir or neg. dir and 2-layers: # from right bottom if x + yd > smax+b: dx = dslot if yd > dslot else yd/4 xpoints = [x + yd//2 + dx - xoff] ypoints = [-coil_height + mh*dx] xpoints += [x + yd//2 - xoff, x, x, x + yd//2-xoff] ypoints += [-coil_height, 0, coil_len, coil_len+coil_height] if x + yd > smax+b: xpoints += [x + yd//2 + dx - xoff] ypoints += [coil_len+coil_height - mh*dx] else: # from left bottom if x - yd < 0: # and x - yd/2 > -3*dslot: dx = dslot if yd > dslot else yd/4 xpoints = [x - yd//2 - dx + xoff] ypoints = [- coil_height + mh*dx] xpoints += [x - yd//2+xoff, x, x, x - yd/2+xoff] ypoints += [-coil_height, 0, coil_len, coil_len+coil_height] if x - yd < 0: # and x - yd > -3*dslot: xpoints += [x - yd//2 - dx + xoff] ypoints += [coil_len + coil_height - mh*dx] ax.add_line(Line2D(xpoints, ypoints, color=coil_color[m], lw=lw)) if k > 0: h = arrow_head_length y = coil_len * 0.8 else: h = -arrow_head_length y = coil_len * 0.2 ax.arrow(x, y, 0, h, length_includes_head=True, head_starts_at_zero=False, head_length=arrow_head_length, head_width=arrow_head_width, fc=coil_color[m], lw=0) if False: # TODO show winding connections m = 0 for k in [n*wdg.Q/wdg.p/wdg.m + 1 for n in range(wdg.m)]: if k < len(slots): x = k * dslot + b + yd/2 - xoff ax.add_line(Line2D([x, x], [-2*coil_height, -coil_height], color=coil_color[m], lw=lw)) ax.text(x, -2*coil_height+0.5, str(m+1), color=coil_color[m]) m += 1 ax.autoscale(enable=True) ax.set_axis_off() def main(): import io import sys import argparse from .__init__ import __version__ from femagtools.bch import Reader argparser = argparse.ArgumentParser( description='Read BCH/BATCH/PLT file and create a plot') argparser.add_argument('filename', help='name of BCH/BATCH/PLT file') argparser.add_argument( "--version", "-v", action="version", version="%(prog)s {}, Python {}".format(__version__, sys.version), help="display version information", ) args = argparser.parse_args() if not matplotlibversion: sys.exit(0) if not args.filename: sys.exit(0) ext = args.filename.split('.')[-1].upper() if ext.startswith('MC'): import femagtools.mcv mcv = femagtools.mcv.read(sys.argv[1]) if mcv['mc1_type'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV): ncols = 2 else: # Permanent Magnet ncols = 1 fig, ax = plt.subplots(nrows=1, ncols=ncols, figsize=(10, 6)) if ncols > 1: plt.subplot(1, 2, 1) mcv_hbj(mcv) plt.subplot(1, 2, 2) mcv_muer(mcv) else: mcv_hbj(mcv, log=False) fig.tight_layout() fig.subplots_adjust(top=0.94) plt.show() return if ext.startswith('PLT'): import femagtools.forcedens fdens = femagtools.forcedens.read(args.filename) cols = 1 rows = 2 fig, ax = plt.subplots(nrows=rows, ncols=cols, figsize=(10, 10*rows)) title = '{}, Rotor position {}'.format( fdens.title, fdens.positions[0]['position']) pos = fdens.positions[0]['X'] FT_FN = (fdens.positions[0]['FT'], fdens.positions[0]['FN']) plt.subplot(rows, cols, 1) forcedens(title, pos, FT_FN) title = 'Force Density Harmonics' plt.subplot(rows, cols, 2) forcedens_fft(title, fdens) # fig.tight_layout(h_pad=3.5) # if title: # fig.subplots_adjust(top=0.92) plt.show() return bchresults = Reader() with io.open(args.filename, encoding='latin1', errors='ignore') as f: bchresults.read(f.readlines()) if (bchresults.type.lower().find( 'pm-synchronous-motor simulation') >= 0 or bchresults.type.lower().find( 'permanet-magnet-synchronous-motor') >= 0 or bchresults.type.lower().find( 'simulation pm/universal-motor') >= 0): pmrelsim(bchresults, bchresults.filename) elif bchresults.type.lower().find( 'multiple calculation of forces and flux') >= 0: multcal(bchresults, bchresults.filename) elif bchresults.type.lower().find('cogging calculation') >= 0: cogging(bchresults, bchresults.filename) elif bchresults.type.lower().find('ld-lq-identification') >= 0: ldlq(bchresults) elif bchresults.type.lower().find('psid-psiq-identification') >= 0: psidq(bchresults) elif bchresults.type.lower().find('fast_torque calculation') >= 0: fasttorque(bchresults) elif bchresults.type.lower().find('transient sc') >= 0: transientsc(bchresults, bchresults.filename) else: raise ValueError("BCH type {} not yet supported".format( bchresults.type)) plt.show() def characteristics(char, title=''): fig, axs = plt.subplots(2, 2, figsize=(10, 8), sharex=True) if title: fig.suptitle(title) n = np.array(char['n'])*60 pmech = np.array(char['pmech'])*1e-3 axs[0, 0].plot(n, np.array(char['T']), 'C0-', label='Torque') axs[0, 0].set_ylabel("Torque / Nm") axs[0, 0].grid() axs[0, 0].legend(loc='center left') ax1 = axs[0, 0].twinx() ax1.plot(n, pmech, 'C1-', label='P mech') ax1.set_ylabel("Power / kW") ax1.legend(loc='lower center') axs[0, 1].plot(n[1:], np.array(char['u1'][1:]), 'C0-', label='Voltage') axs[0, 1].set_ylabel("Voltage / V",) axs[0, 1].grid() axs[0, 1].legend(loc='center left') ax2 = axs[0, 1].twinx() ax2.plot(n[1:], char['cosphi'][1:], 'C1-', label='Cos Phi') ax2.set_ylabel("Cos Phi") ax2.legend(loc='lower right') if 'id' in char: axs[1, 0].plot(n, np.array(char['id']), label='Id') if 'iq' in char: axs[1, 0].plot(n, np.array(char['iq']), label='Iq') axs[1, 0].plot(n, np.array(char['i1']), label='I1') axs[1, 0].set_xlabel("Speed / rpm") axs[1, 0].set_ylabel("Current / A") axs[1, 0].legend(loc='center left') if 'beta' in char: ax3 = axs[1, 0].twinx() ax3.plot(n, char['beta'], 'C3-', label='Beta') ax3.set_ylabel("Beta / °") ax3.legend(loc='center right') axs[1, 0].grid() plfe = np.array(char['plfe'])*1e-3 plcu = np.array(char['plcu'])*1e-3 pl = np.array(char['losses'])*1e-3 axs[1, 1].plot(n, plcu, 'C0-', label='Cu Losses') axs[1, 1].plot(n, plfe, 'C1-', label='Fe Losses') axs[1, 1].set_ylabel("Losses / kW") axs[1, 1].legend(loc='center left') axs[1, 1].grid() axs[1, 1].set_xlabel("Speed / rpm") ax4 = axs[1, 1].twinx() ax4.plot(n[1:-1], char['eta'][1:-1], 'C3-', label="Eta") ax4.legend(loc='upper center') ax4.set_ylabel("Efficiency") fig.tight_layout() if __name__ == "__main__": logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s') main()
SEMAFORInformatik/femagtools
femagtools/plot.py
Python
bsd-2-clause
54,354
import {Component, NgModule} from '@angular/core'; import {BrowserModule} from '@angular/platform-browser'; @Component({ selector: 'application', template: `<div>Hello!</div>` }) export class BasicInlineComponent {} @NgModule({ imports: [BrowserModule], declarations: [BasicInlineComponent], bootstrap: [BasicInlineComponent], }) export class BasicInlineModule {}
clbond/angular-ssr
source/test/fixtures/application-basic-inline.ts
TypeScript
bsd-2-clause
377
# -*- coding: utf-8 -*- from __future__ import (absolute_import, division, print_function) from . import _wrap_numbers, Symbol, Number, Matrix def symbols(s): """ mimics sympy.symbols """ tup = tuple(map(Symbol, s.replace(',', ' ').split())) if len(tup) == 1: return tup[0] else: return tup def symarray(prefix, shape): import numpy as np arr = np.empty(shape, dtype=object) for index in np.ndindex(shape): arr[index] = Symbol('%s_%s' % ( prefix, '_'.join(map(str, index)))) return arr def lambdify(args, exprs): """ lambdify mimics sympy.lambdify """ try: nargs = len(args) except TypeError: args = (args,) nargs = 1 try: nexprs = len(exprs) except TypeError: exprs = (exprs,) nexprs = 1 @_wrap_numbers def f(*inp): if len(inp) != nargs: raise TypeError("Incorrect number of arguments") try: len(inp) except TypeError: inp = (inp,) subsd = dict(zip(args, inp)) return [expr.subs(subsd).evalf() for expr in exprs][ 0 if nexprs == 1 else slice(None)] return f class Lambdify(object): """ Lambdify mimics symengine.Lambdify """ def __init__(self, syms, exprs): self.syms = syms self.exprs = exprs def __call__(self, inp, out=None): inp = tuple(map(Number.make, inp)) subsd = dict(zip(self.syms, inp)) def _eval(expr_iter): return [expr.subs(subsd).evalf() for expr in expr_iter] exprs = self.exprs if out is not None: try: out.flat = _eval(exprs.flatten()) except AttributeError: out.flat = _eval(exprs) elif isinstance(exprs, Matrix): import numpy as np nr, nc = exprs.nrows, exprs.ncols out = np.empty((nr, nc)) for ri in range(nr): for ci in range(nc): out[ri, ci] = exprs._get_element( ri*nc + ci).subs(subsd).evalf() return out # return Matrix(nr, nc, _eval(exprs._get_element(i) for # i in range(nr*nc))) elif hasattr(exprs, 'reshape'): # NumPy like container: container = exprs.__class__(exprs.shape, dtype=float, order='C') container.flat = _eval(exprs.flatten()) return container else: return _eval(exprs)
bjodah/pysym
pysym/util.py
Python
bsd-2-clause
2,569
const maps = require('source-map-support'); maps.install({environment: 'node'});
clbond/angular-ssr
source/application/compiler/webpack/source-map.ts
TypeScript
bsd-2-clause
81
// Copyright (C) 2015 the V8 project authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /*--- esid: sec-array.from es6id: 22.1.2.1 description: Value returned by mapping function (traversed via iterator) info: | [...] 2. If mapfn is undefined, let mapping be false. 3. else a. If IsCallable(mapfn) is false, throw a TypeError exception. b. If thisArg was supplied, let T be thisArg; else let T be undefined. c. Let mapping be true [...] 6. If usingIterator is not undefined, then [...] g. Repeat [...] vii. If mapping is true, then 1. Let mappedValue be Call(mapfn, T, «nextValue, k»). 2. If mappedValue is an abrupt completion, return IteratorClose(iterator, mappedValue). 3. Let mappedValue be mappedValue.[[value]]. features: [Symbol.iterator] ---*/ var thisVals = []; var nextResult = { done: false, value: {} }; var nextNextResult = { done: false, value: {} }; var firstReturnVal = {}; var secondReturnVal = {}; var mapFn = function(value, idx) { var returnVal = nextReturnVal; nextReturnVal = nextNextReturnVal; nextNextReturnVal = null; return returnVal; }; var nextReturnVal = firstReturnVal; var nextNextReturnVal = secondReturnVal; var items = {}; var result; items[Symbol.iterator] = function() { return { next: function() { var result = nextResult; nextResult = nextNextResult; nextNextResult = { done: true }; return result; } }; }; result = Array.from(items, mapFn); assert.sameValue(result.length, 2); assert.sameValue(result[0], firstReturnVal); assert.sameValue(result[1], secondReturnVal);
sebastienros/jint
Jint.Tests.Test262/test/built-ins/Array/from/iter-map-fn-return.js
JavaScript
bsd-2-clause
1,769
package com.mithos.bfg.loop; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.event.MouseWheelEvent; /** * This class is an adapter for {@link OnEvent}. All methods do * nothing and return true, so you need only implement the methods * that you need to. * @author James McMahon * */ public class OnEventAdapter implements OnEvent { @Override public boolean keyPressed(KeyEvent e) { return true; } @Override public boolean keyReleased(KeyEvent e) { return true; } @Override public boolean mousePressed(MouseEvent e) { return true; } @Override public boolean mouseMoved(MouseEvent e) { return true; } @Override public boolean mouseReleased(MouseEvent e) { return true; } @Override public boolean mouseWheel(MouseWheelEvent e) { return true; } }
James1345/bfg
src/com/mithos/bfg/loop/OnEventAdapter.java
Java
bsd-2-clause
821
using Esprima.Ast; namespace Jint.Runtime.Interpreter { /// <summary> /// Per Engine.Evalute() call context. /// </summary> internal sealed class EvaluationContext { public EvaluationContext(Engine engine, in Completion? resumedCompletion = null) { Engine = engine; DebugMode = engine._isDebugMode; ResumedCompletion = resumedCompletion ?? default; // TODO later OperatorOverloadingAllowed = engine.Options.Interop.AllowOperatorOverloading; } public Engine Engine { get; } public Completion ResumedCompletion { get; } public bool DebugMode { get; } public Node LastSyntaxNode { get; set; } public bool OperatorOverloadingAllowed { get; } } }
sebastienros/jint
Jint/Runtime/Interpreter/EvaluationContext.cs
C#
bsd-2-clause
780
log.enableAll(); (function(){ function animate() { requestAnimationFrame(animate); TWEEN.update(); } animate(); })(); var transform = getStyleProperty('transform'); var getStyle = ( function() { var getStyleFn = getComputedStyle ? function( elem ) { return getComputedStyle( elem, null ); } : function( elem ) { return elem.currentStyle; }; return function getStyle( elem ) { var style = getStyleFn( elem ); if ( !style ) { log.error( 'Style returned ' + style + '. Are you running this code in a hidden iframe on Firefox? ' + 'See http://bit.ly/getsizebug1' ); } return style; }; })(); var cache = { imgW: 5100, imgH: 852, panOffsetX: 0, ring: 0, deg: 0, runDeg: 0, minOffsetDeg: 8, rotationOffsetDeg: 0, onceRotationOffsetDeg: 0, nowOffset: 0, len: 0, touchLock: false, timer: null }; var tween1, tween2; var util = { setTranslateX: function setTranslateX(el, num) { el.style[transform] = "translate3d(" + num + "px,0,0)"; } }; var initPanoramaBox = function initPanoramaBox($el, opts) { var elH = $el.height(); var elW = $el.width(); var $panoramaBox = $('<div class="panorama-box">' + '<div class="panorama-item"></div>' + '<div class="panorama-item"></div>' + '</div>'); var $panoramaItem = $('.panorama-item', $panoramaBox); var scal = elH / opts.height; $panoramaItem.css({ width: opts.width, height: opts.height }); $panoramaBox.css({ width: elW / scal, height: opts.height, transform: 'scale3d(' + scal + ',' + scal + ',' + scal + ')', 'transform-origin': '0 0' }); util.setTranslateX($panoramaItem.get(0), 0); util.setTranslateX($panoramaItem.get(1), -opts.width); $el.append($panoramaBox); var offset = function offset(num) { var width = opts.width; var num1 = num % opts.width; var num2; if (num1 < -width / 2) { num2 = width + num1 - 2; } else { num2 = -width + num1 + 2; } util.setTranslateX($panoramaItem.get(0), num1); util.setTranslateX($panoramaItem.get(1), num2); }; var run = function (subBox1, subBox2, width) { return function offset(num) { num = parseInt(num); cache.len = num; var num1 = num % width; var num2; if (num1 < -width / 2) { num2 = width + num1 - 1; } else { num2 = -width + num1 + 2; } util.setTranslateX(subBox1, num1); util.setTranslateX(subBox2, num2); }; }; return run($panoramaItem.get(0), $panoramaItem.get(1), opts.width); }; var $el = {}; $el.main = $('.wrapper'); var offset = initPanoramaBox($el.main, { width: cache.imgW, height: cache.imgH }); var animOffset = function animOffset(length){ if(tween1){ tween1.stop(); } tween1 = new TWEEN.Tween({x: cache.len}); tween1.to({x: length}, 600); tween1.onUpdate(function(){ offset(this.x); }); tween1.start(); }; var animPanEnd = function animPanEnd(velocityX){ if(tween2){ tween2.stop(); } var oldLen = cache.len; var offsetLen ; tween2 = new TWEEN.Tween({x: cache.len}); tween2.to({x: cache.len - 200 * velocityX}, 600); tween2.easing(TWEEN.Easing.Cubic.Out); tween2.onUpdate(function(){ offset(this.x); offsetLen =oldLen - this.x; cache.nowOffset += + offsetLen; cache.panOffsetX += + offsetLen; }); tween2.start(); }; var initOrientationControl = function () { FULLTILT.getDeviceOrientation({'type': 'world'}) .then(function (orientationControl) { var orientationFunc = function orientationFunc() { var screenAdjustedEvent = orientationControl.getScreenAdjustedEuler(); cache.navDeg = 360 - screenAdjustedEvent.alpha; if (cache.navDeg > 270 && cache.navOldDeg < 90) { cache.ring -= 1; } else if (cache.navDeg < 90 && cache.navOldDeg > 270) { cache.ring += 1; } cache.navOldDeg = cache.navDeg; cache.oldDeg = cache.deg; cache.deg = cache.ring * 360 + cache.navDeg; var offsetDeg = cache.deg - cache.runDeg; if (!cache.touchLock && (Math.abs(offsetDeg) > cache.minOffsetDeg)) { var length = cache.imgW / 360 * -(cache.deg - cache.rotationOffsetDeg) + cache.panOffsetX; cache.runDeg = cache.deg; cache.nowOffset = length; animOffset(length); } }; orientationControl.listen(orientationFunc); }) .catch(function(e){ log.error(e); }); }; var initTouch = function(){ var mc = new Hammer.Manager($el.main.get(0)); var pan = new Hammer.Pan(); $el.main.on('touchstart', function (evt) { if (cache.timer) { clearTimeout(cache.timer); cache.timer = null; } cache.touchLock = true; if(tween1){ tween1.stop(); } if(tween2){ tween2.stop(); } cache.nowOffset = cache.len; }); $el.main.on('touchend', function (evt) { cache.timer = setTimeout(function () { cache.onceRotationOffsetDeg = cache.deg - cache.runDeg; cache.runDeg = cache.deg + cache.onceRotationOffsetDeg; cache.rotationOffsetDeg = cache.rotationOffsetDeg + cache.onceRotationOffsetDeg; cache.touchLock = false; }, 1000); }); mc.add(pan); mc.on('pan', function (evt) { offset(cache.nowOffset + evt.deltaX); }); mc.on('panend', function (evt) { cache.nowOffset += + evt.deltaX; cache.panOffsetX += + evt.deltaX; //animPanEnd(evt.velocityX); }); }; initTouch(); initOrientationControl();
wushuyi/panorama360
assets/js/functions_bak.js
JavaScript
bsd-2-clause
6,239
// Copyright (c) 2022, WNProject Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "WNNetworking/inc/WNReliableNetworkTransportSocket.h" #include "WNNetworking/inc/WNReliableNetworkListenSocket.h" #include <netdb.h> #include <netinet/in.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/uio.h> namespace wn { namespace networking { network_error WNReliableNetworkTransportSocket::connect_to(logging::log* _log, const containers::string_view& target, uint32_t _connection_type, uint16_t _port) { char port_array[11] = {0}; memory::writeuint32(port_array, _port, 10); addrinfo* result; addrinfo* ptr; if (0 != getaddrinfo(target.to_string(m_allocator).c_str(), port_array, nullptr, &result)) { _log->log_error("Could not resolve local port ", port_array); return network_error::could_not_resolve; } ptr = result; for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) { if ((_connection_type == 0xFFFFFFFF && (ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)) || ptr->ai_family == static_cast<int>(_connection_type)) { m_sock_fd = socket(ptr->ai_family, SOCK_STREAM, IPPROTO_TCP); if (m_sock_fd == -1) { continue; } if (0 != connect(m_sock_fd, ptr->ai_addr, ptr->ai_addrlen)) { ::close(m_sock_fd); m_sock_fd = -1; continue; } break; } } freeaddrinfo(result); if (ptr == nullptr) { _log->log_error("Could not resolve target ", target, ":", port_array); return network_error::could_not_resolve; } return network_error::ok; } network_error WNReliableNetworkTransportSocket::do_send( const send_ranges& _buffers) { iovec* send_buffers = static_cast<iovec*>(WN_STACK_ALLOC(sizeof(iovec) * _buffers.size())); size_t total_bytes = 0; for (size_t i = 0; i < _buffers.size(); ++i) { total_bytes += _buffers[i].size(); send_buffers[i].iov_base = const_cast<void*>(static_cast<const void*>(_buffers[i].data())); send_buffers[i].iov_len = _buffers[i].size(); } using iovlen_type = decltype(msghdr().msg_iovlen); msghdr header = {nullptr, // msg_name 0, // msg_namelen send_buffers, // msg_iov static_cast<iovlen_type>(_buffers.size()), // msg_iovlen nullptr, // msg_control 0, // msg_controllen 0}; ssize_t num_sent = 0; if (0 > (num_sent = sendmsg(m_sock_fd, &header, 0))) { return network_error::could_not_send; } if (num_sent != static_cast<ssize_t>(total_bytes)) { return network_error::could_not_send; ::close(m_sock_fd); m_sock_fd = -1; } return network_error::ok; } WNReceiveBuffer WNReliableNetworkTransportSocket::recv_sync() { WNReceiveBuffer buffer(m_manager->acquire_buffer()); ssize_t received = 0; if (0 >= (received = recv(m_sock_fd, buffer.data.data(), buffer.data.size(), 0))) { return WNReceiveBuffer(network_error::could_not_receive); } buffer.data = containers::contiguous_range<char>(buffer.data.data(), received); return buffer; } } // namespace networking } // namespace wn
WNProject/WNFramework
Overlays/Posix/Libraries/WNNetworking/src/WNReliableNetworkTransportSocket.cpp
C++
bsd-2-clause
3,381
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information. #ifndef EAVL_SCENE_RENDERER_RT_H #define EAVL_SCENE_RENDERER_RT_H #include "eavlDataSet.h" #include "eavlCellSet.h" #include "eavlColor.h" #include "eavlColorTable.h" #include "eavlSceneRenderer.h" #include "eavlRayTracerMutator.h" #include "eavlTimer.h" // **************************************************************************** // Class: eavlSceneRendererRT // // Purpose: /// /// // // Programmer: Matt Larsen // Creation: July 17, 2014 // // Modifications: // // **************************************************************************** class eavlSceneRendererRT : public eavlSceneRenderer { private: eavlRayTracerMutator* tracer; bool canRender; bool setLight; string ctName; float pointRadius; float lineWidth; public: eavlSceneRendererRT() { tracer = new eavlRayTracerMutator(); tracer->setDepth(1); // /tracer->setVerbose(true); tracer->setAOMax(5); tracer->setOccSamples(4); tracer->setAO(true); tracer->setBVHCache(false); // don't use cache tracer->setCompactOp(false); tracer->setShadowsOn(true); setLight = true; ctName = ""; tracer->setDefaultMaterial(Ka,Kd,Ks); pointRadius = .1f; lineWidth = .05f; } ~eavlSceneRendererRT() { delete tracer; } void SetPointRadius(float r) { if(r > 0) pointRadius = r; } void SetBackGroundColor(float r, float g, float b) { tracer->setBackgroundColor(r,g,b); } virtual void SetActiveColor(eavlColor c) { glColor3fv(c.c); glDisable(GL_TEXTURE_1D); //cout<<"Setting Active Color"<<endl; } virtual void SetActiveColorTable(eavlColorTable ct) { eavlSceneRenderer::SetActiveColorTable(ct); if(ct.GetName()!=ctName) { ctName=ct.GetName(); tracer->setColorMap3f(colors,ncolors); //cout<<"Setting Active Color Table"<<endl; } } virtual void StartScene() { //cout<<"Calling Start scene"<<endl; //tracer->startScene(); } // ------------------------------------------------------------------------ virtual void StartTriangles() { //cout<<"Calling Start Tris"<<endl; tracer->startScene(); } virtual void EndTriangles() { //cout<<"Calling End Tris"<<endl; } virtual void AddTriangleVnVs(double x0, double y0, double z0, double x1, double y1, double z1, double x2, double y2, double z2, double u0, double v0, double w0, double u1, double v1, double w1, double u2, double v2, double w2, double s0, double s1, double s2) { tracer->scene->addTriangle(eavlVector3(x0,y0,z0) , eavlVector3(x1,y1,z1), eavlVector3(x2,y2,z2), eavlVector3(u0,v0,w0) , eavlVector3(u1,v1,w1), eavlVector3(u2,v2,w2), s0,s1,s2, "default"); } // ------------------------------------------------------------------------ virtual void StartPoints() { tracer->startScene(); } virtual void EndPoints() { //glEnd(); } virtual void AddPointVs(double x, double y, double z, double r, double s) { tracer->scene->addSphere(pointRadius,x,y,z,s,"default"); } // ------------------------------------------------------------------------ virtual void StartLines() { tracer->startScene(); } virtual void EndLines() { //glEnd(); } virtual void AddLineVs(double x0, double y0, double z0, double x1, double y1, double z1, double s0, double s1) { //cout<<"ADDING LINE"<<endl; tracer->scene->addLine(lineWidth, eavlVector3(x0,y0,z0),s0, eavlVector3(x1,y1,z1),s1 ); } // ------------------------------------------------------------------------ virtual void Render() { int tframe = eavlTimer::Start(); tracer->setDefaultMaterial(Ka,Kd,Ks); tracer->setResolution(view.h,view.w); float magnitude=tracer->scene->getSceneExtentMagnitude(); tracer->setAOMax(magnitude*.2f); /*Set up field of view: tracer takes the half FOV in degrees*/ float fovx= 2.f*atan(tan(view.view3d.fov/2.f)*view.w/view.h); fovx*=180.f/M_PI; tracer->setFOVy((view.view3d.fov*(180.f/M_PI))/2.f); tracer->setFOVx( fovx/2.f ); tracer->setZoom(view.view3d.zoom); eavlVector3 lookdir = (view.view3d.at - view.view3d.from).normalized(); eavlVector3 right = (lookdir % view.view3d.up).normalized(); /* Tracer is a lefty, so this is flip so down is not up */ eavlVector3 up = ( lookdir % right).normalized(); tracer->lookAtPos(view.view3d.at.x,view.view3d.at.y,view.view3d.at.z); tracer->setCameraPos(view.view3d.from.x,view.view3d.from.y,view.view3d.from.z); tracer->setUp(up.x,up.y,up.z); /*Otherwise the light will move with the camera*/ if(eyeLight)//setLight) { eavlVector3 minersLight(view.view3d.from.x,view.view3d.from.y,view.view3d.from.z); minersLight = minersLight+ up*magnitude*.3f; tracer->setLightParams(minersLight.x,minersLight.y,minersLight.z, 1.f, 1.f, 0.f, 0.f); /*Light params: intensity, constant, linear and exponential coefficeints*/ } else { tracer->setLightParams(Lx, Ly, Lz, 1.f, 1.f , 0.f , 0.f); } tracer->Execute(); cerr<<"\nTotal Frame Time : "<<eavlTimer::Stop(tframe,"")<<endl; } virtual unsigned char *GetRGBAPixels() { return (unsigned char *) tracer->getFrameBuffer()->GetHostArray(); } virtual float *GetDepthPixels() { float proj22=view.P(2,2); float proj23=view.P(2,3); float proj32=view.P(3,2); return (float *) tracer->getDepthBuffer(proj22,proj23,proj32)->GetHostArray(); } }; #endif
jsmeredith/EAVL
src/rendering/eavlSceneRendererRT.h
C
bsd-2-clause
6,371
module WavefrontOBJs export loadOBJ, loadMTL, load_obj_mtl, numVertices, numFaces include("geotypes.jl") include("types.jl") include("utils.jl") include("obj.jl") include("material.jl") # convenience for loading OBJ and MTL simultaneously function load_obj_mtl(fpath::ASCIIString) objpath=string(fpath,".obj") mtlpath=string(fpath,".mtl") if !isfile(objpath) error("OBJ file $objpath not found") end if !isfile(mtlpath) error("MTL file $mtlpath not found") end loadOBJ(objpath), loadMTL(mtlpath) end end # module
ericjang/WavefrontOBJs.jl
src/WavefrontOBJs.jl
Julia
bsd-2-clause
540
var _ = require('lodash'); var requireAll = require('require-all'); function load(router, options) { if (_.isString(options)) options = {dirname: options}; return requireAll(_.defaults(options, { filter: /(.*Controller)\.js$/, recursive: true, resolve: function (Controller) { var c = new (Controller.__esModule ? Controller.default : Controller)(); c.register && c.register(router); return c; } })); } module.exports = load;
vvv-v13/express-starter
library/load.js
JavaScript
bsd-2-clause
476
/* * Copyright (c) 2012, JInterval Project. * 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 net.java.jinterval.ir; import com.cflex.util.lpSolve.LpConstant; import com.cflex.util.lpSolve.LpModel; import com.cflex.util.lpSolve.LpSolver; import java.util.ArrayList; //import org.apache.commons.math3.exception.MathIllegalArgumentException; //TODO: Add exceptions and throws public class IRPredictor { private double[][] X; private double[] Y; private double[] E; private boolean dataAreGiven; // Number of observations private int ObsNumber; // Number of variables private int VarNumber; // Storage for predictions private double PredictionMin; private double PredictionMax; private double[] PredictionMins; private double[] PredictionMaxs; // Last error int ExitCode; public IRPredictor(){ ObsNumber = 0; VarNumber = 0; dataAreGiven = false; } public IRPredictor(double[][] X, double[] Y, double[] E){ setData(X,Y,E); } public final void setData(double[][] X, double[] Y, double[] E) // throws IllegalDimensionException { // if(X.length != Y.length || X.length != E.length) // throw IllegalDimensionException; this.X=X; this.Y=Y; this.E=E; ObsNumber = X.length; VarNumber = X[0].length; dataAreGiven = true; } public int getExitCode() { return ExitCode; } private boolean solveLpp(double[] Objective) // throws IllegalDimensionException { if (Objective.length != VarNumber){ // throw IllegalDimensionException; ExitCode = -1; return false; } try { // Init LP Solver LpModel Lpp = new LpModel(0, VarNumber); // Define LPP double[] zObjective = new double[VarNumber+1]; System.arraycopy(Objective, 0, zObjective, 1, VarNumber); Lpp.setObjFn(zObjective); double[] zX=new double[VarNumber+1]; for (int i=0; i<ObsNumber; i++) { System.arraycopy(X[i], 0, zX, 1, VarNumber); Lpp.addConstraint(zX, LpConstant.LE, Y[i]+E[i]); Lpp.addConstraint(zX, LpConstant.GE, Y[i]-E[i]); // Solver.add_constraint(Lpp, zX, constant.LE, Y[i]+E[i]); // Solver.add_constraint(Lpp, zX, constant.GE, Y[i]-E[i]); } //Solver.set_minim(Lpp); //Lpp.setMinimum(); LpSolver Solver = new LpSolver(Lpp); ExitCode = Solver.solve(); // ExitCode = Solver.solve(Lpp); switch ( ExitCode ) { case LpConstant.OPTIMAL: PredictionMin = Lpp.getBestSolution(0); break; case LpConstant.INFEASIBLE: //throw InfeasibleException case LpConstant.UNBOUNDED: //throw UnboundedException } // Solver.set_maxim(Lpp); Lpp.setMaximum(); ExitCode = Solver.solve(); switch ( ExitCode ) { case LpConstant.OPTIMAL: PredictionMax = Lpp.getBestSolution(0); break; case LpConstant.INFEASIBLE: //throw InfeasibleException case LpConstant.UNBOUNDED: //throw UnboundedException } } catch (Exception e){ //e.printStackTrace(); } return ExitCode == LpConstant.OPTIMAL; } public boolean isDataConsistent(){ return solveLpp(X[0]); } public void compressData(){ } public boolean predictAt(double[] x){ return solveLpp(x); } public boolean predictAtEveryDataPoint(){ PredictionMins = new double[ObsNumber]; PredictionMaxs = new double[ObsNumber]; boolean Solved = true; for (int i=0; i<ObsNumber; i++){ Solved = Solved && predictAt(X[i]); if(!Solved) { break; } PredictionMins[i] = getMin(); PredictionMaxs[i] = getMax(); } return Solved; } public double getMin(){ return PredictionMin; } public double getMax(){ return PredictionMax; } public double getMin(int i) { return PredictionMins[i]; } public double getMax(int i) { return PredictionMaxs[i]; } public double[] getMins() { return PredictionMins; } public double[] getMaxs() { return PredictionMaxs; } public double[] getResiduals(){ //Residuals=(y-(vmax+vmin)/2)/beta double v; double[] residuals = new double[ObsNumber]; for(int i=0; i<ObsNumber; i++) { v = (PredictionMins[i]+PredictionMaxs[i])/2; residuals[i] = (Y[i]-v)/E[i]; } return residuals; } public double[] getLeverages(){ //Leverage=((vmax-vmin)/2)/beta double v; double[] leverages = new double[ObsNumber]; for(int i=0; i<ObsNumber; i++) { v = (PredictionMaxs[i]-PredictionMins[i])/2; leverages[i] = v/E[i]; } return leverages; } public int[] getBoundary(){ final double EPSILON = 1.0e-6; ArrayList<Integer> boundary = new ArrayList<Integer>(); double yp, ym, vp, vm; for (int i=0; i<ObsNumber; i++){ yp = Y[i]+E[i]; vp = PredictionMaxs[i]; ym = Y[i]-E[i]; vm = PredictionMins[i]; if ( Math.abs(yp - vp) < EPSILON || Math.abs(ym - vm) < EPSILON ) { boundary.add(1); } else { boundary.add(0); } } int[] a_boundary = new int[boundary.size()]; for (int i=0; i<a_boundary.length; i++){ a_boundary[i] = boundary.get(i).intValue(); } return a_boundary; } public int[] getBoundaryNumbers(){ int Count = 0; int[] boundary = getBoundary(); for (int i=0; i<boundary.length; i++){ if(boundary[i] == 1) { Count++; } } int j = 0; int[] numbers = new int[Count]; for (int i=0; i<boundary.length; i++){ if(boundary[i] == 1) { numbers[j++] = i; } } return numbers; } //TODO: Implement getOutliers() // public int[] getOutliers(){ // // } //TODO: Implement getOutliersNumbers() // public int[] getOutliersNumbers(){ // // } public double[] getOutliersWeights(){ double[] outliers = new double[ObsNumber]; for(int i=0; i<ObsNumber; i++) { outliers[i]=0; } try { LpModel Lpp = new LpModel(0, ObsNumber+VarNumber); // Build and set objective of LPP double[] zObjective = new double[ObsNumber+VarNumber+1]; for(int i=1;i<=VarNumber; i++) { zObjective[i] = 0; } for(int i=1;i<=ObsNumber; i++) { zObjective[VarNumber+i] = 1; } Lpp.setObjFn(zObjective); //Solver.set_minim(Lpp); // Build and set constraints of LPP double[] Row = new double[ObsNumber+VarNumber+1]; for (int i=0; i<ObsNumber; i++) { for (int j=1; j<=VarNumber; j++) { Row[j]=X[i][j-1]; } for(int j=1; j<=ObsNumber; j++) { Row[VarNumber+j] = 0; } Row[VarNumber+i+1] = -E[i]; // Solver.add_constraint(Lpp, Row, constant.LE, Y[i]); Lpp.addConstraint(Row, LpConstant.LE, Y[i]); Row[VarNumber+i+1] = E[i]; // Solver.add_constraint(Lpp, Row, constant.GE, Y[i]); Lpp.addConstraint(Row, LpConstant.GE, Y[i]); for (int j=1; j<=ObsNumber+VarNumber; j++) { Row[j] = 0; } Row[VarNumber+i+1] = 1; // Solver.add_constraint(Lpp, Row, constant.GE, 1); Lpp.addConstraint(Row, LpConstant.GE, 1); } // Solve LPP and get outliers' weights LpSolver Solver = new LpSolver(Lpp); ExitCode = Solver.solve(); for(int i = 0; i < ObsNumber; i++) { outliers[i] = Lpp.getBestSolution(Lpp.getRows()+VarNumber+i+1); } } catch(Exception e){ //e.printStackTrace(); } return outliers; } }
jinterval/jinterval
jinterval-ir/src/main/java/net/java/jinterval/ir/IRPredictor.java
Java
bsd-2-clause
10,164
/* * Copyright (c) 2016-2016, Roland Bock * 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 "compare.h" #include "Sample.h" #include <sqlpp11/sqlpp11.h> #include <iostream> namespace { auto getTrue() -> std::string { MockDb::_serializer_context_t printer = {}; return serialize(sqlpp::value(true), printer).str(); } auto getFalse() -> std::string { MockDb::_serializer_context_t printer = {}; return serialize(sqlpp::value(false), printer).str(); } } // namespace int Where(int, char*[]) { const auto foo = test::TabFoo{}; const auto bar = test::TabBar{}; // Unconditionally compare(__LINE__, select(foo.omega).from(foo).unconditionally(), "SELECT tab_foo.omega FROM tab_foo"); compare(__LINE__, remove_from(foo).unconditionally(), "DELETE FROM tab_foo"); compare(__LINE__, update(foo).set(foo.omega = 42).unconditionally(), "UPDATE tab_foo SET omega=42"); compare(__LINE__, update(foo).set(foo.omega = foo.omega - -1).unconditionally(), "UPDATE tab_foo SET omega=(tab_foo.omega - -1)"); compare(__LINE__, where(sqlpp::value(true)), " WHERE " + getTrue()); // Never compare(__LINE__, where(sqlpp::value(false)), " WHERE " + getFalse()); // Sometimes compare(__LINE__, where(bar.gamma), " WHERE tab_bar.gamma"); compare(__LINE__, where(bar.gamma == false), " WHERE (tab_bar.gamma=" + getFalse() + ")"); compare(__LINE__, where(bar.beta.is_null()), " WHERE (tab_bar.beta IS NULL)"); compare(__LINE__, where(bar.beta == "SQL"), " WHERE (tab_bar.beta='SQL')"); compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null("SQL"))), " WHERE (tab_bar.beta='SQL')"); compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null<sqlpp::text>(::sqlpp::null))), " WHERE (tab_bar.beta IS NULL)"); #if __cplusplus >= 201703L // string_view argument std::string_view sqlString = "SQL"; compare(__LINE__, where(bar.beta == sqlString), " WHERE (tab_bar.beta='SQL')"); #endif return 0; }
rbock/sqlpp11
tests/core/serialize/Where.cpp
C++
bsd-2-clause
3,294
#include <iostream> #include <string> #include <map> #include <unistd.h> #include <utility> #include <sstream> #include "./patricia-tree.hpp" int main(void) { std::cout << "Add new command!\n"; PatriciaTree<Node<std::string, StringKeySpec>> pt; std::string command = "command"; std::string key; while(command != "exit") { getline(std::cin, key); pt.insertNode(key, command); std::cout << pt << "\n"; } return 0; }
giovannicuriel/tinytools
src/c++/patricia-tree-demo.cpp
C++
bsd-2-clause
472
# urlwatch A Puppet module for managing urlwatch and urlwatch cronjobs. This module also supports urlwatch's built-in filtering features (hooks.py). # Module usage Example using Hiera: monitor Trac WikiStart and RecentChanges pages for edits: classes: - urlwatch urlwatch::userconfigs: john: hour: '*' minute: '20' urls: trac_wikistart: url: 'https://trac.example.org/openvpn/wiki/WikiStart' filter: '[0-9]* (year|month|week|day|hour|minute|second)s{0,1} ago' trac_recentchanges: url: 'https://trac.example.org/openvpn/wiki/RecentChanges' filter: '[0-9]* (year|month|week|day|hour|minute|second)s{0,1} ago' If you want the email to user 'john' to go to a public address, you can use the puppetfinland/postfix module: classes: - postfix postfix::mailaliases: john: recipient: '[email protected]' For details please refer to [init.pp](manifests/init.pp) and [userconfig.pp](manifests/userconfig.pp). If you want to use the cron functionality in this module you probably want to set up some mail aliases. One way to do this is to use ::postfix::mailaliases hash parameter in the Puppet-Finland [postfix module](https://github.com/Puppet-Finland/postfix).
Puppet-Finland/urlwatch
README.md
Markdown
bsd-2-clause
1,379
# Add your own choices here! fruit = ["apples", "oranges", "pears", "grapes", "blueberries"] lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"] situations = {"fruit":fruit, "lunch":lunch}
rbracken/internbot
plugins/pick/choices.py
Python
bsd-2-clause
218
/***** includes *****/ #include "lfds720_stack_np_internal.h" /***** private prototypes *****/ static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss, struct lfds720_misc_validation_info *vi, enum lfds720_misc_validity *lfds720_stack_np_validity ); /****************************************************************************/ void lfds720_stack_np_query( struct lfds720_stack_np_state *ss, enum lfds720_stack_np_query query_type, void *query_input, void *query_output ) { LFDS720_PAL_ASSERT( ss != NULL ); // TRD : query_type can be any value in its range LFDS720_MISC_BARRIER_LOAD; switch( query_type ) { case LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT: { ptrdiff_t se; LFDS720_PAL_ASSERT( query_input == NULL ); LFDS720_PAL_ASSERT( query_output != NULL ); *(lfds720_pal_uint_t *) query_output = 0; // TRD : count the elements on the stack_np se = ss->top[LFDS720_MISC_OFFSET]; while( se != 0 ) { ( *(lfds720_pal_uint_t *) query_output )++; se = LFDS720_MISC_OFFSET_TO_POINTER( ss, se, struct lfds720_stack_np_element )->next; } } break; case LFDS720_STACK_NP_QUERY_SINGLETHREADED_VALIDATE: // TRD : query_input can be NULL LFDS720_PAL_ASSERT( query_output != NULL ); lfds720_stack_np_internal_stack_np_validate( ss, (struct lfds720_misc_validation_info *) query_input, (enum lfds720_misc_validity *) query_output ); break; } return; } /****************************************************************************/ static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss, struct lfds720_misc_validation_info *vi, enum lfds720_misc_validity *lfds720_stack_np_validity ) { lfds720_pal_uint_t number_elements = 0; ptrdiff_t se_slow, se_fast; LFDS720_PAL_ASSERT( ss != NULL ); // TRD : vi can be NULL LFDS720_PAL_ASSERT( lfds720_stack_np_validity != NULL ); *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_VALID; se_slow = se_fast = ss->top[LFDS720_MISC_OFFSET]; /* TRD : first, check for a loop we have two pointers both of which start at the top of the stack_np we enter a loop and on each iteration we advance one pointer by one element and the other by two we exit the loop when both pointers are NULL (have reached the end of the stack_np) or if we fast pointer 'sees' the slow pointer which means we have a loop */ if( se_slow != 0 ) do { // se_slow = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_slow ) )->next; se_slow = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_slow, struct lfds720_stack_np_element )->next; if( se_fast != 0 ) // se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next; se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next; if( se_fast != 0 ) // se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next; se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next; } while( se_slow != 0 and se_fast != se_slow ); if( se_fast != 0 and se_slow != 0 and se_fast == se_slow ) *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_LOOP; /* TRD : now check for expected number of elements vi can be NULL, in which case we do not check we know we don't have a loop from our earlier check */ if( *lfds720_stack_np_validity == LFDS720_MISC_VALIDITY_VALID and vi != NULL ) { lfds720_stack_np_query( ss, LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT, NULL, (void *) &number_elements ); if( number_elements < vi->min_elements ) *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_MISSING_ELEMENTS; if( number_elements > vi->max_elements ) *lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_ADDITIONAL_ELEMENTS; } return; }
grz0zrg/fas
lib/liblfds7.2.0/src/liblfds720/src/lfds720_stack_nodeallocate_positionindependent/lfds720_stack_np_query.c
C
bsd-2-clause
4,484
/* * 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.properties; import com.jme3.gde.core.scene.SceneApplication; import com.jme3.scene.Spatial; import java.beans.PropertyEditor; import java.lang.reflect.InvocationTargetException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.logging.Level; import java.util.logging.Logger; import org.openide.nodes.PropertySupport; import org.openide.util.Exceptions; /** * * @author normenhansen */ public class UserDataProperty extends PropertySupport.ReadWrite<String> { private Spatial spatial; private String name = "null"; private int type = 0; private List<ScenePropertyChangeListener> listeners = new LinkedList<ScenePropertyChangeListener>(); public UserDataProperty(Spatial node, String name) { super(name, String.class, name, ""); this.spatial = node; this.name = name; this.type = getObjectType(node.getUserData(name)); } public static int getObjectType(Object type) { if (type instanceof Integer) { return 0; } else if (type instanceof Float) { return 1; } else if (type instanceof Boolean) { return 2; } else if (type instanceof String) { return 3; } else if (type instanceof Long) { return 4; } else { Logger.getLogger(UserDataProperty.class.getName()).log(Level.WARNING, "UserData not editable" + (type == null ? "null" : type.getClass())); return -1; } } @Override public String getValue() throws IllegalAccessException, InvocationTargetException { return spatial.getUserData(name) + ""; } @Override public void setValue(final String val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException { if (spatial == null) { return; } try { SceneApplication.getApplication().enqueue(new Callable<Void>() { public Void call() throws Exception { switch (type) { case 0: spatial.setUserData(name, Integer.parseInt(val)); break; case 1: spatial.setUserData(name, Float.parseFloat(val)); break; case 2: spatial.setUserData(name, Boolean.parseBoolean(val)); break; case 3: spatial.setUserData(name, val); break; case 4: spatial.setUserData(name, Long.parseLong(val)); break; default: // throw new UnsupportedOperationException(); } return null; } }).get(); notifyListeners(null, val); } catch (InterruptedException ex) { Exceptions.printStackTrace(ex); } catch (ExecutionException ex) { Exceptions.printStackTrace(ex); } } @Override public PropertyEditor getPropertyEditor() { return null; // return new AnimationPropertyEditor(control); } public void addPropertyChangeListener(ScenePropertyChangeListener listener) { listeners.add(listener); } public void removePropertyChangeListener(ScenePropertyChangeListener listener) { listeners.remove(listener); } private void notifyListeners(Object before, Object after) { for (Iterator<ScenePropertyChangeListener> it = listeners.iterator(); it.hasNext();) { ScenePropertyChangeListener propertyChangeListener = it.next(); propertyChangeListener.propertyChange(getName(), before, after); } } }
chototsu/MikuMikuStudio
sdk/jme3-core/src/com/jme3/gde/core/properties/UserDataProperty.java
Java
bsd-2-clause
5,643
#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_ #define FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_ #include "aos/common/controls/polytope.h" #ifdef INCLUDE_971_INFRASTRUCTURE #include "frc971/control_loops/drivetrain/drivetrain.q.h" #endif //INCLUDE_971_INFRASTRUCTURE #include "frc971/control_loops/state_feedback_loop.h" #include "frc971/control_loops/drivetrain/drivetrain_config.h" namespace frc971 { namespace control_loops { namespace drivetrain { class PolyDrivetrain { public: enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN }; PolyDrivetrain(const DrivetrainConfig &dt_config); int controller_index() const { return loop_->controller_index(); } bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; } // Computes the speed of the motor given the hall effect position and the // speed of the robot. double MotorSpeed(const constants::ShifterHallEffect &hall_effect, double shifter_position, double velocity); // Computes the states of the shifters for the left and right drivetrain sides // given a requested state. void UpdateGears(Gear requested_gear); // Computes the next state of a shifter given the current state and the // requested state. Gear UpdateSingleGear(Gear requested_gear, Gear current_gear); void SetGoal(double wheel, double throttle, bool quickturn, bool highgear); #ifdef INCLUDE_971_INFRASTRUCTURE void SetPosition( const ::frc971::control_loops::DrivetrainQueue::Position *position); #else //INCLUDE_971_INFRASTRUCTURE void SetPosition( const DrivetrainPosition *position); #endif //INCLUDE_971_INFRASTRUCTURE double FilterVelocity(double throttle); double MaxVelocity(); void Update(); #ifdef INCLUDE_971_INFRASTRUCTURE void SendMotors(::frc971::control_loops::DrivetrainQueue::Output *output); #else //INCLUDE_971_INFRASTRUCTURE void SendMotors(DrivetrainOutput *output); #endif //INCLUDE_971_INFRASTRUCTURE private: StateFeedbackLoop<7, 2, 3> kf_; const ::aos::controls::HPolytope<2> U_Poly_; ::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_; const double ttrust_; double wheel_; double throttle_; bool quickturn_; int stale_count_; double position_time_delta_; Gear left_gear_; Gear right_gear_; #ifdef INCLUDE_971_INFRASTRUCTURE ::frc971::control_loops::DrivetrainQueue::Position last_position_; ::frc971::control_loops::DrivetrainQueue::Position position_; #else //INCLUDE_971_INFRASTRUCTURE DrivetrainPosition last_position_; DrivetrainPosition position_; #endif //INCLUDE_971_INFRASTRUCTURE int counter_; DrivetrainConfig dt_config_; }; } // namespace drivetrain } // namespace control_loops } // namespace frc971 #endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
FRC1296/CheezyDriver2016
frc971/control_loops/drivetrain/polydrivetrain.h
C
bsd-2-clause
2,780
// Copyright (c) 2017 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 "minipy.h" #include <iostream> #include <string> int main(int argc, char* argv[]) { (void)argc, (void)argv; const char* prompt = ">>> "; std::cout << "********** MiniPy 0.1 **********" << std::endl; std::cout << prompt; std::string command; while (std::getline(std::cin, command)) { if (command.empty()) ; else if (command == "exit") break; else Py_Execute(command); std::cout << prompt; } return 0; }
ASMlover/study
python/minipy/main.cc
C++
bsd-2-clause
1,837
# OCaml does not preserve binary compatibility across compiler releases, # so when updating it you should ensure that all dependent packages are # also updated by incrementing their revisions. # # Specific packages to pay attention to include: # - camlp5 # - lablgtk # # Applications that really shouldn't break on a compiler update are: # - coq # - coccinelle # - unison class Ocaml < Formula desc "General purpose programming language in the ML family" homepage "https://ocaml.org/" url "https://caml.inria.fr/pub/distrib/ocaml-4.12/ocaml-4.12.0.tar.xz" sha256 "39ee9db8dc1e3eb65473dd81a71fabab7cc253dbd7b85e9f9b5b28271319bec3" license "LGPL-2.1-only" => { with: "OCaml-LGPL-linking-exception" } head "https://github.com/ocaml/ocaml.git", branch: "trunk" livecheck do url "https://ocaml.org/releases/" regex(/href=.*?v?(\d+(?:\.\d+)+)\.html/i) end bottle do sha256 cellar: :any, arm64_big_sur: "23d4a0ea99bad00b29387d05eef233fb1ce44a71e9031644f984850820f7b1fc" sha256 cellar: :any, big_sur: "98ee5c246e559e6d494ce7e2927a8a4c11ff3c47c26d7a2da19053ba97aa6158" sha256 cellar: :any, catalina: "f1f72000415627bc8ea540dffc7fd29c2d7ebc41c70e76b03a994c7e6e746284" sha256 cellar: :any, mojave: "9badb226c3d92ae196c9a2922c73075eaa45ee90f3c9b06180e29706e95f2f0b" sha256 cellar: :any_skip_relocation, x86_64_linux: "779e6f230c29dd6ef71ec70e83fea42168c097c720c0a4d4b1ae34ab6e58be74" end pour_bottle? do # The ocaml compilers embed prefix information in weird ways that the default # brew detection doesn't find, and so needs to be explicitly blacklisted. reason "The bottle needs to be installed into #{Homebrew::DEFAULT_PREFIX}." satisfy { HOMEBREW_PREFIX.to_s == Homebrew::DEFAULT_PREFIX } end def install ENV.deparallelize # Builds are not parallel-safe, esp. with many cores # the ./configure in this package is NOT a GNU autoconf script! args = %W[ --prefix=#{HOMEBREW_PREFIX} --enable-debug-runtime --mandir=#{man} ] system "./configure", *args system "make", "world.opt" system "make", "prefix=#{prefix}", "install" end test do output = shell_output("echo 'let x = 1 ;;' | #{bin}/ocaml 2>&1") assert_match "val x : int = 1", output assert_match HOMEBREW_PREFIX.to_s, shell_output("#{bin}/ocamlc -where") end end
Linuxbrew/homebrew-core
Formula/ocaml.rb
Ruby
bsd-2-clause
2,431
class Xonsh < Formula include Language::Python::Virtualenv desc "Python-ish, BASHwards-compatible shell language and command prompt" homepage "https://xon.sh/" url "https://github.com/xonsh/xonsh/archive/0.8.12.tar.gz" sha256 "7c51ce752f86e9eaae786a4886a6328ba66e16d91d2b7ba696baa6560a4de4ec" head "https://github.com/xonsh/xonsh.git" bottle do cellar :any_skip_relocation sha256 "0946b4172b6c6f927f17d9bd12ecb2fdf18f8f086abe0e7841c9dcb3b4c634dc" => :mojave sha256 "19efaf5ee095bdbfd58e8b32b3629e3f5bd58f3dc3d310e382520554873bfaf6" => :high_sierra sha256 "188f0659e92c741173d0d9fd14ecfd050abdbc7d82a350cb5e38faf931a65d35" => :sierra end depends_on "python" # Resources based on `pip3 install xonsh[ptk,pygments,proctitle]` # See https://xon.sh/osx.html#dependencies resource "prompt_toolkit" do url "https://files.pythonhosted.org/packages/d9/a5/4b2dd1a05403e34c3ba0d9c00f237c01967c0a4f59a427c9b241129cdfe4/prompt_toolkit-2.0.7.tar.gz" sha256 "fd17048d8335c1e6d5ee403c3569953ba3eb8555d710bfc548faf0712666ea39" end resource "Pygments" do url "https://files.pythonhosted.org/packages/64/69/413708eaf3a64a6abb8972644e0f20891a55e621c6759e2c3f3891e05d63/Pygments-2.3.1.tar.gz" sha256 "5ffada19f6203563680669ee7f53b64dabbeb100eb51b61996085e99c03b284a" end resource "setproctitle" do url "https://files.pythonhosted.org/packages/5a/0d/dc0d2234aacba6cf1a729964383e3452c52096dc695581248b548786f2b3/setproctitle-1.1.10.tar.gz" sha256 "6283b7a58477dd8478fbb9e76defb37968ee4ba47b05ec1c053cb39638bd7398" end resource "six" do url "https://files.pythonhosted.org/packages/dd/bf/4138e7bfb757de47d1f4b6994648ec67a51efe58fa907c1e11e350cddfca/six-1.12.0.tar.gz" sha256 "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73" end resource "wcwidth" do url "https://files.pythonhosted.org/packages/55/11/e4a2bb08bb450fdbd42cc709dd40de4ed2c472cf0ccb9e64af22279c5495/wcwidth-0.1.7.tar.gz" sha256 "3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e" end def install virtualenv_install_with_resources end test do assert_match "4", shell_output("#{bin}/xonsh -c 2+2") end end
bcg62/homebrew-core
Formula/xonsh.rb
Ruby
bsd-2-clause
2,201
/* * cuda_common.h * * Created on: Jul 14, 2014 * Author: shu */ #pragma once #include <cstdio> #include <stdint.h> #define CUDA_CHECK_RETURN(value) { \ cudaError_t _m_cudaStat = value; \ if (_m_cudaStat != cudaSuccess) { \ fprintf(stderr, "Error %s at line %d in file %s\n", \ cudaGetErrorString(_m_cudaStat), __LINE__, __FILE__); \ exit(1); \ } } namespace cuda_common { typedef struct { uint32_t query_position; uint32_t database_position; } Coordinate; enum Direction { kFoward, kReverse, }; static const size_t kMaxLoadLength = 4; }
akiyamalab/ghostz-gpu
src/cuda_common.h
C
bsd-2-clause
616
<?php namespace Bacharu\Models; use \Prajna\Objects\VIFMetrics as PrajnaVIFMetrics; class VIFMetrics extends PrajnaVIFMetrics { public function __construct(){} }
cameronjacobson/Bacharu
src/Bacharu/Models/VIFMetrics.php
PHP
bsd-2-clause
166
# Copyright (c) 2015-2018 by the parties listed in the AUTHORS file. # All rights reserved. Use of this source code is governed by # a BSD-style license that can be found in the LICENSE file. """ sim_det_noise.py implements the noise simulation operator, OpSimNoise. """ import numpy as np from ..op import Operator from ..ctoast import sim_noise_sim_noise_timestream as sim_noise_timestream from .. import timing as timing class OpSimNoise(Operator): """ Operator which generates noise timestreams. This passes through each observation and every process generates data for its assigned samples. The dictionary for each observation should include a unique 'ID' used in the random number generation. The observation dictionary can optionally include a 'global_offset' member that might be useful if you are splitting observations and want to enforce reproducibility of a given sample, even when using different-sized observations. Args: out (str): accumulate data to the cache with name <out>_<detector>. If the named cache objects do not exist, then they are created. realization (int): if simulating multiple realizations, the realization index. component (int): the component index to use for this noise simulation. noise (str): PSD key in the observation dictionary. """ def __init__(self, out='noise', realization=0, component=0, noise='noise', rate=None, altFFT=False): # We call the parent class constructor, which currently does nothing super().__init__() self._out = out self._oversample = 2 self._realization = realization self._component = component self._noisekey = noise self._rate = rate self._altfft = altFFT def exec(self, data): """ Generate noise timestreams. This iterates over all observations and detectors and generates the noise timestreams based on the noise object for the current observation. Args: data (toast.Data): The distributed data. Raises: KeyError: If an observation in data does not have noise object defined under given key. RuntimeError: If observations are not split into chunks. """ autotimer = timing.auto_timer(type(self).__name__) for obs in data.obs: obsindx = 0 if 'id' in obs: obsindx = obs['id'] else: print("Warning: observation ID is not set, using zero!") telescope = 0 if 'telescope' in obs: telescope = obs['telescope_id'] global_offset = 0 if 'global_offset' in obs: global_offset = obs['global_offset'] tod = obs['tod'] if self._noisekey in obs: nse = obs[self._noisekey] else: raise KeyError('Observation does not contain noise under ' '"{}"'.format(self._noisekey)) if tod.local_chunks is None: raise RuntimeError('noise simulation for uniform distributed ' 'samples not implemented') # eventually we'll redistribute, to allow long correlations... if self._rate is None: times = tod.local_times() else: times = None # Iterate over each chunk. chunk_first = tod.local_samples[0] for curchunk in range(tod.local_chunks[1]): chunk_first += self.simulate_chunk( tod=tod, nse=nse, curchunk=curchunk, chunk_first=chunk_first, obsindx=obsindx, times=times, telescope=telescope, global_offset=global_offset) return def simulate_chunk(self, *, tod, nse, curchunk, chunk_first, obsindx, times, telescope, global_offset): """ Simulate one chunk of noise for all detectors. Args: tod (toast.tod.TOD): TOD object for the observation. nse (toast.tod.Noise): Noise object for the observation. curchunk (int): The local index of the chunk to simulate. chunk_first (int): First global sample index of the chunk. obsindx (int): Observation index for random number stream. times (int): Timestamps for effective sample rate. telescope (int): Telescope index for random number stream. global_offset (int): Global offset for random number stream. Returns: chunk_samp (int): Number of simulated samples """ autotimer = timing.auto_timer(type(self).__name__) chunk_samp = tod.total_chunks[tod.local_chunks[0] + curchunk] local_offset = chunk_first - tod.local_samples[0] if self._rate is None: # compute effective sample rate rate = 1 / np.median(np.diff( times[local_offset : local_offset+chunk_samp])) else: rate = self._rate for key in nse.keys: # Check if noise matching this PSD key is needed weight = 0. for det in tod.local_dets: weight += np.abs(nse.weight(det, key)) if weight == 0: continue # Simulate the noise matching this key #nsedata = sim_noise_timestream( # self._realization, telescope, self._component, obsindx, # nse.index(key), rate, chunk_first+global_offset, chunk_samp, # self._oversample, nse.freq(key), nse.psd(key), # self._altfft)[0] nsedata = sim_noise_timestream( self._realization, telescope, self._component, obsindx, nse.index(key), rate, chunk_first+global_offset, chunk_samp, self._oversample, nse.freq(key), nse.psd(key)) # Add the noise to all detectors that have nonzero weights for det in tod.local_dets: weight = nse.weight(det, key) if weight == 0: continue cachename = '{}_{}'.format(self._out, det) if tod.cache.exists(cachename): ref = tod.cache.reference(cachename) else: ref = tod.cache.create(cachename, np.float64, (tod.local_samples[1], )) ref[local_offset : local_offset+chunk_samp] += weight*nsedata del ref return chunk_samp
tskisner/pytoast
src/python/tod/sim_det_noise.py
Python
bsd-2-clause
6,740
(function(){ var slides = [ {title: 'Работы для отдела Клиентского сервиса и сапорта ФС\nТикетная админка, админка массовых сбоев', works: [ {img: 'i/works/ticket-admin.png', description: '<div class="presentation_mb10"><strong>Тикетная админка</strong></div>' + '<div class="presentation_mb10">Через эту админку сотрудники сапорта работают с обращениями пользователей соц. сети. Мною была реализована вся верстка раздела и код на js.</div>' + '<div class="presentation_mb10">Особенности:</div>' + '<ul class="presentation-list">' + '<li>Интерфейс занимают всю высоту экрана монитора - резиновый по вертикали (На странице могут быть три внутреннии области со скролом );</li>' + '<li>Автоподгрузка новых тикетов;</li>' + '<li>Большое число кастомных элементов управления.</li>' + '</ul>' }, {img: 'i/works/ticket-admin2.png', description: '<div class="presentation_mb10"><strong>Админка массовых сбоев</strong></div>' + '<div class="presentation_mb10">Инструмент взаимодействия сотрудников сапорта и тестеровщиков. При наличие однотипных обращений пользователей, их тикеты групируются в массовый сбой. Который попадает к тестировщикам в виде таска в редмайн для исследования.</div>' }, {img: 'i/works/ticket-admin3.png', description: 'Диалог просмотра массового сбоя.'}, {img: 'i/works/ticket-admin4.png', description: 'Пример реализации кастомного выпадающего списка.'}, ] },{title: 'Отдел модерации \nПопапы жалоб, страница заблокированного пользователя', works: [ {img: 'i/works/complaint_popup.png', description: '<div class="presentation_mb10"><strong>Попап подачи жалоб на пользователя</strong></div>' + '<div class="">Мною была реализована вся frontend часть - верстка и код на js.</div>' },{img: 'i/works/abusePopups.jpg', description: '<div class="">Реализовано несколько кейсов с последовательной навигацией.</div>' },{img: 'i/works/complaint_popup1.png', description: '<div class="">Содержимое попапа - вопросник с готовыми ответами и возможностью отправить расширенное описание.</div>' }, {img: 'i/works/abuse_form.jpg', description: 'Различные варианты попапов жалоб на нарушения со стороны пользователей. Попапы показываются на странице пользователя.'}, {img: 'i/works/abuse_page.jpg', description: 'Страница заблокированного пользователя. Реализована в нескольких вариантах для удаленного пользователя и расширенной для сотрудников Фотостраны. Мною была реализована верстка (html/php).'}, ] },{title: 'Раздел помощи (FAQ)', works: [ {img: 'i/works/faq1.png', description: '<div class="presentation_mb10">В разделе помощи я занимался поддержкой старого кода, правил баги. Поэтому там моя верстка присутствует только фрагментами. К примеру этот опросник сверстан мной. Весь hover эффект при выборе количества звезд реализован только на css.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/support/feedback/ask/" target="_blank">http://fotostrana.ru/support/feedback/ask/</a></div>'}, ] },{title: 'Раздел "Мои финансы"', works: [ {img: 'i/works/finroom.png', description: '<div class="presentation_mb10"><strong>Раздел "Мои финансы" страницы пользователя</strong></div>' + '<div class="presentation_mb10">Мною была реализована верстка и необходимый код на js.</div>' + '<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/finance/index/" target="_blank">http://fotostrana.ru/finance/index/</a></div>' }, {img: 'i/works/finroom2.png', description: '<div class="presentation_mb10">Для страницы было реализовано много различных блоков показываемые разным сегментам пользовательской аудитории.</div>'}, {img: 'i/works/finroom3.png', description: 'Так же мною были сверстаны различные попапы сопутсвующих премиальных услуг, доступные из этого раздела.'}, {img: 'i/works/autopay1.png', description: 'Попап услуги &laquo;Автоплатеж&raquo;'}, {img: 'i/works/fotocheck.png', description: 'СМС информирование'}, {img: 'i/works/finroom4.png', description: ''}, ] },{title: 'Финансовый попап \nПопап пополнения счета пользователя', works: [ {img: 'i/works/finpopup1.png', description: '<div class="presentation_mb10">Попап с большим количеством переходов и кастомными элементами управления.</div>' + '<div class="presentation_mb10">Мною была сделана необходимая верстка и js код.</div>' }, {img: 'i/works/finpopup2.png', description: '<div class="presentation_mb10">Из сложных деталей интерфейса:</div>' + '<ul class="presentation-list">' + '<li>"резиновые" кнопки ввода необходимой суммы Фотомани, с возможностью указать произвольную сумму;</li>' + '<li>контроль за вводом и валидация пользовательских данных.</li>' + '</ul>' }, {img: 'i/works/finpopup3.png', description: ''}, ] },{title: 'Сервис "Я модератор"', works: [ {img: 'i/works/imoderator1.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Я модератор"</strong> - пользователям за вознаграждение передается часть модерируемого контента.</div>' + '<div class="">Мною была выполнена вся верстка и весь js код. Из сложных деталей интерфеса - флип часы, реализованные с использованием css3 animation.</div>' }, {img: 'i/works/imoderator2.jpg', description: '<div class="presentation_mb10">В приложении реализовано несколько режимов модерации, в том числе и полно экранный режим (резиновый, скрывающий стандартный лэйаут страниц соц. сети).</div>' + '<div class="">Так же в приложении реализованы инструменты для мотивации "качественной" оценки фотографий пользователями. Используются тестовые проверочные изображения, принудительная отправка в режим обучения и поиск дубликатов изображений в Google/Yandex.</div>' }, ] },{title: 'Сервис "Голосование"', works: [ {img: 'i/works/contest.jpg', description: '<div class="presentation_mb10"><strong>Сервис "Голосование"</strong> - один из основных по доходности сервисов Фотостраны с большой аудиторией</div>' + '<div class="presentation_mb10">В этом сервисе, я занимался поддержкой старого кода и версткой скидочных акций и сезонных мероприятий по активизации пользовательской активности приуроченные к праздникам, мероприятиям (Новый год, Олимпийские игры, 8-е марта, день всех влюбленных, 23 февраля, 12 апреля и др.)</div>' + '<div class="presentation_mb10">Так же мною был переделан механизм рендеринга фотостены.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/" target="_blank">www.fotostrana.ru/contest/</a></div>' }, {img: 'i/works/contest1.jpg', description: ''}, ] },{title: 'Игровой сервис "Битва кланов"', works: [ {img: 'i/works/clan1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Битва Кланов"</strong> - игровой под сервис голосования. Игра в форме квеста.</div>' + '<div>В этом сервисе я делал верстку и js код. Много кейсов, много попапов, много backbon-а. Используется sass, require.js, backbone.</div>' }, {img: 'i/works/clan2.jpg', description: '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/clan2/" target="_blank">www.fotostrana.ru/contest/clan2/</a></div>'}, {img: 'i/works/clan4.jpg', description: 'В сервисе много сложных интерфейсных решений, как на пример поле ввода сообщения в чат. Реализовано ограничение на длину вводимого сообщения и авторесайз высоты textarea.'}, {img: 'i/works/clan3.jpg', description: ''}, ] },{title: 'Сервис "Элитное голосование"', works: [ {img: 'i/works/elite1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Элитное голосование"</strong> - игровой под сервис голосования, доступный несколько дней в месяце для активных участников основного голосования.</div>' + '<div>В этом сервисе я делал верстку и js код. Внешнее оформление переделывалось мною к каждому запуску сервиса.</div>'}, {img: 'i/works/elite2.jpg', description: ''}, ] },{title: 'Сервис "Люди"\nДейтинговый сервис Фотостраны', works: [ {img: 'i/works/people1.jpg', description: '<div class="presentation_mb10"><strong>Дейтинговый сервис "Люди"</strong> - на протяжении полу года поддерживал фронтенд сервиса - исправлял баги, верстал рекламные банеры и попапы.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/people/" target="_blank">fotostrana.ru/people/</a></div>'}, {img: 'i/works/people2.jpg', description: ''}, ] },{title: 'Сообщества и пиновый интерфейс', works: [ {img: 'i/works/community1.jpg', description: '<div class="presentation_mb10">Некоторое время работал над версткой сообществ и пиновым интерфейсом. Концепция пинов была позаимствована у другого сервиса Pinterest. Занимался проектом начиная с первого прототипа и до предрелизной подготовкой.</div>' + '<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/public/" target="_blank">fotostrana.ru/public/</a></div>'}, ] },{title: 'Сайт http://www.blik-cleaning.ru/', works: [ {img: 'i/works/cleaning.jpg', description: '<div class="presentation_mb10"><strong>Разработка сайта клининговой компании</strong></div>' + '<div>Сайт сделан на CMS WordPress с оригинальной темой. </div>'}, {img: 'i/works/cleaning1.jpg', description: ''}, ] },{title: 'Сайт http://www.promalp.name/', works: [ {img: 'i/works/promalp1.jpg', description: '<div class="presentation_mb10"><strong>Сайт компании занимающейся промышленным альпинизмом.</strong></div>' + '<div>Сайт сделан на node.js (express). Полностью реализован мною.</div>'}, {img: 'i/works/promalp2.jpg', description: 'Страница с портфолио.'}, {img: 'i/works/promalp3.jpg', description: 'Форма заявки.'}, ] },{title: 'Расширение для браузера chrome Netmarks', works: [ {img: 'i/works/netmarks.jpg', description: '<div class="presentation_mb10"><strong>Chrome extension "NetMarks"</strong></div>' + '<div class="presentation_mb10">Расширение для удобной работы с браузерными закладками в виде выпадающего меню.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/netmarks/boepmphdpbdnficfifejnkejlljcefjb" target="_blank">Chrome store</a></div>' }, ] },{title: 'Приложение для браузера chrome Deposit.calc', works: [ {img: 'i/works/depcalc1.jpg', description: '<div class="presentation_mb10"><strong>Deposit.calc</strong></div>' + '<div class="presentation_mb10">Приложение позволяющее расчитать доход по вкладу с пополнениями. Используется собственный оригинальный алгоритм расчета.</div>' + '<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/депозитный-калькулятор/cibblnjekngmoeiehohbkmcbfijpcjdj" target="_blank">Chrome store</a></div>'}, {img: 'i/works/depcalc2.jpg', description: 'Для вывода графиков был использован highcharts.'}, ] }, ]; var View = m3toolkit.View, CollectionView = m3toolkit.CollectionView, BlockView = m3toolkit.BlockView, _base = { // @param {Int} Index // @return {Model} model from collection by index getAnother: function(index){ return this.slideCollection.at(index); } }; var SlideModel = Backbone.Model.extend({ defaults: { title: '', works: [], index: undefined, next: undefined, prev: undefined } }); var SlidesCollection = Backbone.Collection.extend({ model: SlideModel, initialize: function(list){ var i = 0, len = list.length indexedList = list.map(function(item){ item.index = i; if(i > 0){ item.prev = i - 1; } if(i < len - 1){ item.next = i + 1; } if(Array.isArray(item.works)){ item.frontImage = item.works[0].img; } i++; return item; }); Backbone.Collection.prototype.initialize.call(this, indexedList); } }); var WorkItemModel = Backbone.Model.extend({ defaults: { img: '', description: '' } }); var WorkItemsCollections = Backbone.Collection.extend({ model: WorkItemModel }); var WorkItemPreview = View.extend({ className: 'presentation_work-item clearfix', template: _.template( '<img src="<%=img%>" class="Stretch m3-vertical "/>' + '<% if(obj.description){ %>' + '<div class="presentation_work-item_description"><%=obj.description%></div>' + '<% }%>' ) }); var SlideView = View.extend({ className: 'presentation_slide-wrap', template: _.template( '<div style="background-image: url(<%=obj.frontImage%>)" class="presentation_front-image"></div>' + '<div class="presentation_front-image_hover"></div>' ), events: { click: function(e){ _base.openFullScreenPresentation(this.model); } }, }); var FullscreenSlideView = BlockView.extend({ className: 'presentation_fullscreen-slide', template: '<div class="presentation_fullscreen-slide_back"></div>' + '<div class="presentation_fullscreen-slide_close" data-bind="close"></div>' + '<div class="presentation_fullscreen-slide_wrap">' + '<div class="presentation_fullscreen-slide_next" data-co="next">' + '<div class="presentation_fullscreen-slide_nav-btn presentation_fullscreen-slide_nav-btn_next "></div>' + '</div>' + '<div class="presentation_fullscreen-slide_prev" data-co="prev">' + '<div class="presentation_fullscreen-slide_nav-btn"></div>'+ '</div>' + '<pre class="presentation_fullscreen-slide_title" data-co="title"></pre>' + '<div class="" data-co="works" style=""></div>' + '</div>', events: { 'click [data-bind=close]': function(){ _base.hideFullScreenPresentation(); }, 'click [data-co=next]': function(){ var nextIndex = this.model.get('next'); nextIndex != undefined && this._navigateTo(nextIndex); }, 'click [data-co=prev]': function(){ var prevIndex = this.model.get('prev'); prevIndex != undefined && this._navigateTo(prevIndex); }, }, _navigateTo: function(index){ var prevModel =_base.getAnother(index); if(prevModel){ var data = prevModel.toJSON(); this.model.set(prevModel.toJSON()); } }, initialize: function(){ BlockView.prototype.initialize.call(this); this.controls.prev[this.model.get('prev') != undefined ? 'show': 'hide'](); this.controls.next[this.model.get('next') ? 'show': 'hide'](); var workItemsCollection = new WorkItemsCollections(this.model.get('works')); this.children.workCollection = new CollectionView({ collection: workItemsCollection, el: this.controls.works }, WorkItemPreview); this.listenTo(this.model, 'change:works', function(model){ console.log('Works Changed'); workItemsCollection.reset(model.get('works')); }); }, defineBindings: function(){ this._addComputed('works', 'works', function(control, model){ console.log('Refresh works'); var worksList = model.get('works'); console.dir(worksList); }); this._addTransform('title', function(control, model, value){ console.log('Set new Title: `%s`', value); control.text(value); }); this._addTransform('next', function(control, model, value){ control[value ? 'show': 'hide'](); }); this._addTransform('prev', function(control, model, value){ control[value != undefined ? 'show': 'hide'](); }); } }); var PresentationApp = View.extend({ className: 'presentation-wrap', template: '<div class="presentation-wrap_header">' + '<div class="presentation-wrap_header-container">' + '<div class="presentation-wrap_header-title clearfix">' + /*'<div class="presentation-wrap_header-contacts">' + '<div class="">Контакты для связи:</div>' + '<div class="">8 (960) 243 14 03</div>' + '<div class="">[email protected]</div>' + '</div>' +*/ '<h2 class="presentation_header1">Портфолио презентация</h2>' + '<div class="presentation_liter1">Фронтенд разработчика Николая Мальцева</div>' + '<div class="presentation_liter1">8 (960) 243 14 03, [email protected]</div>' + '<div class="presentation_liter1"><a href="http://matraska231.herokuapp.com/?portfolio=1#cv" target="_blank">Резюме</a></div>' + '</div>' + '</div>' + '</div>' + '<div class="presentation-wrap_body" data-bind="body">' + '<div class="presentation-wrap_slide clearfix" data-bind="slides">' + '</div>' + '</div>' + '<div data-bind="fullscreen" class="presentation_fullscreen-slide" style="display: none;"></div>', initialize: function(){ View.prototype.initialize.call(this); var $slides = this.$('[data-bind=slides]'), $body = this.$('[data-bind=body]'), slideCollection = new SlidesCollection(slides); _base.app = this; _base.slideCollection = slideCollection; this.children['slides'] = new CollectionView({ collection: slideCollection, el: $slides }, SlideView); this.children['fullscreen'] = new FullscreenSlideView({ el: this.$('[data-bind=fullscreen]'), model: new SlideModel() }); _base.openFullScreenPresentation = function(model){ $body.addClass('presentation-fix-body'); this.children['fullscreen'].$el.show(); this.children['fullscreen'].model.set(model.toJSON()); // TODO store vertical position }.bind(this); _base.hideFullScreenPresentation = function(){ this.children['fullscreen'].$el.hide(); $body.removeClass('presentation-fix-body'); }.bind(this); } }); var app = new PresentationApp({ el: '#app' }); }());
matraska23/m3-backbone-toolkit
demo_presentation/js/presentation.js
JavaScript
bsd-2-clause
22,354
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2013 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. import zmq import time if __name__ == '__main__': ctx = zmq.Context() worker = ctx.socket(zmq.PULL) worker.connect('tcp://localhost:5555') sinker = ctx.socket(zmq.PUSH) sinker.connect('tcp://localhost:6666') print 'all workers are ready ...' while True: try: msg = worker.recv() print 'begin to work on task use `%s ms`' % msg time.sleep(int(msg) * 0.001) print '\tfinished this task' sinker.send('finished task which used `%s ms`' % msg) except KeyboardInterrupt: break sinker.close() worker.close()
ASMlover/study
zeroMQ/python/push-pull/worker.py
Python
bsd-2-clause
1,961
class WireguardGo < Formula desc "Userspace Go implementation of WireGuard" homepage "https://www.wireguard.com/" url "https://git.zx2c4.com/wireguard-go/snapshot/wireguard-go-0.0.20200320.tar.xz" sha256 "c8262da949043976d092859843d3c0cdffe225ec6f1398ba119858b6c1b3552f" license "MIT" head "https://git.zx2c4.com/wireguard-go", using: :git livecheck do url :head regex(/href=.*?wireguard-go[._-]v?(\d+(?:\.\d+)+)\.t/i) end bottle do cellar :any_skip_relocation sha256 "783b1eeb0aba2c336e91fe59ef9e8d5d449e51ef3a5ed313f96666c7d055fb02" => :catalina sha256 "baf1cc2e7f0795747bcaed6856ce3a4075083356cc557497adf06ceaf28e0514" => :mojave sha256 "23d0d338dddebcecc58aa5f1e651fbde03494b0d49071937c4cff0b4d19961c2" => :high_sierra sha256 "168b97cf56b028ecf953768dcd06bd894aa1fc2daedb63a5074bfb5b60df99e5" => :x86_64_linux end depends_on "go" => :build def install ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache" system "make", "PREFIX=#{prefix}", "install" end test do # ERROR: (notrealutun) Failed to create TUN device: no such file or directory return if ENV["CI"] assert_match "be utun", pipe_output("WG_PROCESS_FOREGROUND=1 #{bin}/wireguard-go notrealutun") end end
maxim-belkin/homebrew-core
Formula/wireguard-go.rb
Ruby
bsd-2-clause
1,241
# Writing your docs How to write and layout your markdown source files. --- ## Configure Pages and Navigation The [pages configuration](/user-guide/configuration/#pages) in your `mkdocs.yml` defines which pages are built by MkDocs and how they appear in the documentation navigation. If not provided, the pages configuration will be automatically created by discovering all the Markdown files in the [documentation directory](/user-guide/configuration/#docs_dir). A simple pages configuration looks like this: pages: - 'index.md' - 'about.md' With this example we will build two pages at the top level and they will automatically have their titles inferred from the filename. Assuming `docs_dir` has the default value, `docs`, the source files for this documentation would be `docs/index.md` and `docs/about.md`. To provide a custom name for these pages, they can be added before the filename. pages: - Home: 'index.md' - About: 'about.md' ### Multilevel documentation Subsections can be created by listing related pages together under a section title. For example: pages: - Home: 'index.md' - User Guide: - 'Writing your docs': 'user-guide/writing-your-docs.md' - 'Styling your docs': 'user-guide/styling-your-docs.md' - About: - 'License': 'about/license.md' - 'Release Notes': 'about/release-notes.md' With the above configuration we have three top level sections: Home, User Guide and About. Then under User Guide we have two pages, Writing your docs and Styling your docs. Under the About section we also have two pages, License and Release Notes. *Note:* At present MkDocs only supports a second level of navigation. ## File layout Your documentation source should be written as regular Markdown files, and placed in a directory somewhere in your project. Normally this directory will be named `docs` and will exist at the top level of your project, alongside the `mkdocs.yml` configuration file. The simplest project you can create will look something like this: mkdocs.yml docs/ index.md By convention your project homepage should always be named `index`. Any of the following extensions may be used for your Markdown source files: `markdown`, `mdown`, `mkdn`, `mkd`, `md`. You can also create multi-page documentation, by creating several markdown files: mkdocs.yml docs/ index.md about.md license.md The file layout you use determines the URLs that are used for the generated pages. Given the above layout, pages would be generated for the following URLs: / /about/ /license/ You can also include your Markdown files in nested directories if that better suits your documentation layout. docs/ index.md user-guide/getting-started.md user-guide/configuration-options.md license.md Source files inside nested directories will cause pages to be generated with nested URLs, like so: / /user-guide/getting-started/ /user-guide/configuration-options/ /license/ ## Linking documents MkDocs allows you to interlink your documentation by using regular Markdown hyperlinks. #### Internal hyperlinks When linking between pages in the documentation you can simply use the regular Markdown hyperlinking syntax, including the relative path to the Markdown document you wish to link to. Please see the [project license](license.md) for further details. When the MkDocs build runs, these hyperlinks will automatically be transformed into a hyperlink to the appropriate HTML page. When working on your documentation you should be able to open the linked Markdown document in a new editor window simply by clicking on the link. If the target documentation file is in another directory you'll need to make sure to include any relative directory path in the hyperlink. Please see the [project license](../about/license.md) for further details. You can also link to a section within a target documentation page by using an anchor link. The generated HTML will correctly transform the path portion of the hyperlink, and leave the anchor portion intact. Please see the [project license](about.md#license) for further details. ## Images and media As well as the Markdown source files, you can also include other file types in your documentation, which will be copied across when generating your documentation site. These might include images and other media. For example, if your project documentation needed to include a [GitHub pages CNAME file](https://help.github.com/articles/setting-up-a-custom-domain-with-pages#setting-the-domain-in-your-repo) and a PNG formatted screenshot image then your file layout might look as follows: mkdocs.yml docs/ CNAME index.md about.md license.md img/ screenshot.png To include images in your documentation source files, simply use any of the regular Markdown image syntaxes: Cupcake indexer is a snazzy new project for indexing small cakes. ![Screenshot](img/screenshot.png) *Above: Cupcake indexer in progress* You image will now be embedded when you build the documentation, and should also be previewed if you're working on the documentation with a Markdown editor. ## Markdown extensions MkDocs supports the following Markdown extensions. #### Tables A simple table looks like this: ```text First Header | Second Header | Third Header ------------ | ------------- | ------------ Content Cell | Content Cell | Content Cell Content Cell | Content Cell | Content Cell ``` If you wish, you can add a leading and tailing pipe to each line of the table: ```text | First Header | Second Header | Third Header | | ------------ | ------------- | ------------ | | Content Cell | Content Cell | Content Cell | | Content Cell | Content Cell | Content Cell | ``` Specify alignment for each column by adding colons to separator lines: ```text First Header | Second Header | Third Header :----------- | :-----------: | -----------: Left | Center | Right Left | Center | Right ``` #### Fenced code blocks Start with a line containing 3 or more backtick \` characters, and ends with the first line with the same number of backticks \`: ``` Fenced code blocks are like Stardard Markdown’s regular code blocks, except that they’re not indented and instead rely on a start and end fence lines to delimit the code block. ``` With the approach, the language can be specified on the first line after the backticks: ```python def fn(): pass ```
samhatfield/mkdocs
docs/user-guide/writing-your-docs.md
Markdown
bsd-2-clause
6,667
/* @LICENSE(MUSLC_MIT) */ #include "pthread_impl.h" int pthread_detach(pthread_t t) { /* Cannot detach a thread that's already exiting */ if (a_swap(t->exitlock, 1)) return pthread_join(t, 0); t->detached = 2; __unlock(t->exitlock); return 0; }
gapry/refos
libs/libmuslc/src/thread/pthread_detach.c
C
bsd-2-clause
254
#!/bin/bash -e # erik reed # runs EM algorithm on hadoop streaming if [ $# -ne 5 ]; then echo Usage: $0 \"dir with net,tab,fg,em\" EM_FLAGS MAPPERS REDUCERS POP echo "2 choices for EM_FLAGS: -u and -alem" echo " -u corresponds to update; standard EM with fixed population size" echo " e.g. a simple random restart with $POP BNs" echo " -alem corresponds to Age-Layered EM with dynamic population size" exit 1 fi DAT_DIR=$1 EM_FLAGS=$2 MAPPERS=$3 REDUCERS=$4 # set to min_runs[0] if using ALEM POP=$5 HADOOP_JAR=`echo $HADOOP_PREFIX/contrib/streaming/*.jar` if [ -n "$HADOOP_PREFIX" ]; then HADOOP_HOME=$HADOOP_PREFIX elif [ -n "$HADOOP_HOME" ]; then echo Hadoop env vars not proeprly set! exit 1 else HADOOP_PREFIX=$HADOOP_HOME fi # max MapReduce job iterations, not max EM iters, which # is defined in dai_mapreduce.h MAX_ITERS=1 # (disabled) save previous run if it exists (just in case) #rm -rf out.prev #mv -f out out.prev || true rm -rf dat/out out mkdir -p dat/out out LOG="tee -a dat/out/log.txt" echo $0 started at `date` | $LOG echo -- Using parameters -- | $LOG echo Directory: $DAT_DIR | $LOG echo Max number of MapReduce iterations: $MAX_ITERS | $LOG echo Reducers: $REDUCERS | $LOG echo Mappers: $MAPPERS | $LOG echo Population size: $POP | $LOG echo EM flags: $EM_FLAGS echo Max MR iterations: $MAX_ITERS echo ---------------------- | $LOG ./scripts/make_input.sh $DAT_DIR echo $POP > in/pop # create random initial population ./utils in/fg $POP # copy 0th iteration (i.e. initial values) mkdir -p dat/out/iter.0 cp dat/in/dat dat/out/iter.0 cp dat/in/dat in echo Clearing previous input from HDFS hadoop fs -rmr -skipTrash out in &> /dev/null || true echo Adding input to HDFS hadoop fs -D dfs.replication=1 -put in in for i in $(seq 1 1 $MAX_ITERS); do echo starting MapReduce job iteration: $i $HADOOP_PREFIX/bin/hadoop jar $HADOOP_JAR \ -files "dai_map,dai_reduce,in" \ -D 'stream.map.output.field.separator=:' \ -D 'stream.reduce.output.field.separator=:' \ -D mapred.tasktracker.tasks.maximum=$MAPPERS \ -D mapred.map.tasks=$MAPPERS \ -D mapred.output.compress=false \ -input in/tab_content \ -output out \ -mapper ./dai_map \ -reducer ./dai_reduce \ -numReduceTasks $REDUCERS hadoop fs -cat out/part-* > dat/out/tmp hadoop fs -rmr -skipTrash out in/dat cat dat/out/tmp | ./utils $EM_FLAGS rm dat/out/tmp in/dat # remove previous iteration mkdir -p dat/out/iter.$i mv out/* dat/out/iter.$i if [ $i != $MAX_ITERS ]; then cp out/dat in echo Adding next iteration input to HDFS hadoop fs -D dfs.replication=1 -put out/dat in fi if [ -n "$start_time" -a -n "$time_duration" ]; then dur=$((`date +%s` - $start_time)) if [ $dur -ge $time_duration ]; then echo $time_duration seconds reached! Quitting... break fi fi converged=`cat dat/out/iter.$i/converged` if [ "$converged" = 1 ]; then echo EM converged at iteration $i break fi done
erikreed/HadoopBNEM
mapreduce/scripts/mr_streaming.sh
Shell
bsd-2-clause
3,032
#ifndef SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_ #define SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_ // Copyright (c) 2014, Ruslan Baratov // All rights reserved. #include <functional> // std::function namespace sober { namespace network { namespace http { using ExtraSuccessHandler = std::function<void()>; } // namespace http } // namespace network } // namespace sober #endif // SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_
ruslo/sober
Source/sober/network/http/ExtraSuccessHandler.hpp
C++
bsd-2-clause
441
##大纲 * DevOps基础 * DevOps是什么 * DevOps解决什么问题 * DevOps都做什么 * Vagrant基础 * init * box管理 * up * ssh * reload * destroy * port forward * multi-machines ##目标 * 基本理解DevOps以及DevOps要做的事情 * 可以使用Vagrant创建虚拟机并使用虚拟机工作 ##详细内容 #### DevOps是啥? ``` DevOps顾名思义, 就是Developer + Operatior,开发 + 运维。 当然,其实这里面还得加上QA。如图所示,三不像。 难道DevOps仅仅就是干三个角色的事儿么? 必然不是 DevOps是互相紧扣的一个过程。 通过Dev看QA,通过Ops看Dev等等 以上的概念太大,说个例子: 现在BOSS要你把所有javaEE的API拆成单独的jar包或者war包 然后每个包都部署到一个或者多个机器上。 真的你会去启动N个机器手动去部署么? QA怎么去验证各个java实例的运行? 开发以后还怎么开发? DevOps就会cover到上面的事儿 比如引入gradle自动拆成api包,然后要引入一个CI工具,比如jenkins或者go 当然构建出artifact是远远不够的,引入CD,我们要通过一系列的脚本来达到快速部署 还有在这个PIPELINE上的QA流程,是否通过job 最后,还能把虚拟化引入,比如vagrant、docker来部署单个java进程。 以上cover的就是devops的事儿 ``` #### DevOps都干些啥? ``` 如图,这些工具DevOps或多或少都会用 当然,我们普遍在LINUX下玩这件事儿,所以中间的BASH和SHELL SCRIPT是必须要求的 这里可以看到 有各种语言平台 有各种配置管理 有各种CI工具 有各种虚拟化产品 这些都会穿插在我们整个开发周期,所以,DevOps会一直跟这些工具打交到 ``` #### DevOps解决什么问题 ``` 在提DevOps定义的时候举了一个例子, 实际上,DevOps就是解决整个开发过程中的协调问题 如何快速的给DEV和QA配置环境,开发的产出如何快速的到QA手里 QA反馈如何能及时到Dev手上 最重要的:CD 仅修改一行代码,要多久才能部署到产品环境,个人认为这就是DevOps。 ``` #### SESSION课程和范围 ``` 一共会有5节课,这次是ITERATOR 0 目标是做一套完整的PIPELINE,达到快速部署的目的 会涉及到 java、jenkins、vagrant、tomcat、git等软件 通过是MAC作为宿主机,LINUX作为虚拟机进行整个课程的练习 ```
ThoughtWorks-Chengdu-DevOps-Club/tw_devops_workshop
season_1/workshop_0/introduction.md
Markdown
bsd-2-clause
2,470
/* * Copyright (c) 2012 Tom Denley * This file incorporates work covered by the following copyright and * permission notice: * * Copyright (c) 2003-2008, Franz-Josef Elmer, 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 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 org.netmelody.neoclassycle.renderer; import org.netmelody.neoclassycle.graph.StrongComponent; /** * Interface for rendering a {@link StrongComponent}. * * @author Franz-Josef Elmer */ public interface StrongComponentRenderer { /** Renderes the specified {@link StrongComponent}. */ public String render(StrongComponent component); }
netmelody/neoclassycle
src/main/java/org/netmelody/neoclassycle/renderer/StrongComponentRenderer.java
Java
bsd-2-clause
1,856
from unittest import TestCase import pkg_resources from mock import patch from click import UsageError from click.testing import CliRunner class TestCli(TestCase): @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'foo', 'author': 'Praekelt Foundation', 'author_email': '[email protected]', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': (), 'include': (), } }) @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold_with_custom_dir(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo', 'bar']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'bar', 'author': 'Praekelt Foundation', 'author_email': '[email protected]', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': (), 'include': (), } }) @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold_with_requirements(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo', '--require', 'bar']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'foo', 'author': 'Praekelt Foundation', 'author_email': '[email protected]', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': ('bar',), 'include': (), } }) @patch('molo.core.cookiecutter.cookiecutter') def test_scaffold_with_includes(self, mock_cookiecutter): from molo.core.scripts import cli package = pkg_resources.get_distribution('molo.core') runner = CliRunner() runner.invoke(cli.scaffold, ['foo', '--include', 'bar', 'baz']) [call] = mock_cookiecutter.call_args_list args, kwargs = call self.assertTrue(kwargs['extra_context'].pop('secret_key')) self.assertEqual(kwargs, { 'no_input': True, 'extra_context': { 'app_name': 'foo', 'directory': 'foo', 'author': 'Praekelt Foundation', 'author_email': '[email protected]', 'url': None, 'license': 'BSD', 'molo_version': package.version, 'require': (), 'include': (('bar', 'baz'),), } }) @patch('molo.core.scripts.cli.get_package') @patch('molo.core.scripts.cli.get_template_dirs') @patch('shutil.copytree') def test_unpack(self, mock_copytree, mock_get_template_dirs, mock_get_package): package = pkg_resources.get_distribution('molo.core') mock_get_package.return_value = package mock_get_template_dirs.return_value = ['foo'] mock_copytree.return_value = True from molo.core.scripts import cli runner = CliRunner() runner.invoke(cli.unpack_templates, ['app1', 'app2']) mock_copytree.assert_called_with( pkg_resources.resource_filename('molo.core', 'templates/foo'), pkg_resources.resource_filename('molo.core', 'templates/foo')) def test_get_package(self): from molo.core.scripts.cli import get_package self.assertRaisesRegexp( UsageError, 'molo.foo is not installed.', get_package, 'molo.foo')
praekelt/molo
molo/core/scripts/tests/test_cli.py
Python
bsd-2-clause
4,820
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ItzWarty.RAF { public class RAFFileListEntry { private byte[] directoryFileContent = null; private UInt32 offsetEntry = 0; private RAF raf = null; public RAFFileListEntry(RAF raf, byte[] directoryFileContent, UInt32 offsetEntry) { this.raf = raf; this.directoryFileContent = directoryFileContent; this.offsetEntry = offsetEntry; } /// <summary> /// Hash of the string name /// </summary> public UInt32 StringNameHash { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry); } } /// <summary> /// Offset to the start of the archived file in the data file /// </summary> public UInt32 FileOffset { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+4); } } /// <summary> /// Size of this archived file /// </summary> public UInt32 FileSize { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+8); } } /// <summary> /// Index of the name of the archvied file in the string table /// </summary> public UInt32 FileNameStringTableIndex { get { return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+12); } } public String GetFileName { get { return this.raf.GetDirectoryFile().GetStringTable()[this.FileNameStringTableIndex]; } } } }
dargondevteam/raflib
RAFFileListEntry.cs
C#
bsd-2-clause
1,881
// Copyright (c) 2020 WNProject Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Intentionally left empty so that we can build a lib target for this library #include "hashing/inc/hash.h"
WNProject/WNFramework
Libraries/hashing/src/dummy.cpp
C++
bsd-2-clause
277
// // Copyright (c) 2015 CNRS // // This file is part of Pinocchio // Pinocchio is free software: you can redistribute it // and/or modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation, either version // 3 of the License, or (at your option) any later version. // // Pinocchio is distributed in the hope that it will be // useful, but WITHOUT ANY WARRANTY; without even the implied warranty // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // General Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // Pinocchio If not, see // <http://www.gnu.org/licenses/>. #ifndef __se3_se3_hpp__ #define __se3_se3_hpp__ #include <Eigen/Geometry> #include "pinocchio/spatial/fwd.hpp" #include "pinocchio/spatial/skew.hpp" namespace se3 { /* Type returned by the "se3Action" and "se3ActionInverse" functions. */ namespace internal { template<typename D> struct ActionReturn { typedef D Type; }; } /** The rigid transform aMb can be seen in two ways: * * - given a point p expressed in frame B by its coordinate vector Bp, aMb * computes its coordinates in frame A by Ap = aMb Bp. * - aMb displaces a solid S centered at frame A into the solid centered in * B. In particular, the origin of A is displaced at the origin of B: $^aM_b * ^aA = ^aB$. * The rigid displacement is stored as a rotation matrix and translation vector by: * aMb (x) = aRb*x + aAB * where aAB is the vector from origin A to origin B expressed in coordinates A. */ template< class Derived> class SE3Base { protected: typedef Derived Derived_t; SPATIAL_TYPEDEF_TEMPLATE(Derived_t); public: Derived_t & derived() { return *static_cast<Derived_t*>(this); } const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); } const Angular_t & rotation() const { return derived().rotation_impl(); } const Linear_t & translation() const { return derived().translation_impl(); } Angular_t & rotation() { return derived().rotation_impl(); } Linear_t & translation() { return derived().translation_impl(); } void rotation(const Angular_t & R) { derived().rotation_impl(R); } void translation(const Linear_t & R) { derived().translation_impl(R); } Matrix4 toHomogeneousMatrix() const { return derived().toHomogeneousMatrix_impl(); } operator Matrix4() const { return toHomogeneousMatrix(); } Matrix6 toActionMatrix() const { return derived().toActionMatrix_impl(); } operator Matrix6() const { return toActionMatrix(); } void disp(std::ostream & os) const { static_cast<const Derived_t*>(this)->disp_impl(os); } Derived_t operator*(const Derived_t & m2) const { return derived().__mult__(m2); } /// ay = aXb.act(by) template<typename D> typename internal::ActionReturn<D>::Type act (const D & d) const { return derived().act_impl(d); } /// by = aXb.actInv(ay) template<typename D> typename internal::ActionReturn<D>::Type actInv(const D & d) const { return derived().actInv_impl(d); } Derived_t act (const Derived_t& m2) const { return derived().act_impl(m2); } Derived_t actInv(const Derived_t& m2) const { return derived().actInv_impl(m2); } bool operator == (const Derived_t & other) const { return derived().__equal__(other); } bool isApprox (const Derived_t & other) const { return derived().isApprox_impl(other); } friend std::ostream & operator << (std::ostream & os,const SE3Base<Derived> & X) { X.disp(os); return os; } }; // class SE3Base template<typename T, int U> struct traits< SE3Tpl<T, U> > { typedef T Scalar_t; typedef Eigen::Matrix<T,3,1,U> Vector3; typedef Eigen::Matrix<T,4,1,U> Vector4; typedef Eigen::Matrix<T,6,1,U> Vector6; typedef Eigen::Matrix<T,3,3,U> Matrix3; typedef Eigen::Matrix<T,4,4,U> Matrix4; typedef Eigen::Matrix<T,6,6,U> Matrix6; typedef Matrix3 Angular_t; typedef Vector3 Linear_t; typedef Matrix6 ActionMatrix_t; typedef Eigen::Quaternion<T,U> Quaternion_t; typedef SE3Tpl<T,U> SE3; typedef ForceTpl<T,U> Force; typedef MotionTpl<T,U> Motion; typedef Symmetric3Tpl<T,U> Symmetric3; enum { LINEAR = 0, ANGULAR = 3 }; }; // traits SE3Tpl template<typename _Scalar, int _Options> class SE3Tpl : public SE3Base< SE3Tpl< _Scalar, _Options > > { public: friend class SE3Base< SE3Tpl< _Scalar, _Options > >; SPATIAL_TYPEDEF_TEMPLATE(SE3Tpl); SE3Tpl(): rot(), trans() {}; template<typename M3,typename v3> SE3Tpl(const Eigen::MatrixBase<M3> & R, const Eigen::MatrixBase<v3> & p) : rot(R), trans(p) { } template<typename M4> SE3Tpl(const Eigen::MatrixBase<M4> & m) : rot(m.template block<3,3>(LINEAR,LINEAR)), trans(m.template block<3,1>(LINEAR,ANGULAR)) { } SE3Tpl(int) : rot(Matrix3::Identity()), trans(Vector3::Zero()) {} template<typename S2, int O2> SE3Tpl( const SE3Tpl<S2,O2> & clone ) : rot(clone.rotation()),trans(clone.translation()) {} template<typename S2, int O2> SE3Tpl & operator= (const SE3Tpl<S2,O2> & other) { rot = other.rotation (); trans = other.translation (); return *this; } static SE3Tpl Identity() { return SE3Tpl(1); } SE3Tpl & setIdentity () { rot.setIdentity (); trans.setZero (); return *this;} /// aXb = bXa.inverse() SE3Tpl inverse() const { return SE3Tpl(rot.transpose(), -rot.transpose()*trans); } static SE3Tpl Random() { Quaternion_t q(Vector4::Random()); q.normalize(); return SE3Tpl(q.matrix(),Vector3::Random()); } SE3Tpl & setRandom () { Quaternion_t q(Vector4::Random()); q.normalize (); rot = q.matrix (); trans.setRandom (); return *this; } public: Matrix4 toHomogeneousMatrix_impl() const { Matrix4 M; M.template block<3,3>(LINEAR,LINEAR) = rot; M.template block<3,1>(LINEAR,ANGULAR) = trans; M.template block<1,3>(ANGULAR,LINEAR).setZero(); M(3,3) = 1; return M; } /// Vb.toVector() = bXa.toMatrix() * Va.toVector() Matrix6 toActionMatrix_impl() const { Matrix6 M; M.template block<3,3>(ANGULAR,ANGULAR) = M.template block<3,3>(LINEAR,LINEAR) = rot; M.template block<3,3>(ANGULAR,LINEAR).setZero(); M.template block<3,3>(LINEAR,ANGULAR) = skew(trans) * M.template block<3,3>(ANGULAR,ANGULAR); return M; } void disp_impl(std::ostream & os) const { os << " R =\n" << rot << std::endl << " p = " << trans.transpose() << std::endl; } /// --- GROUP ACTIONS ON M6, F6 and I6 --- /// ay = aXb.act(by) template<typename D> typename internal::ActionReturn<D>::Type act_impl (const D & d) const { return d.se3Action(*this); } /// by = aXb.actInv(ay) template<typename D> typename internal::ActionReturn<D>::Type actInv_impl(const D & d) const { return d.se3ActionInverse(*this); } Vector3 act_impl (const Vector3& p) const { return (rot*p+trans).eval(); } Vector3 actInv_impl(const Vector3& p) const { return (rot.transpose()*(p-trans)).eval(); } SE3Tpl act_impl (const SE3Tpl& m2) const { return SE3Tpl( rot*m2.rot,trans+rot*m2.trans);} SE3Tpl actInv_impl (const SE3Tpl& m2) const { return SE3Tpl( rot.transpose()*m2.rot, rot.transpose()*(m2.trans-trans));} SE3Tpl __mult__(const SE3Tpl & m2) const { return this->act(m2);} bool __equal__( const SE3Tpl & m2 ) const { return (rotation_impl() == m2.rotation() && translation_impl() == m2.translation()); } bool isApprox_impl( const SE3Tpl & m2 ) const { Matrix4 diff( toHomogeneousMatrix_impl() - m2.toHomogeneousMatrix_impl()); return (diff.isMuchSmallerThan(toHomogeneousMatrix_impl(), 1e-14) && diff.isMuchSmallerThan(m2.toHomogeneousMatrix_impl(), 1e-14) ); } public: const Angular_t & rotation_impl() const { return rot; } Angular_t & rotation_impl() { return rot; } void rotation_impl(const Angular_t & R) { rot = R; } const Linear_t & translation_impl() const { return trans;} Linear_t & translation_impl() { return trans;} void translation_impl(const Linear_t & p) { trans=p; } protected: Angular_t rot; Linear_t trans; }; // class SE3Tpl typedef SE3Tpl<double,0> SE3; } // namespace se3 #endif // ifndef __se3_se3_hpp__
aelkhour/pinocchio
src/spatial/se3.hpp
C++
bsd-2-clause
8,904
/* Copyright (c) 2012-2013, Politecnico di Milano. All rights reserved. Andrea Zoppi <[email protected]> Martino Migliavacca <[email protected]> http://airlab.elet.polimi.it/ http://www.openrobots.com/ 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. */ /** * @file urosNode.c * @author Andrea Zoppi <[email protected]> * * @brief Node features of the middleware. */ /*===========================================================================*/ /* HEADER FILES */ /*===========================================================================*/ #include "../include/urosBase.h" #include "../include/urosUser.h" #include "../include/urosNode.h" #include "../include/urosRpcCall.h" #include "../include/urosRpcParser.h" #include <string.h> #define DEBUG 0 /*===========================================================================*/ /* LOCAL TYPES & MACROS */ /*===========================================================================*/ #if UROS_NODE_C_USE_ASSERT == UROS_FALSE && !defined(__DOXYGEN__) #undef urosAssert #define urosAssert(expr) #endif #if UROS_NODE_C_USE_ERROR_MSG == UROS_FALSE && !defined(__DOXYGEN__) #undef urosError #define urosError(when, action, msgargs) { if (when) { action; } } #endif /*===========================================================================*/ /* LOCAL VARIABLES */ /*===========================================================================*/ /** @brief Node thread stack.*/ static UROS_STACK(urosNodeThreadStack, UROS_NODE_THREAD_STKSIZE); /** @brief XMLRPC Listener thread stack.*/ static UROS_STACK(xmlrpcListenerStack, UROS_XMLRPC_LISTENER_STKSIZE); /** @brief TCPROS Listener thread stack.*/ static UROS_STACK(tcprosListenerStack, UROS_TCPROS_LISTENER_STKSIZE); /** @brief XMLRPC Slave server worker thread stacks.*/ static UROS_STACKPOOL(slaveMemPoolChunk, UROS_XMLRPC_SLAVE_STKSIZE, UROS_XMLRPC_SLAVE_POOLSIZE); /** @brief TCPROS Client worker thread stacks.*/ static UROS_STACKPOOL(tcpcliMemPoolChunk, UROS_TCPROS_CLIENT_STKSIZE, UROS_TCPROS_CLIENT_POOLSIZE); /** @brief TCPROS Server worker thread stacks.*/ static UROS_STACKPOOL(tcpsvrMemPoolChunk, UROS_TCPROS_SERVER_STKSIZE, UROS_TCPROS_SERVER_POOLSIZE); /*===========================================================================*/ /* GLOBAL VARIABLES */ /*===========================================================================*/ /** * @brief Node singleton. */ UrosNode urosNode; /*===========================================================================*/ /* LOCAL FUNCTIONS */ /*===========================================================================*/ void uros_node_createthreads(void) { static UrosNodeStatus *const stp = &urosNode.status; uros_err_t err; (void)err; urosAssert(stp->xmlrpcListenerId == UROS_NULL_THREADID); urosAssert(stp->tcprosListenerId == UROS_NULL_THREADID); /* Fill the worker thread pools.*/ #if DEBUG sleep(1); printf("%s\n", stp->tcpcliThdPool.namep); #endif /* Subscribe thread */ printf("Subscribe Thread ID\n"); err = urosThreadPoolCreateAll(&stp->tcpcliThdPool); urosAssert(err == UROS_OK); /* Publish thread */ printf("Publish Thread ID\n"); err = urosThreadPoolCreateAll(&stp->tcpsvrThdPool); urosAssert(err == UROS_OK); printf("Servece? Thread ID\n"); err = urosThreadPoolCreateAll(&stp->slaveThdPool); urosAssert(err == UROS_OK); /* Spawn the XMLRPC Slave listener threads.*/ err = urosThreadCreateStatic(&stp->xmlrpcListenerId, "RpcSlaveLis", UROS_XMLRPC_LISTENER_PRIO, (uros_proc_f)urosRpcSlaveListenerThread, NULL, xmlrpcListenerStack, UROS_XMLRPC_LISTENER_STKSIZE); urosAssert(err == UROS_OK); /* Spawn the TCPROS listener thread.*/ err = urosThreadCreateStatic(&stp->tcprosListenerId, "TcpRosLis", UROS_TCPROS_LISTENER_PRIO, (uros_proc_f)urosTcpRosListenerThread, NULL, tcprosListenerStack, UROS_TCPROS_LISTENER_STKSIZE); urosAssert(err == UROS_OK); } void uros_node_jointhreads(void) { static const UrosNodeConfig *const cfgp = &urosNode.config; static UrosNodeStatus *const stp = &urosNode.status; UrosConn conn; uros_err_t err; (void)err; urosAssert(stp->xmlrpcListenerId != UROS_NULL_THREADID); urosAssert(stp->tcprosListenerId != UROS_NULL_THREADID); /* Join the XMLRPC Slave listener threads.*/ urosConnObjectInit(&conn); urosConnCreate(&conn, UROS_PROTO_TCP); urosConnConnect(&conn, &cfgp->xmlrpcAddr); urosConnClose(&conn); err = urosThreadJoin(stp->xmlrpcListenerId); urosAssert(err == UROS_OK); stp->xmlrpcListenerId = UROS_NULL_THREADID; /* Join the TCPROS listener thread.*/ urosConnObjectInit(&conn); urosConnCreate(&conn, UROS_PROTO_TCP); urosConnConnect(&conn, &cfgp->tcprosAddr); urosConnClose(&conn); err = urosThreadJoin(stp->tcprosListenerId); urosAssert(err == UROS_OK); stp->tcprosListenerId = UROS_NULL_THREADID; /* Join the worker thread pools.*/ err = urosThreadPoolJoinAll(&stp->tcpcliThdPool); urosAssert(err == UROS_OK); err = urosThreadPoolJoinAll(&stp->tcpsvrThdPool); urosAssert(err == UROS_OK); err = urosThreadPoolJoinAll(&stp->slaveThdPool); urosAssert(err == UROS_OK); } uros_err_t uros_node_pollmaster(void) { static const UrosNodeConfig *const cfgp = &urosNode.config; UrosRpcResponse res; uros_err_t err; /* Check if the Master can reply to a getPid() request.*/ urosRpcResponseObjectInit(&res); err = urosRpcCallGetPid( &cfgp->masterAddr, &cfgp->xmlrpcUri, &res ); urosRpcResponseClean(&res); return err; } void uros_node_registerall(void) { /* Register topics.*/ urosUserPublishTopics(); urosUserSubscribeTopics(); /* Register services.*/ urosUserPublishServices(); /* Register parameters.*/ urosUserSubscribeParams(); } void uros_node_unregisterall(void) { static UrosNodeStatus *const stp = &urosNode.status; UrosListNode *np; UrosString exitMsg; /* Get the exit message.*/ urosMutexLock(&stp->stateLock); exitMsg = stp->exitMsg; stp->exitMsg = urosStringAssignZ(NULL); urosMutexUnlock(&stp->stateLock); /* Exit from all the registered TCPROS worker threads.*/ urosMutexLock(&stp->pubTcpListLock); for (np = stp->pubTcpList.headp; np != NULL; np = np->nextp) { urosTcpRosStatusIssueExit((UrosTcpRosStatus*)np->datap); } urosMutexUnlock(&stp->pubTcpListLock); urosMutexLock(&stp->subTcpListLock); for (np = stp->subTcpList.headp; np != NULL; np = np->nextp) { urosTcpRosStatusIssueExit((UrosTcpRosStatus*)np->datap); } urosMutexUnlock(&stp->subTcpListLock); /* Call the shutdown function provided by the user.*/ urosUserShutdown(&exitMsg); urosStringClean(&exitMsg); /* Unregister topics.*/ urosUserUnpublishTopics(); urosUserUnsubscribeTopics(); /* Unregister services.*/ urosUserUnpublishServices(); /* Unregister parameters.*/ urosUserUnsubscribeParams(); } /*===========================================================================*/ /* GLOBAL FUNCTIONS */ /*===========================================================================*/ /** @addtogroup node_funcs */ /** @{ */ /** * @brief Initializes a node object. * @details This procedure: * - loads a nullified configuration * - initializes the status lists * - initializes the status locks * - initializes and allocates memory pools * - initializes thread pools * * @pre The node has not been initialized yet. * * @param[in,out] np * Pointer to the @p UrosNode to be initialized. */ void urosNodeObjectInit(UrosNode *np) { UrosNodeStatus *stp; urosAssert(np != NULL); /* Invalidate configuration variables.*/ memset((void*)&np->config, 0, sizeof(UrosNodeConfig)); /* Initialize status variables.*/ stp = &np->status; stp->state = UROS_NODE_UNINIT; stp->xmlrpcPid = ~0; urosListObjectInit(&stp->subTopicList); urosListObjectInit(&stp->pubTopicList); urosListObjectInit(&stp->pubServiceList); urosListObjectInit(&stp->subParamList); urosListObjectInit(&stp->subTcpList); urosListObjectInit(&stp->pubTcpList); stp->xmlrpcListenerId = UROS_NULL_THREADID; stp->tcprosListenerId = UROS_NULL_THREADID; urosMutexObjectInit(&stp->stateLock); urosMutexObjectInit(&stp->xmlrpcPidLock); urosMutexObjectInit(&stp->subTopicListLock); urosMutexObjectInit(&stp->pubTopicListLock); urosMutexObjectInit(&stp->pubServiceListLock); urosMutexObjectInit(&stp->subParamListLock); urosMutexObjectInit(&stp->subTcpListLock); urosMutexObjectInit(&stp->pubTcpListLock); stp->exitFlag = UROS_FALSE; /* Initialize mempools with their description.*/ urosMemPoolObjectInit(&stp->slaveMemPool, UROS_STACKPOOL_BLKSIZE(UROS_XMLRPC_SLAVE_STKSIZE), NULL); urosMemPoolObjectInit(&stp->tcpcliMemPool, UROS_STACKPOOL_BLKSIZE(UROS_TCPROS_CLIENT_STKSIZE), NULL); urosMemPoolObjectInit(&stp->tcpsvrMemPool, UROS_STACKPOOL_BLKSIZE(UROS_TCPROS_SERVER_STKSIZE), NULL); /* Load the actual memory chunks for worker thread stacks.*/ urosMemPoolLoadArray(&stp->slaveMemPool, slaveMemPoolChunk, UROS_XMLRPC_SLAVE_POOLSIZE); urosMemPoolLoadArray(&stp->tcpcliMemPool, tcpcliMemPoolChunk, UROS_TCPROS_CLIENT_POOLSIZE); urosMemPoolLoadArray(&stp->tcpsvrMemPool, tcpsvrMemPoolChunk, UROS_TCPROS_SERVER_POOLSIZE); /* Initialize thread pools.*/ urosThreadPoolObjectInit(&stp->tcpcliThdPool, &stp->tcpcliMemPool, (uros_proc_f)urosTcpRosClientThread, "TcpRosCli", UROS_TCPROS_CLIENT_PRIO); urosThreadPoolObjectInit(&stp->tcpsvrThdPool, &stp->tcpsvrMemPool, (uros_proc_f)urosTcpRosServerThread, "TcpRosSvr", UROS_TCPROS_SERVER_PRIO); urosThreadPoolObjectInit(&stp->slaveThdPool, &stp->slaveMemPool, (uros_proc_f)urosRpcSlaveServerThread, "RpcSlaveSvr", UROS_XMLRPC_SLAVE_PRIO); /* The node is initialized and stopped.*/ urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_IDLE; urosMutexUnlock(&stp->stateLock); } /** * @brief Creates the main Node thread. * @note Should be called at system startup, after @p urosInit(). * * @return * Error code. */ uros_err_t urosNodeCreateThread(void) { urosAssert(urosNode.status.exitFlag == UROS_FALSE); urosNode.status.exitFlag = UROS_FALSE; return urosThreadCreateStatic( &urosNode.status.nodeThreadId, "urosNode", UROS_NODE_THREAD_PRIO, (uros_proc_f)urosNodeThread, NULL, urosNodeThreadStack, UROS_NODE_THREAD_STKSIZE ); } /** * @brief Node thread. * @details This thread handles the whole life of the local node, including * (un)registration (from)to the Master, thread pool magnagement, * node shutdown, and so on. * * @param[in] argp * Ignored. * @return * Error code. */ uros_err_t urosNodeThread(void *argp) { static UrosNodeStatus *const stp = &urosNode.status; uros_bool_t exitFlag; (void)argp; #if UROS_NODE_C_USE_ASSERT urosMutexLock(&stp->stateLock); urosAssert(stp->state == UROS_NODE_IDLE); urosMutexUnlock(&stp->stateLock); #endif urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_STARTUP; urosMutexUnlock(&stp->stateLock); /* Create the listener and pool threads.*/ uros_node_createthreads(); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); while (!exitFlag) { /* Check if the Master is alive.*/ if (uros_node_pollmaster() != UROS_OK) { /* Add a delay not to flood in case of short timeouts.*/ urosThreadSleepSec(3); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); continue; } /* Register to the Master.*/ uros_node_registerall(); urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_RUNNING; urosMutexUnlock(&stp->stateLock); /* Check if the Master is alive every 3 seconds.*/ urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); while (!exitFlag) { #if UROS_NODE_POLL_MASTER urosError(uros_node_pollmaster() != UROS_OK, break, ("Master node "UROS_IPFMT" lost\n", UROS_IPARG(&urosNode.config.masterAddr.ip))); #endif urosThreadSleepMsec(UROS_NODE_POLL_PERIOD); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; urosMutexUnlock(&stp->stateLock); } urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_SHUTDOWN; urosMutexUnlock(&stp->stateLock); /* Unregister from the Master*/ uros_node_unregisterall(); urosMutexLock(&stp->stateLock); exitFlag = stp->exitFlag; if (!exitFlag) { /* The node has simply lost sight of the Master, restart.*/ stp->state = UROS_NODE_STARTUP; } urosMutexUnlock(&stp->stateLock); } /* Join listener and pool threads.*/ uros_node_jointhreads(); /* The node has shut down.*/ urosMutexLock(&stp->stateLock); stp->state = UROS_NODE_IDLE; urosMutexUnlock(&stp->stateLock); return UROS_OK; } /** * @brief Loads the default node configuration. * @details Any previously allocated data is freed, then the default node * configuration is loaded. * * @pre The related @p UrosNode is initialized. * * @param[in,out] cfgp * Pointer to the target configuration descriptor. */ void urosNodeConfigLoadDefaults(UrosNodeConfig *cfgp) { urosAssert(cfgp != NULL); urosAssert(UROS_XMLRPC_LISTENER_PORT != UROS_TCPROS_LISTENER_PORT); /* Deallocate any previously allocated data.*/ urosStringClean(&cfgp->nodeName); urosStringClean(&cfgp->xmlrpcUri); urosStringClean(&cfgp->tcprosUri); urosStringClean(&cfgp->masterUri); /* Load default values.*/ cfgp->nodeName = urosStringCloneZ(UROS_NODE_NAME); cfgp->xmlrpcAddr.ip.dword = UROS_XMLRPC_LISTENER_IP; cfgp->xmlrpcAddr.port = UROS_XMLRPC_LISTENER_PORT; cfgp->xmlrpcUri = urosStringCloneZ( "http://"UROS_XMLRPC_LISTENER_IP_SZ ":"UROS_STRINGIFY2(UROS_XMLRPC_LISTENER_PORT)); cfgp->tcprosAddr.ip.dword = UROS_TCPROS_LISTENER_IP; cfgp->tcprosAddr.port = UROS_TCPROS_LISTENER_PORT; cfgp->tcprosUri = urosStringCloneZ( "rosrpc://"UROS_TCPROS_LISTENER_IP_SZ ":"UROS_STRINGIFY2(UROS_TCPROS_LISTENER_PORT)); cfgp->masterAddr.ip.dword = UROS_XMLRPC_MASTER_IP; cfgp->masterAddr.port = UROS_XMLRPC_MASTER_PORT; cfgp->masterUri = urosStringCloneZ( "http://"UROS_XMLRPC_MASTER_IP_SZ ":"UROS_STRINGIFY2(UROS_XMLRPC_MASTER_PORT)); } /** * @brief Publishes a topic. * @details Issues a @p publishTopic() call to the XMLRPC Master. * @see urosRpcCallRegisterPublisher() * @see urosNodePublishTopicByDesc() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is not published. * @pre The TCPROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name string. * @param[in] typep * Pointer to the topic message type name string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodePublishTopic(const UrosString *namep, const UrosString *typep, uros_proc_f procf, uros_topicflags_t flags) { static UrosNode *const np = &urosNode; UrosTopic *topicp; const UrosMsgType *statictypep; UrosListNode *topicnodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(procf != NULL); urosAssert(!flags.service); /* Get the registered message type.*/ statictypep = urosFindStaticMsgType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown message type [%.*s]\n", UROS_STRARG(typep))); /* Check if the topic already exists.*/ urosMutexLock(&np->status.pubTopicListLock); topicnodep = urosTopicListFindByName(&np->status.pubTopicList, namep); urosMutexUnlock(&np->status.pubTopicListLock); urosError(topicnodep != NULL, return UROS_ERR_BADPARAM, ("Topic [%.*s] already published\n", UROS_STRARG(namep))); /* Create a new topic descriptor.*/ topicp = urosNew(NULL, UrosTopic); if (topicp == NULL) { return UROS_ERR_NOMEM; } urosTopicObjectInit(topicp); topicp->name = urosStringClone(namep); topicp->typep = statictypep; topicp->procf = procf; topicp->flags = flags; /* Publish the topic.*/ err = urosNodePublishTopicByDesc(topicp); if (err != UROS_OK) { urosTopicDelete(topicp); } return err; } /** * @brief Publishes a topic. * @details Issues a @p publishTopic() call to the XMLRPC Master. * @see urosRpcCallRegisterPublisher() * @see urosNodePublishTopicByDesc() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is not published. * @pre The TPCROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name null-terminated string. * @param[in] typep * Pointer to the topic message type name null-terminated string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodePublishTopicSZ(const char *namep, const char *typep, uros_proc_f procf, uros_topicflags_t flags) { UrosString namestr, typestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(procf != NULL); urosAssert(!flags.service); namestr = urosStringAssignZ(namep); typestr = urosStringAssignZ(typep); return urosNodePublishTopic(&namestr, &typestr, procf, flags); } /** * @brief Publishes a topic by its descriptor. * @details Issues a @p publishTopic() call to the XMLRPC Master. * @see urosRpcCallRegisterPublisher() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is not published. * @pre The topic descriptor must have the @p service flag set to @p 0. * @post The topic descriptor is used the following way: * - If successful, the topic descriptor is referenced by the topic * registry, and is no longer modifiable by the caller function. * - If unsuccessful, the topic descriptor can be deallocated by the * caller function. * @pre The TCPROS @p service flag must be clear. * * @param[in] topicp * Pointer to the topic descriptor to be published and registered. * @return * Error code. */ uros_err_t urosNodePublishTopicByDesc(UrosTopic *topicp) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosListNode *nodep; urosAssert(topicp != NULL); urosAssert(urosStringNotEmpty(&topicp->name)); urosAssert(topicp->typep != NULL); urosAssert(urosStringNotEmpty(&topicp->typep->name)); urosAssert(topicp->procf != NULL); urosAssert(!topicp->flags.service); urosAssert(topicp->refcnt == 0); urosAssert(topicp->refcnt == 0); urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.pubTopicListLock); /* Master XMLRPC registerPublisher() */ err = urosRpcCallRegisterPublisher( &np->config.masterAddr, &np->config.nodeName, &topicp->name, &topicp->typep->name, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, goto _finally, ("Error %s while registering as publisher of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(&topicp->name))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Add to the published topics list.*/ nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; } urosListNodeObjectInit(nodep); nodep->datap = (void*)topicp; urosListAdd(&np->status.pubTopicList, nodep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.pubTopicListLock); urosRpcResponseClean(&res); return err; } /** * @brief Unpublishes a topic. * @details Issues an @p unpublishTopic() call to the XMLRPC Master. * @see urosRpcCallUnregisterPublisher() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnpublishTopic(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosListNode *tcprosnodep, *topicnodep; UrosTopic *topicp; uros_err_t err; UrosRpcResponse res; urosAssert(urosStringNotEmpty(namep)); /* Find the topic descriptor.*/ urosMutexLock(&np->status.pubTopicListLock); topicnodep = urosTopicListFindByName(&np->status.pubTopicList, namep); if (topicnodep == NULL) { urosError(topicnodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Topic [%.*s] not published\n", UROS_STRARG(namep))); } topicp = (UrosTopic*)topicnodep->datap; /* Unregister the topic on the Master node.*/ err = urosRpcCallUnregisterPublisher( &np->config.masterAddr, &np->config.nodeName, namep, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, UROS_NOP, ("Error %s while unregistering as publisher of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Unregister the topic locally.*/ topicp->flags.deleted = UROS_TRUE; tcprosnodep = urosListRemove(&np->status.pubTopicList, topicnodep); urosAssert(tcprosnodep == topicnodep); if (topicp->refcnt > 0) { /* Tell each publishing TCPROS thread to exit.*/ urosMutexLock(&np->status.pubTcpListLock); for (tcprosnodep = np->status.pubTcpList.headp; tcprosnodep != NULL; tcprosnodep = tcprosnodep->nextp) { UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap; if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) { urosMutexLock(&tcpstp->threadExitMtx); tcpstp->threadExit = UROS_TRUE; urosMutexUnlock(&tcpstp->threadExitMtx); } } urosMutexUnlock(&np->status.pubTcpListLock); /* NOTE: The last exiting thread freeds the topic descriptor.*/ } else { /* No TCPROS connections, just free the descriptor immediately.*/ urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete); } _finally: urosMutexUnlock(&np->status.pubTopicListLock); return err; } /** * @brief Unpublishes a topic. * @details Issues an @p unpublishTopic() call to the XMLRPC Master. * @see urosRpcCallUnregisterPublisher() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a null-terminated string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnpublishTopicSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnpublishTopic(&namestr); } /** * @brief Subscribes to a topic. * @details Issues a @p registerSubscriber() call to the XMLRPC Master, and * connects to known publishers. * @see urosNodeSubscribeTopicByDesc() * @see urosRpcCallRegisterSubscriber() * @see urosNodeFindNewPublishers() * @see urosRpcSlaveConnectToPublishers() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * subscribe/unsubscribe to any topics. * * @pre The topic is not subscribed. * @post Connects to known publishers listed by a successful response. * @pre The TCPROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name string. * @param[in] typep * Pointer to the topic message type name string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodeSubscribeTopic(const UrosString *namep, const UrosString *typep, uros_proc_f procf, uros_topicflags_t flags) { static UrosNode *const np = &urosNode; UrosTopic *topicp; const UrosMsgType *statictypep; UrosListNode *topicnodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(procf != NULL); urosAssert(!flags.service); /* Get the registered message type.*/ statictypep = urosFindStaticMsgType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown message type [%.*s]\n", UROS_STRARG(typep))); /* Check if the topic already exists.*/ urosMutexLock(&np->status.subTopicListLock); topicnodep = urosTopicListFindByName(&np->status.subTopicList, namep); urosMutexUnlock(&np->status.subTopicListLock); urosError(topicnodep != NULL, return UROS_ERR_BADPARAM, ("Topic [%.*s] already subscribed\n", UROS_STRARG(namep))); /* Create a new topic descriptor.*/ topicp = urosNew(NULL, UrosTopic); if (topicp == NULL) { return UROS_ERR_NOMEM; } urosTopicObjectInit(topicp); topicp->name = urosStringClone(namep); topicp->typep = statictypep; topicp->procf = procf; topicp->flags = flags; /* Subscribe to the topic.*/ err = urosNodeSubscribeTopicByDesc(topicp); if (err != UROS_OK) { urosTopicDelete(topicp); } return err; } /** * @brief Subscribes to a topic. * @details Issues a @p registerSubscriber() call to the XMLRPC Master, and * connects to known publishers. * @see urosNodeSubscribeTopicByDesc() * @see urosRpcCallRegisterSubscriber() * @see urosNodeFindNewPublishers() * @see urosRpcSlaveConnectToPublishers() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * subscribe/unsubscribe to any topics. * * @pre The topic is not subscribed. * @post Connects to known publishers listed by a successful response. * @pre The TCPROS @p service flag must be clear. * * @param[in] namep * Pointer to the topic name null-terminated string. * @param[in] typep * Pointer to the topic message type name null-terminated string. * @param[in] procf * Topic handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodeSubscribeTopicSZ(const char *namep, const char *typep, uros_proc_f procf, uros_topicflags_t flags) { UrosString namestr, typestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(procf != NULL); urosAssert(!flags.service); namestr = urosStringAssignZ(namep); typestr = urosStringAssignZ(typep); return urosNodeSubscribeTopic(&namestr, &typestr, procf, flags); } /** * @brief Subscribes to a topic by its descriptor. * @details Issues a @p registerSubscriber() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallRegisterSubscriber() * @see urosNodeFindNewPublishers() * @see urosRpcSlaveConnectToPublishers() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * subscribe/unsubscribe to any topics. * * @pre The topic is not subscribed. * @pre The topic descriptor must have the @p service flag set to @p 0. * @post The topic descriptor is used the following way: * - If successful, the topic descriptor is referenced by the topic * registry, and is no longer modifiable by the caller function. * - If unsuccessful, the topic descriptor can be deallocated by the * caller function. * @post Connects to known publishers listed by a successful response. * @pre The TCPROS @p service flag must be clear. * * @param[in] topicp * Pointer to the topic descriptor to be subscribed to and registered. * @return * Error code. */ uros_err_t urosNodeSubscribeTopicByDesc(UrosTopic *topicp) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosList newpubs; UrosListNode *nodep; urosAssert(topicp != NULL); urosAssert(urosStringNotEmpty(&topicp->name)); urosAssert(topicp->typep != NULL); urosAssert(urosStringNotEmpty(&topicp->typep->name)); urosAssert(topicp->procf != NULL); urosAssert(!topicp->flags.service); urosAssert(topicp->refcnt == 0); urosRpcResponseObjectInit(&res); urosListObjectInit(&newpubs); urosMutexLock(&np->status.subTopicListLock); /* Master XMLRPC registerSubscriber() */ err = urosRpcCallRegisterSubscriber( &np->config.masterAddr, &np->config.nodeName, &topicp->name, &topicp->typep->name, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, goto _finally, ("Cannot register as subscriber of topic [%.*s]\n", UROS_STRARG(&topicp->name))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Connect to registered publishers.*/ err = urosNodeFindNewTopicPublishers(&topicp->name, res.valuep, &newpubs); urosError(err != UROS_OK, goto _finally, ("Error %s while finding new publishers of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(&topicp->name))); urosRpcResponseClean(&res); err = urosRpcSlaveConnectToPublishers(&topicp->name, &newpubs); urosError(err != UROS_OK, goto _finally, ("Error %s while connecting to new publishers of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(&topicp->name))); /* Add to the subscribed topics list.*/ nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; } urosListNodeObjectInit(nodep); nodep->datap = (void*)topicp; urosListAdd(&np->status.subTopicList, nodep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.subTopicListLock); urosListClean(&newpubs, (uros_delete_f)urosFree); urosRpcResponseClean(&res); return err; } /** * @brief Unsubscribes to a topic. * @details Issues an @p unregisterSubscriber() call to the XMLRPC Master. * @see urosRpcCallUnregisterSubscriber() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no subscribing TCPROS threads, or * - by the last subscribing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnsubscribeTopic(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosListNode *tcprosnodep, *topicnodep; UrosTopic *topicp; UrosTcpRosStatus *tcpstp; uros_err_t err; UrosRpcResponse res; urosAssert(urosStringNotEmpty(namep)); /* Find the topic descriptor.*/ urosMutexLock(&np->status.subTopicListLock); topicnodep = urosTopicListFindByName(&np->status.subTopicList, namep); if (topicnodep == NULL) { urosError(topicnodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Topic [%.*s] not subscribed\n", UROS_STRARG(namep))); } topicp = (UrosTopic*)topicnodep->datap; /* Unregister the topic on the Master node.*/ err = urosRpcCallUnregisterSubscriber( &np->config.masterAddr, &np->config.nodeName, namep, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, UROS_NOP, ("Error %s while unregistering as subscriber of topic [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Unregister the topic locally.*/ topicp->flags.deleted = UROS_TRUE; tcprosnodep = urosListRemove(&np->status.subTopicList, topicnodep); urosAssert(tcprosnodep == topicnodep); if (topicp->refcnt > 0) { /* Tell each subscribing TCPROS thread to exit.*/ urosMutexLock(&np->status.subTcpListLock); for (tcprosnodep = np->status.subTcpList.headp; tcprosnodep != NULL; tcprosnodep = tcprosnodep->nextp) { tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap; if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) { urosMutexLock(&tcpstp->threadExitMtx); tcpstp->threadExit = UROS_TRUE; urosMutexUnlock(&tcpstp->threadExitMtx); } } urosMutexUnlock(&np->status.subTcpListLock); /* NOTE: The last exiting thread freeds the topic descriptor.*/ } else { /* No TCPROS connections, just free the descriptor immediately.*/ urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete); } _finally: urosMutexUnlock(&np->status.subTopicListLock); return err; } /** * @brief Unsubscribes to a topic. * @details Issues an @p unregisterSubscriber() call to the XMLRPC Master. * @see urosRpcCallUnregisterSubscriber() * @warning The access to the topic registry is thread-safe, but delays of the * XMLRPC communication will delay also any other threads trying to * publish/unpublish any topics. * * @pre The topic is published. * @post If successful, the topic descriptor is dereferenced by the topic * registry, and will be freed: * - by this function, if there are no subscribing TCPROS threads, or * - by the last subscribing TCPROS thread which references the topic. * * @param[in] namep * Pointer to a null-terminated string which names the topic. * @return * Error code. */ uros_err_t urosNodeUnsubscribeTopicSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnsubscribeTopic(&namestr); } /** * @brief Executes a service call. * @details Gets the service URI from the Master node. If found, it executes * the service call once, and the result is returned. * @note Only a @e single call will be executed. Persistent TCPROS service * connections need custom handlers. * * @pre The TCPROS @p service flag must be set, @p persistent clear. * * @param[in] namep * Pointer to the service name string. * @param[in] typep * Pointer to the service type name string. * @param[in] callf * Service call handler. * @param[in] flags * TCPROS flags. The @p service flag must be set, and @p persistent * must be clear. * @param[out] resobjp * Pointer to the allocated response object. The service result will * be written there only if the call is successful. * @return * Error code. */ uros_err_t urosNodeCallService(const UrosString *namep, const UrosString *typep, uros_tcpsrvcall_t callf, uros_topicflags_t flags, void *resobjp) { UrosTopic service; UrosAddr pubaddr; const UrosMsgType *statictypep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(callf != NULL); urosAssert(flags.service); urosAssert(!flags.persistent); urosAssert(resobjp != NULL); /* Get the registered message type.*/ statictypep = urosFindStaticSrvType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown service type [%.*s]\n", UROS_STRARG(typep))); /* Resolve the service provider.*/ err = urosNodeResolveServicePublisher(namep, &pubaddr); if (err != UROS_OK) { return err; } /* Call the client service handler.*/ urosTopicObjectInit(&service); service.name = *namep; service.typep = statictypep; service.procf = (uros_proc_f)callf; service.flags = flags; return urosTcpRosCallService(&pubaddr, &service, resobjp); } /** * @brief Executes a service call. * @details Gets the service URI from the Master node. If found, it executes * the service call once, and the result is returned. * @note Only a @e single call will be executed. Persistent TCPROS service * connections need custom handlers. * * @pre The TCPROS @p service flag must be set, @p persistent clear. * * @param[in] namep * Pointer to the service name null-terminated string. * @param[in] typep * Pointer to the service type name null-terminated string. * @param[in] callf * Service call handler. * @param[in] flags * TCPROS flags. The @p service flag must be set, and @p persistent * must be clear. * @param[out] resobjp * Pointer to the allocated response object. The service result will * be written there only if the call is successful. * @return * Error code. */ uros_err_t urosNodeCallServiceSZ(const char *namep, const char *typep, uros_tcpsrvcall_t callf, uros_topicflags_t flags, void *resobjp) { UrosTopic service; UrosAddr pubaddr; const UrosMsgType *statictypep; uros_err_t err; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(callf != NULL); urosAssert(flags.service); urosAssert(!flags.persistent); urosAssert(resobjp != NULL); /* Get the registered message type.*/ statictypep = urosFindStaticSrvTypeSZ(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown service type [%s]\n", typep)); /* Resolve the service provider.*/ urosTopicObjectInit(&service); service.name = urosStringAssignZ(namep); err = urosNodeResolveServicePublisher(&service.name, &pubaddr); if (err != UROS_OK) { return err; } /* Call the client service handler.*/ service.typep = statictypep; service.procf = (uros_proc_f)callf; service.flags = flags; return urosTcpRosCallService(&pubaddr, &service, resobjp); } /** * @brief Executes a service call. * @details Gets the service URI from the Master node. If found, it executes * the service call once, and the result is returned. * @note Only a @e single call will be executed. Persistent TCPROS service * connections need custom handlers. * * @pre @p servicep->procf must address a @p uros_tcpsrvcall_t function. * @pre The TCPROS @p service flag must be set, @p persistent clear. * * @param[in] servicep * Pointer to the service descriptor. * @param[out] resobjp * Pointer to the allocated response object. The service result will * be written there only if the call is successful. * @return * Error code. */ uros_err_t urosNodeCallServiceByDesc(const UrosTopic *servicep, void *resobjp) { UrosAddr pubaddr; uros_err_t err; urosAssert(servicep != NULL); urosAssert(urosStringNotEmpty(&servicep->name)); urosAssert(servicep->typep != NULL); urosAssert(urosStringNotEmpty(&servicep->typep->name)); urosAssert(servicep->procf != NULL); urosAssert(servicep->flags.service); urosAssert(!servicep->flags.persistent); urosAssert(resobjp != NULL); /* Resolve the service provider.*/ err = urosNodeResolveServicePublisher(&servicep->name, &pubaddr); if (err != UROS_OK) { return err; } /* Call the client service handler.*/ return urosTcpRosCallService(&pubaddr, servicep, resobjp); } /** * @brief Publishes a service. * @details Issues a @p registerService() call to the XMLRPC Master. * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * @see urosNodePublishServiceByDesc() * @see urosRpcCallRegisterService() * * @pre The service is not published. * @pre The TCPROS @p service flag must be set. * * @param[in] namep * Pointer to the service name string. * @param[in] typep * Pointer to the service type name string. * @param[in] procf * Service handler function. * @param[in] flags * Topic flags. * @return * Error code. */ uros_err_t urosNodePublishService(const UrosString *namep, const UrosString *typep, uros_proc_f procf, uros_topicflags_t flags) { static UrosNode *const np = &urosNode; UrosTopic *servicep; const UrosMsgType *statictypep; UrosListNode *servicenodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); urosAssert(urosStringNotEmpty(typep)); urosAssert(procf != NULL); urosAssert(flags.service); /* Get the registered service type.*/ statictypep = urosFindStaticSrvType(typep); urosError(statictypep == NULL, return UROS_ERR_BADPARAM, ("Unknown message type [%.*s]\n", UROS_STRARG(typep))); /* Check if the service already exists.*/ urosMutexLock(&np->status.pubServiceListLock); servicenodep = urosTopicListFindByName(&np->status.pubServiceList, namep); urosMutexUnlock(&np->status.pubServiceListLock); urosError(servicenodep != NULL, return UROS_ERR_BADPARAM, ("Service [%.*s] already published\n", UROS_STRARG(namep))); /* Create a new topic descriptor.*/ servicep = urosNew(NULL, UrosTopic); if (servicep == NULL) { return UROS_ERR_NOMEM; } urosTopicObjectInit(servicep); servicep->name = urosStringClone(namep); servicep->typep = statictypep; servicep->procf = procf; servicep->flags = flags; /* Try to register the topic.*/ err = urosNodePublishServiceByDesc(servicep); if (err != UROS_OK) { urosTopicDelete(servicep); } return err; } /** * @brief Publishes a service. * @details Issues a @p registerService() call to the XMLRPC Master. * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * @see urosNodePublishServiceByDesc() * @see urosRpcCallRegisterService() * * @pre The service is not published. * @pre The TCPROS @p service flag must be set. * * @param[in] namep * Pointer to the service name null-terminated string. * @param[in] typep * Pointer to the service type name null-terminated string. * @param[in] procf * Service handler function. * @param[in] flags * Service flags. * @return * Error code. */ uros_err_t urosNodePublishServiceSZ(const char *namep, const char *typep, uros_proc_f procf, uros_topicflags_t flags) { UrosString namestr, typestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); urosAssert(typep != NULL); urosAssert(typep[0] != 0); urosAssert(procf != NULL); namestr = urosStringAssignZ(namep); typestr = urosStringAssignZ(typep); return urosNodePublishService(&namestr, &typestr, procf, flags); } /** * @brief Publishes a service by its descriptor. * @details Issues a @p registerService() call to the XMLRPC Master. * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * @see urosRpcCallRegisterService() * * @pre The TCPROS @p service flag must be set. * * @pre The service is not published. * @pre The service descriptor must have the @p service flag set to @p 1. * @post - If successful, the service descriptor is referenced by the * service registry, and is no longer modifiable by the caller * function. * - If unsuccessful, the service descriptor can be deallocated by the * caller function. * * @param[in] servicep * Pointer to the service descriptor to be published and registered. * @return * Error code. */ uros_err_t urosNodePublishServiceByDesc(const UrosTopic *servicep) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosListNode *nodep; urosAssert(servicep != NULL); urosAssert(urosStringNotEmpty(&servicep->name)); urosAssert(servicep->typep != NULL); urosAssert(urosStringNotEmpty(&servicep->typep->name)); urosAssert(servicep->procf != NULL); urosAssert(servicep->flags.service); urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.pubServiceListLock); /* Master XMLRPC registerPublisher() */ err = urosRpcCallRegisterService( &np->config.masterAddr, &np->config.nodeName, &servicep->name, &np->config.tcprosUri, &np->config.xmlrpcUri, &res ); urosError(err != UROS_OK, goto _finally, ("Cannot register service [%.*s]\n", UROS_STRARG(&servicep->name))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Add to the published topics list.*/ nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; } urosListNodeObjectInit(nodep); nodep->datap = (void*)servicep; urosListAdd(&np->status.pubServiceList, nodep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.pubServiceListLock); urosRpcResponseClean(&res); return err; } /** * @brief Unpublishes a service. * @details Issues an @p unregisterService() call to the XMLRPC Master. * @see urosRpcCallUnregisterService() * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * * @pre The service is published. * @post If successful, the service descriptor is dereferenced by the * service registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the * service. * * @param[in] namep * Pointer to a string which names the service. * @return * Error code. */ uros_err_t urosNodeUnpublishService(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosListNode *tcprosnodep, *servicenodep; UrosTopic *servicep; uros_err_t err; UrosRpcResponse res; urosAssert(urosStringNotEmpty(namep)); /* Find the service descriptor.*/ urosMutexLock(&np->status.pubServiceListLock); servicenodep = urosTopicListFindByName(&np->status.pubServiceList, namep); urosError(servicenodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Service [%.*s] not published\n", UROS_STRARG(namep))); servicep = (UrosTopic*)servicenodep->datap; /* Unregister the service on the Master node.*/ err = urosRpcCallUnregisterService( &np->config.masterAddr, &np->config.nodeName, namep, &np->config.tcprosUri, &res ); urosError(err != UROS_OK, goto _finally, ("Error %s while unregistering as publisher of service [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Unregister the service locally.*/ servicep->flags.deleted = UROS_TRUE; tcprosnodep = urosListRemove(&np->status.pubServiceList, servicenodep); urosAssert(tcprosnodep == servicenodep); if (np->status.pubTcpList.length > 0) { /* Tell each publishing TCPROS thread to exit.*/ urosMutexLock(&np->status.pubTcpListLock); for (tcprosnodep = np->status.pubTcpList.headp; tcprosnodep != NULL; tcprosnodep = tcprosnodep->nextp) { UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap; if (tcpstp->topicp == servicep && tcpstp->topicp->flags.service) { urosMutexLock(&tcpstp->threadExitMtx); tcpstp->threadExit = UROS_TRUE; urosMutexUnlock(&tcpstp->threadExitMtx); } } urosMutexUnlock(&np->status.pubTcpListLock); /* NOTE: The last exiting thread freeds the service descriptor.*/ } else { /* No TCPROS connections, just free the descriptor immediately.*/ urosListNodeDelete(servicenodep, (uros_delete_f)urosTopicDelete); } _finally: urosMutexUnlock(&np->status.pubServiceListLock); return err; } /** * @brief Unpublishes a service. * @details Issues an @p unregisterService() call to the XMLRPC Master. * @see urosRpcCallUnregisterService() * @warning The access to the service registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to publish/unpublish any services. * * @pre The service is published. * @post If successful, the service descriptor is dereferenced by the * service registry, and will be freed: * - by this function, if there are no publishing TCPROS threads, or * - by the last publishing TCPROS thread which references the * service. * * @param[in] namep * Pointer to a null-terminated string which names the service. * @return * Error code. */ uros_err_t urosNodeUnpublishServiceSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnpublishService(&namestr); } /** * @brief Subscribes to a parameter by its descriptor. * @details Issues a @p subscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallSubscribeParam() * @see urosNodeSubscribeParamByDesc() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has not been registered yet. * * @param[in] namep * Pointer to the parameter name string. * @return * Error code. */ uros_err_t urosNodeSubscribeParam(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosString *clonednamep; UrosListNode *paramnodep; UrosRpcResponse res; UrosListNode *nodep; uros_err_t err; urosAssert(urosStringNotEmpty(namep)); /* Check if the parameter already exists.*/ urosMutexLock(&np->status.subParamListLock); paramnodep = urosStringListFindByName(&np->status.subParamList, namep); urosMutexUnlock(&np->status.subParamListLock); urosError(paramnodep != NULL, return UROS_ERR_BADPARAM, ("Parameter [%.*s] already subscribed\n", UROS_STRARG(namep))); /* Create the storage data in advance.*/ clonednamep = urosNew(NULL, UrosString); if (clonednamep == NULL) { return UROS_ERR_NOMEM; } *clonednamep = urosStringClone(namep); nodep = urosNew(NULL, UrosListNode); if (clonednamep->datap == NULL || nodep == NULL) { urosStringDelete(clonednamep); urosFree(nodep); return UROS_ERR_NOMEM; } /* Subscribe to the topic.*/ urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.subParamListLock); /* Master XMLRPC registerSubscriber() */ err = urosRpcCallSubscribeParam( &np->config.masterAddr, &np->config.nodeName, &np->config.xmlrpcUri, namep, &res ); urosError(err != UROS_OK, goto _finally, ("Error %s while subscribing to parameter [%.*s]\n", urosErrorText(err), UROS_STRARG(namep))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %d, expected %d\n", res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %d, expected 200\n", res.httpcode)); /* Add to the subscribed parameter list.*/ urosListNodeObjectInit(nodep); nodep->datap = (void*)clonednamep; urosListAdd(&np->status.subParamList, nodep); /* Update to the current value.*/ urosUserParamUpdate(namep, res.valuep); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.subParamListLock); urosRpcResponseClean(&res); return err; } /** * @brief Subscribes to a parameter. * @details Issues a @p subscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallSubscribeParam() * @see urosNodeSubscribeParamByDesc() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has not been registered yet. * * @param[in] namep * Pointer to the parameter name null-terminated string. * @return * Error code. */ uros_err_t urosNodeSubscribeParamSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeSubscribeParam(&namestr); } /** * @brief Subscribes to a parameter. * @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallUnubscribeParam() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has been registered. * @post If successful, the parameter descriptor is unreferenced and deleted * by the parameter registry. * * @param[in] namep * Pointer to a string which names the parameter to be unregistered. * @return * Error code. */ uros_err_t urosNodeUnsubscribeParam(const UrosString *namep) { static UrosNode *const np = &urosNode; UrosRpcResponse res; uros_err_t err; UrosListNode *nodep; urosAssert(urosStringNotEmpty(namep)); urosRpcResponseObjectInit(&res); urosMutexLock(&np->status.subParamListLock); /* Check if the parameter was actually subscribed.*/ nodep = urosStringListFindByName(&np->status.subParamList, namep); urosError(nodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Parameter [%.*s] not found\n", UROS_STRARG(namep))); /* Master XMLRPC registerSubscriber() */ err = urosRpcCallUnsubscribeParam( &np->config.masterAddr, &np->config.nodeName, &np->config.xmlrpcUri, namep, &res ); urosError(err != UROS_OK, goto _finally, ("Cannot unsubscribe from param [%.*s]\n", UROS_STRARG(namep))); /* Check for valid codes.*/ urosError(res.code != UROS_RPCC_SUCCESS, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response code %ld, expected %d\n", (long int)res.code, UROS_RPCC_SUCCESS)); urosError(res.httpcode != 200, { err = UROS_ERR_BADPARAM; goto _finally; }, ("Response HTTP code %ld, expected 200\n", (long int)res.httpcode)); /* Remove from the subscribed parameter list and delete.*/ nodep = urosListRemove(&np->status.subParamList, nodep); urosAssert(nodep != NULL); urosListNodeDelete(nodep, (uros_delete_f)urosStringDelete); err = UROS_OK; _finally: /* Cleanup and return.*/ urosMutexUnlock(&np->status.subParamListLock); urosRpcResponseClean(&res); return err; } /** * @brief Subscribes to a parameter. * @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and * connects to known publishers. * @see urosRpcCallUnubscribeParam() * @warning The access to the parameter registry is thread-safe, but delays of * the XMLRPC communication will delay also any other threads trying * to subscribe/unsubscribe to any parameters. * * @pre The parameter has been registered. * @post If successful, the parameter descriptor is unreferenced and deleted * by the parameter registry. * * @param[in] namep * Pointer to a null-terminated string which names the parameter to be * unregistered. * @return * Error code. */ uros_err_t urosNodeUnsubscribeParamSZ(const char *namep) { UrosString namestr; urosAssert(namep != NULL); urosAssert(namep[0] != 0); namestr = urosStringAssignZ(namep); return urosNodeUnsubscribeParam(&namestr); } /** * @brief Find new publishers for a given topic. * @details Scans through the provided publishers list to look for any new * publishers. * * @param[in] namep * Pointer to a non-empty string which names the targeted topic. * @param[in] publishersp * Pointer to an @p UrosRpcParam with @p UROS_RPCP_ARRAY pclass. * It contains the list of current publishers, received for example * through a XMLRPC call to @p subscribeTopic(). Each publisher is * addressed by its URI. * @param[out] newpubsp * Pointer to an empty list which will be populated by the newly * discovered publishers, if any. * @return * Error code. */ uros_err_t urosNodeFindNewTopicPublishers(const UrosString *namep, const UrosRpcParam *publishersp, UrosList *newpubsp) { static UrosNode *const np = &urosNode; uros_err_t err; const UrosListNode *tcpnodep; const UrosRpcParamNode *paramnodep; const UrosTcpRosStatus *tcpstp, *tcpfoundp; const UrosString *urip; UrosAddr pubaddr; (void)err; urosAssert(urosStringNotEmpty(namep)); urosAssert(publishersp != NULL); urosAssert(publishersp->pclass == UROS_RPCP_ARRAY); urosAssert(publishersp->value.listp != NULL); urosAssert(urosListIsValid(newpubsp)); urosAssert(newpubsp->length == 0); /* Build a list of newly discovered publishers.*/ urosMutexLock(&np->status.subTcpListLock); for (paramnodep = publishersp->value.listp->headp; paramnodep != NULL; paramnodep = paramnodep->nextp) { urip = &paramnodep->param.value.string; err = urosUriToAddr(urip, &pubaddr); urosAssert(err == UROS_OK); tcpfoundp = NULL; for (tcpnodep = np->status.subTcpList.headp; tcpnodep != NULL; tcpnodep = tcpnodep->nextp) { tcpstp = (const UrosTcpRosStatus *)tcpnodep->datap; if (tcpstp->topicp->flags.service == UROS_FALSE) { urosAssert(tcpstp->topicp != NULL); if (0 == urosStringCmp(&tcpstp->topicp->name, namep)) { urosAssert(tcpstp->csp != NULL); if (tcpstp->csp->remaddr.ip.dword == pubaddr.ip.dword && tcpstp->csp->remaddr.port == pubaddr.port) { tcpfoundp = tcpstp; } } } } if (tcpfoundp == NULL) { UrosAddr *addrp; UrosListNode *nodep; /* New publisher.*/ addrp = urosNew(NULL, UrosAddr); if (addrp == NULL) { urosMutexUnlock(&np->status.subTcpListLock); return UROS_ERR_NOMEM; } nodep = urosNew(NULL, UrosListNode); if (nodep == NULL) { urosFree(addrp); urosMutexUnlock(&np->status.subTcpListLock); return UROS_ERR_NOMEM; } *addrp = pubaddr; nodep->datap = addrp; nodep->nextp = NULL; urosListAdd(newpubsp, nodep); } } urosMutexUnlock(&np->status.subTcpListLock); return UROS_OK; } /** * @brief Gets the TCPROS URI of a topic publisher. * @details Requests the TCPROS URI of a topic published by a node. * * @param[in] apiaddrp * XMLRPC API address of the target node. * @param[in] namep * Pointer to the topic name string. * @param[out] tcprosaddrp * Pointer to an allocated @p UrosAddr descriptor, which will hold the * TCPROS API address of the requested topic provider. * @return * Error code. */ uros_err_t urosNodeResolveTopicPublisher(const UrosAddr *apiaddrp, const UrosString *namep, UrosAddr *tcprosaddrp) { static const UrosRpcParamNode tcprosnode = { { UROS_RPCP_STRING, {{ 6, "TCPROS" }} }, NULL }; static const UrosRpcParamList tcproslist = { (UrosRpcParamNode*)&tcprosnode, (UrosRpcParamNode*)&tcprosnode, 1 }; static const UrosRpcParamNode protonode = { { UROS_RPCP_ARRAY, {{ (size_t)&tcproslist, NULL }} }, NULL }; static const UrosRpcParamList protolist = { (UrosRpcParamNode*)&protonode, (UrosRpcParamNode*)&protonode, 1 }; uros_err_t err; UrosRpcParamNode *nodep; UrosRpcParam *paramp; UrosRpcResponse res; urosAssert(apiaddrp != NULL); urosAssert(urosStringNotEmpty(namep)); urosAssert(tcprosaddrp != NULL); #define _ERR { err = UROS_ERR_BADPARAM; goto _finally; } /* Request the topic to the publisher.*/ urosRpcResponseObjectInit(&res); err = urosRpcCallRequestTopic( apiaddrp, &urosNode.config.nodeName, namep, &protolist, &res ); /* Check for valid values.*/ if (err != UROS_OK) { goto _finally; } urosError(res.httpcode != 200, _ERR, ("The HTTP response code is %lu, expected 200\n", (long unsigned int)res.httpcode)); if (res.code != UROS_RPCC_SUCCESS) { _ERR } urosError(res.valuep->pclass != UROS_RPCP_ARRAY, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_ARRAY)\n", (int)res.valuep->pclass, (int)UROS_RPCP_ARRAY)); urosAssert(res.valuep->value.listp != NULL); urosError(res.valuep->value.listp->length != 3, _ERR, ("Response value array length %lu, expected 3", (long unsigned int)res.valuep->value.listp->length)); nodep = res.valuep->value.listp->headp; /* Check the protocol string.*/ paramp = &nodep->param; nodep = nodep->nextp; urosError(paramp->pclass != UROS_RPCP_STRING, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n", (int)paramp->pclass, (int)UROS_RPCP_STRING)); urosError(0 != urosStringCmp(&tcprosnode.param.value.string, &paramp->value.string), _ERR, ("Response protocol is [%.*s], expected [TCPROS]\n", UROS_STRARG(&tcprosnode.param.value.string))); /* Check the node hostname string.*/ paramp = &nodep->param; nodep = nodep->nextp; urosError(paramp->pclass != UROS_RPCP_STRING, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n", (int)paramp->pclass, (int)UROS_RPCP_STRING)); err = urosHostnameToIp(&paramp->value.string, &tcprosaddrp->ip); urosError(err != UROS_OK, goto _finally, ("Cannot resolve hostname [%.*s]", UROS_STRARG(&paramp->value.string))); /* Check the node port number.*/ paramp = &nodep->param; urosError(paramp->pclass != UROS_RPCP_INT, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_INT)\n", (int)paramp->pclass, (int)UROS_RPCP_INT)); urosError(paramp->value.int32 < 0 || paramp->value.int32 > 65535, _ERR, ("Port number %ld outside range\n", (long int)paramp->value.int32)); tcprosaddrp->port = (uint16_t)paramp->value.int32; err = UROS_OK; _finally: urosRpcResponseClean(&res); return err; #undef _ERR } /** * @brief Gets the TCPROS URI of a service publisher. * @details Requests the TCPROS URI of a service published by a node. * * @param[in] namep * Pointer to the topic name string. * @param[out] pubaddrp * Pointer to an allocated @p UrosAddr descriptor, which will hold the * TCPROS API address of the requested service provider. * @return * Error code. */ uros_err_t urosNodeResolveServicePublisher(const UrosString *namep, UrosAddr *pubaddrp) { static const UrosNodeConfig *const cfgp = &urosNode.config; uros_err_t err; UrosRpcResponse res; UrosString *uristrp; urosAssert(urosStringNotEmpty(namep)); urosAssert(pubaddrp != NULL); #define _ERR { err = UROS_ERR_BADPARAM; goto _finally; } /* Lookup the service URI.*/ urosRpcResponseObjectInit(&res); err = urosRpcCallLookupService( &cfgp->masterAddr, &cfgp->nodeName, namep, &res ); /* Check for valid values.*/ if (err != UROS_OK) { goto _finally; } urosError(res.httpcode != 200, _ERR, ("The HTTP response code is %lu, expected 200\n", (long unsigned int)res.httpcode)); urosError(res.code != UROS_RPCC_SUCCESS, _ERR, ("Cannot find a provider for service [%.*s]\n", UROS_STRARG(namep))); urosError(res.valuep->pclass != UROS_RPCP_STRING, _ERR, ("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n", (int)res.valuep->pclass, (int)UROS_RPCP_STRING)); uristrp = &res.valuep->value.string; res.valuep->value.string = urosStringAssignZ(NULL); urosRpcResponseClean(&res); urosAssert(urosStringIsValid(uristrp)); urosError(uristrp->length == 0, _ERR, ("Service URI string is empty\n")); /* Resolve the service address.*/ err = urosUriToAddr(uristrp, pubaddrp); _finally: urosRpcResponseClean(&res); return err; #undef _ERR } /** @} */
yukkysaito/uros_velodyne
src/urosNode.c
C
bsd-2-clause
70,678
import numpy as np from scipy.sparse import csr_matrix class AliasArray(np.ndarray): """An ndarray with a mapping of values to user-friendly names -- see example This ndarray subclass enables comparing sub_id and hop_id arrays directly with their friendly string identifiers. The mapping parameter translates sublattice or hopping names into their number IDs. Only the `==` and `!=` operators are overloaded to handle the aliases. Examples -------- >>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1}) >>> list(a == 0) [True, False, True] >>> list(a == "A") [True, False, True] >>> list(a != "A") [False, True, False] >>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2}) >>> list(a == "A") [True, False, True, True] >>> list(a != "A") [False, True, False, False] """ def __new__(cls, array, mapping): obj = np.asarray(array).view(cls) obj.mapping = {SplitName(k): v for k, v in mapping.items()} return obj def __array_finalize__(self, obj): if obj is None: return self.mapping = getattr(obj, "mapping", None) def _mapped_eq(self, other): if other in self.mapping: return super().__eq__(self.mapping[other]) else: result = np.zeros(len(self), dtype=np.bool) for k, v in self.mapping.items(): if k == other: result = np.logical_or(result, super().__eq__(v)) return result def __eq__(self, other): if isinstance(other, str): return self._mapped_eq(other) else: return super().__eq__(other) def __ne__(self, other): if isinstance(other, str): return np.logical_not(self._mapped_eq(other)) else: return super().__ne__(other) # noinspection PyAbstractClass class AliasCSRMatrix(csr_matrix): """Same as :class:`AliasArray` but for a CSR matrix Examples -------- >>> from scipy.sparse import spdiags >>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2}) >>> list(m.data == 'A') [True, False, True] >>> list(m.tocoo().data == 'A') [True, False, True] >>> list(m[:2].data == 'A') [True, False] """ def __init__(self, *args, **kwargs): mapping = kwargs.pop('mapping', {}) if not mapping: mapping = getattr(args[0], 'mapping', {}) super().__init__(*args, **kwargs) self.data = AliasArray(self.data, mapping) @property def format(self): return 'csr' @format.setter def format(self, _): pass @property def mapping(self): return self.data.mapping def tocoo(self, *args, **kwargs): coo = super().tocoo(*args, **kwargs) coo.data = AliasArray(coo.data, mapping=self.mapping) return coo def __getitem__(self, item): result = super().__getitem__(item) if getattr(result, 'format', '') == 'csr': return AliasCSRMatrix(result, mapping=self.mapping) else: return result class AliasIndex: """An all-or-nothing array index based on equality with a specific value The `==` and `!=` operators are overloaded to return a lazy array which is either all `True` or all `False`. See the examples below. This is useful for modifiers where the each call gets arrays with the same sub_id/hop_id for all elements. Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex` does the same all-or-nothing indexing. Examples -------- >>> l = np.array([1, 2, 3]) >>> ai = AliasIndex("A", len(l)) >>> list(l[ai == "A"]) [1, 2, 3] >>> list(l[ai == "B"]) [] >>> list(l[ai != "A"]) [] >>> list(l[ai != "B"]) [1, 2, 3] >>> np.logical_and([True, False, True], ai == "A") array([ True, False, True], dtype=bool) >>> np.logical_and([True, False, True], ai != "A") array([False, False, False], dtype=bool) >>> bool(ai == "A") True >>> bool(ai != "A") False >>> str(ai) 'A' >>> hash(ai) == hash("A") True >>> int(ai.eye) 1 >>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2)) True """ class LazyArray: def __init__(self, value, shape): self.value = value self.shape = shape def __bool__(self): return bool(self.value) def __array__(self): return np.full(self.shape, self.value) def __init__(self, name, shape, orbs=(1, 1)): self.name = name self.shape = shape self.orbs = orbs def __str__(self): return self.name def __eq__(self, other): return self.LazyArray(self.name == other, self.shape) def __ne__(self, other): return self.LazyArray(self.name != other, self.shape) def __hash__(self): return hash(self.name) @property def eye(self): return np.eye(*self.orbs) class SplitName(str): """String subclass with special support for strings of the form "first|second" Operators `==` and `!=` are overloaded to return `True` even if only the first part matches. Examples -------- >>> s = SplitName("first|second") >>> s == "first|second" True >>> s != "first|second" False >>> s == "first" True >>> s != "first" False >>> s == "second" False >>> s != "second" True """ @property def first(self): return self.split("|")[0] def __eq__(self, other): return super().__eq__(other) or self.first == other def __ne__(self, other): return super().__ne__(other) and self.first != other def __hash__(self): return super().__hash__()
MAndelkovic/pybinding
pybinding/support/alias.py
Python
bsd-2-clause
5,869
package org.mastodon.tracking.mamut.trackmate.wizard; import org.mastodon.mamut.model.Link; import org.mastodon.mamut.model.Model; import org.mastodon.mamut.model.Spot; import org.mastodon.model.AbstractModelImporter; public class CreateLargeModelExample { private static final int N_STARTING_CELLS = 6; private static final int N_DIVISIONS = 17; private static final int N_FRAMES_PER_DIVISION = 5; private static final double VELOCITY = 5; private static final double RADIUS = 3; private final Model model; public CreateLargeModelExample() { this.model = new Model(); } public Model run() { return run( N_STARTING_CELLS, N_DIVISIONS, N_FRAMES_PER_DIVISION ); } public Model run( final int nStartingCells, final int nDivisions, final int nFramesPerDivision ) { new AbstractModelImporter< Model >( model ){{ startImport(); }}; final Spot tmp = model.getGraph().vertexRef(); for ( int ic = 0; ic < nStartingCells; ic++ ) { final double angle = 2d * ic * Math.PI / N_STARTING_CELLS; final double vx = VELOCITY * Math.cos( angle ); final double vy = VELOCITY * Math.sin( angle ); // final int nframes = N_DIVISIONS * N_FRAMES_PER_DIVISION; final double x = 0.; // nframes * VELOCITY + vx; final double y = 0.; // nframes * VELOCITY + vy; final double z = N_DIVISIONS * VELOCITY; final double[] pos = new double[] { x, y, z }; final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } }; final Spot mother = model.getGraph().addVertex( tmp ).init( 0, pos, cov ); addBranch( mother, vx, vy, 1, nDivisions, nFramesPerDivision ); } model.getGraph().releaseRef( tmp ); new AbstractModelImporter< Model >( model ){{ finishImport(); }}; return model; } private void addBranch( final Spot start, final double vx, final double vy, final int iteration, final int nDivisions, final int nFramesPerDivision ) { if ( iteration >= nDivisions ) { return; } final Spot previousSpot = model.getGraph().vertexRef(); final Spot spot = model.getGraph().vertexRef(); final Spot daughter = model.getGraph().vertexRef(); final Link link = model.getGraph().edgeRef(); final double[] pos = new double[ 3 ]; final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } }; // Extend previousSpot.refTo( start ); for ( int it = 0; it < nFramesPerDivision; it++ ) { pos[ 0 ] = previousSpot.getDoublePosition( 0 ) + vx; pos[ 1 ] = previousSpot.getDoublePosition( 1 ) + vy; pos[ 2 ] = previousSpot.getDoublePosition( 2 ); final int frame = previousSpot.getTimepoint() + 1; model.getGraph().addVertex( spot ).init( frame, pos, cov ); model.getGraph().addEdge( previousSpot, spot, link ).init(); previousSpot.refTo( spot ); } // Divide for ( int id = 0; id < 2; id++ ) { final double sign = id == 0 ? 1 : -1; final double x; final double y; final double z; if ( iteration % 2 == 0 ) { x = previousSpot.getDoublePosition( 0 ); y = previousSpot.getDoublePosition( 1 ); z = previousSpot.getDoublePosition( 2 ) + sign * VELOCITY * ( 1 - 0.5d * iteration / nDivisions ) * 2; } else { x = previousSpot.getDoublePosition( 0 ) - sign * vy * ( 1 - 0.5d * iteration / nDivisions ) * 2; y = previousSpot.getDoublePosition( 1 ) + sign * vx * ( 1 - 0.5d * iteration / nDivisions ) * 2; z = previousSpot.getDoublePosition( 2 ); } final int frame = previousSpot.getTimepoint() + 1; pos[ 0 ] = x; pos[ 1 ] = y; pos[ 2 ] = z; model.getGraph().addVertex( daughter ).init( frame, pos, cov ); model.getGraph().addEdge( previousSpot, daughter, link ).init(); addBranch( daughter, vx, vy, iteration + 1, nDivisions, nFramesPerDivision ); } model.getGraph().releaseRef( previousSpot ); model.getGraph().releaseRef( spot ); model.getGraph().releaseRef( daughter ); model.getGraph().releaseRef( link ); } public static void main( final String[] args ) { final CreateLargeModelExample clme = new CreateLargeModelExample(); final long start = System.currentTimeMillis(); final Model model = clme.run(); final long end = System.currentTimeMillis(); System.out.println( "Model created in " + ( end - start ) + " ms." ); System.out.println( "Total number of spots: " + model.getGraph().vertices().size() ); System.out.println( String.format( "Total memory used by the model: %.1f MB", ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / 1e6d ) ); } }
TrNdy/mastodon-tracking
src/test/java/org/mastodon/tracking/mamut/trackmate/wizard/CreateLargeModelExample.java
Java
bsd-2-clause
4,524
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [email protected]. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/
gl-demos/masters
CODE_OF_CONDUCT.md
Markdown
bsd-2-clause
3,215
/* Copyright (c) 2016-2017, Artem Kashkanov 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.*/ #ifndef IMAGE_H_ #define IMAGE_H_ #include <cstdlib> #include <vector> #include <fstream> #include <iostream> #include "bfutils.h" #include "cmd.h" #include <string.h> class Section{ public: Section(std::vector<Cmd> &SectionCmd, uint16_t MemoryBase, uint16_t MemorySize); Section(std::vector<uint16_t> &SectionData, uint16_t MemoryBase, uint16_t MemorySize); Section(std::fstream &File); ~Section(); uint8_t GetType(){return Hdr.type;}; uint16_t GetFileBase(){return Hdr.FileBase;}; uint16_t GetMemoryBase(){return Hdr.MemoryBase;}; uint16_t GetFileSize(){return Hdr.FileSize;}; uint16_t GetMemorySize(){return Hdr.MemorySize;}; void WriteHeader(std::fstream &File); void WriteData(std::fstream &File); uint16_t *GetData(){return Data;}; bool Error(){return err;}; private: bool err; BfSection_t Hdr; uint16_t *Data; }; class Image{ public: Image(std::fstream &File, bool hex); Image(uint8_t _machine); ~Image(); void AddSection(Section &section); uint8_t GetSectionNum(void){return Hdr.SectionNum;}; Section &GetSection(uint8_t section){return Sections[section];}; void SetIpEntry(ADDRESS_TYPE Ptr){Hdr.IpEntry = Ptr;}; void SetApEntry(ADDRESS_TYPE Ptr){Hdr.ApEntry = Ptr;}; ADDRESS_TYPE GetIpEntry(){return Hdr.IpEntry;}; ADDRESS_TYPE GetApEntry(){return Hdr.ApEntry;}; bool ReadHex(std::fstream &File); void Write(std::fstream &File); bool Error(){return err;}; private: bool m_hex; bool err; BfHeader_t Hdr; std::vector<Section> Sections; }; #endif //IMAGE_H_
radiolok/bfutils
common/Image.h
C
bsd-2-clause
2,890
#{extends 'main.html' /} #{set title:'FAQ' /} #{set faq:'active'/} #{set title:'FAQ'/} <div class="page-header"> <h1>Frequently Asked Questions <a class="btn btn-primary login pull-right" href="@{Login.auth()}">Login with Dropbox</a> <a class="btn btn-primary login pull-right" href="@{Login.boxAuth()}">Login with Box</a> </h1> </div> <div class="well faq"> <h3>What is SortMyBox?</h3> <p>SortMyBox is a magic folder inside your cloud storage folder. Save new files there and we will move them based on rules you create. Like e-mail filters, for your Dropbox.</p> <h3>How does SortMyBox work?</h3> <p>We check the contents of your SortMyBox folder every 15 minutes. If there are any files that match any of your rules, we will move them to their correct location. We also log all file moves so you never lose a file.</p> <h3>Is SortMyBox for me?</h3> <p>Yes! Whether you're keeping your photos and videos organized or sharing documents with other people, SortMyBox will keep your files organized.</p> <h3>How do I begin?</h3> <p>Login using your <a href="@{Login.login()}">Dropbox</a> or <a href="@{Login.boxAuth()}">Box</a> account and we will create a SortMyBox folder and some sample rules for you. Save your files in this folder and you're good to go.</p> <h3>Why do I have to provide access for my Dropbox/Box account?</h3> <p>SortMyBox needs permission to move files around and put them in the appropriate folders. SortMyBox will never use your access for any other purposes.</p> <h3>What sorting options do I have?</h3> <p>We have 3 kinds of rules: </p> <dl class="dl-horizontal"> <dt>Name Contains:</dt> <dd>Move similarly named files to an appropriate folder.</dd> <dd>A rule with the pattern <code>venice 2011</code> matches files named <code>jen birthday venice 2011.jpg</code> or <code>gondola venice 2011.jpg</code>.</dd> <dt>Extension equals:</dt> <dd>Files with a matching extension will be moved to an appropriate folder.</dd> <dd>A rule with the extension <code>doc</code> matches files named <code>science report final.doc</code> or <code>resume.doc</code>, <strong>but not</strong> <code>doc brown with marty.jpg</code>.</dd> <dt>Name Pattern:</dt> <dd>Use wildcards like <code>?</code> and <code>*</code> to move files to an appropriate folder. <code>?</code> matches a single letter/number/symbol/character whereas <code>*</code> can match any number of them.</dd> <dd>The pattern <code>Prince*.mp3</code> matches <code>Prince - Purple rain.mp3</code> or <code>Prince.mp3</code>, <strong>but not</strong> <code>Prince.doc</code> or <code>Best of Prince.mp3</code>.</dd> <dd>The pattern <code>error?.txt</code> matches <code>error.txt</code> or <code>errors.txt</code>, <strong>but not</strong> <code>errorss.txt</code> or <code>new error.txt</code>.</dd> </dl> <h3>Is SortMyBox free?</h3> <p>Yes.</p> <h3>Open source?</h3> <p>SortMyBox is open source and BSD licensed, you can find it on <a href ="https://github.com/mustpax/sortmybox"> GitHub.</a></p> <p>You can even run it on your own Google AppEngine instance. Instructions forthcoming!</p> <h3>How do I contact you?</h3> <p>You can <a href = "mailto: ${play.configuration.getProperty("sortbox.email")}" >email us</a> or find us on <a href = "http://twitter.com/sortmybox">Twitter</a>.</p> <h3>Anything else?</h3> <p>Yes, please help us spread the word and share SortMyBox with other Dropbox & Box users! </p> </div>
mustpax/sortmybox
app/views/Footer/faq.html
HTML
bsd-2-clause
3,632
<?php /** * Class for XML output * * PHP versions 5 and 7 * * @category PEAR * @package PEAR_PackageFileManager * @author Greg Beaver <[email protected]> * @copyright 2003-2015 The PEAR Group * @license New BSD, Revised * @link http://pear.php.net/package/PEAR_PackageFileManager * @since File available since Release 1.2.0 */ /** * Class for XML output * * @category PEAR * @package PEAR_PackageFileManager * @author Greg Beaver <[email protected]> * @copyright 2003-2015 The PEAR Group * @license New BSD, Revised * @version Release: @PEAR-VER@ * @link http://pear.php.net/package/PEAR_PackageFileManager * @since Class available since Release 1.2.0 */ class PEAR_PackageFileManager_XMLOutput extends PEAR_Common { /** * Generate part of an XML description with release information. * * @param array $pkginfo array with release information * @param bool $changelog whether the result will be in a changelog element * * @return string XML data * @access private */ function _makeReleaseXml($pkginfo, $changelog = false) { $indent = $changelog ? " " : ""; $ret = "$indent <release>\n"; if (!empty($pkginfo['version'])) { $ret .= "$indent <version>$pkginfo[version]</version>\n"; } if (!empty($pkginfo['release_date'])) { $ret .= "$indent <date>$pkginfo[release_date]</date>\n"; } if (!empty($pkginfo['release_license'])) { $ret .= "$indent <license>$pkginfo[release_license]</license>\n"; } if (!empty($pkginfo['release_state'])) { $ret .= "$indent <state>$pkginfo[release_state]</state>\n"; } if (!empty($pkginfo['release_notes'])) { $ret .= "$indent <notes>".htmlspecialchars($pkginfo['release_notes'])."</notes>\n"; } if (!empty($pkginfo['release_warnings'])) { $ret .= "$indent <warnings>".htmlspecialchars($pkginfo['release_warnings'])."</warnings>\n"; } if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) { $ret .= "$indent <deps>\n"; foreach ($pkginfo['release_deps'] as $dep) { $ret .= "$indent <dep type=\"$dep[type]\" rel=\"$dep[rel]\""; if (isset($dep['version'])) { $ret .= " version=\"$dep[version]\""; } if (isset($dep['optional'])) { $ret .= " optional=\"$dep[optional]\""; } if (isset($dep['name'])) { $ret .= ">$dep[name]</dep>\n"; } else { $ret .= "/>\n"; } } $ret .= "$indent </deps>\n"; } if (isset($pkginfo['configure_options'])) { $ret .= "$indent <configureoptions>\n"; foreach ($pkginfo['configure_options'] as $c) { $ret .= "$indent <configureoption name=\"". htmlspecialchars($c['name']) . "\""; if (isset($c['default'])) { $ret .= " default=\"" . htmlspecialchars($c['default']) . "\""; } $ret .= " prompt=\"" . htmlspecialchars($c['prompt']) . "\""; $ret .= "/>\n"; } $ret .= "$indent </configureoptions>\n"; } if (isset($pkginfo['provides'])) { foreach ($pkginfo['provides'] as $key => $what) { $ret .= "$indent <provides type=\"$what[type]\" "; $ret .= "name=\"$what[name]\" "; if (isset($what['extends'])) { $ret .= "extends=\"$what[extends]\" "; } $ret .= "/>\n"; } } if (isset($pkginfo['filelist'])) { $ret .= "$indent <filelist>\n"; $ret .= $this->_doFileList($indent, $pkginfo['filelist'], '/'); $ret .= "$indent </filelist>\n"; } $ret .= "$indent </release>\n"; return $ret; } /** * Generate the <filelist> tag * * @param string $indent string to indent xml tag * @param array $filelist list of files included in release * @param string $curdir * * @access private * @return string XML data */ function _doFileList($indent, $filelist, $curdir) { $ret = ''; foreach ($filelist as $file => $fa) { if (isset($fa['##files'])) { $ret .= "$indent <dir"; } else { $ret .= "$indent <file"; } if (isset($fa['role'])) { $ret .= " role=\"$fa[role]\""; } if (isset($fa['baseinstalldir'])) { $ret .= ' baseinstalldir="' . htmlspecialchars($fa['baseinstalldir']) . '"'; } if (isset($fa['md5sum'])) { $ret .= " md5sum=\"$fa[md5sum]\""; } if (isset($fa['platform'])) { $ret .= " platform=\"$fa[platform]\""; } if (!empty($fa['install-as'])) { $ret .= ' install-as="' . htmlspecialchars($fa['install-as']) . '"'; } $ret .= ' name="' . htmlspecialchars($file) . '"'; if (isset($fa['##files'])) { $ret .= ">\n"; $recurdir = $curdir; if ($recurdir == '///') { $recurdir = ''; } $ret .= $this->_doFileList("$indent ", $fa['##files'], $recurdir . $file . '/'); $displaydir = $curdir; if ($displaydir == '///' || $displaydir == '/') { $displaydir = ''; } $ret .= "$indent </dir> <!-- $displaydir$file -->\n"; } else { if (empty($fa['replacements'])) { $ret .= "/>\n"; } else { $ret .= ">\n"; foreach ($fa['replacements'] as $r) { $ret .= "$indent <replace"; foreach ($r as $k => $v) { $ret .= " $k=\"" . htmlspecialchars($v) .'"'; } $ret .= "/>\n"; } $ret .= "$indent </file>\n"; } } } return $ret; } }
pear/PEAR_PackageFileManager
PEAR/PackageFileManager/XMLOutput.php
PHP
bsd-2-clause
6,592
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess // 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. /** \file spline.h * * \brief Contains definition and partial implementaiton of sirius::Spline class. */ #ifndef __SPLINE_H__ #define __SPLINE_H__ // TODO: add back() method like in std::vector // TODO: [?] store radial grid, not the pointer to the grid. namespace sirius { /// Cubic spline with a not-a-knot boundary conditions. /** The following convention for spline coefficients is used: between points * \f$ x_i \f$ and \f$ x_{i+1} \f$ the value of the spline is equal to * \f$ a_i + b_i(x_{i+1} - x_i) + c_i(x_{i+1}-x_i)^2 + d_i(x_{i+1}-x_i)^3 \f$. */ template <typename T, typename U = double> class Spline { private: /// Radial grid. Radial_grid<U> const* radial_grid_{nullptr}; mdarray<T, 2> coeffs_; /* forbid copy constructor */ Spline(Spline<T, U> const& src__) = delete; /* forbid assigment operator */ Spline<T, U>& operator=(Spline<T, U> const& src__) = delete; /// Solver tridiagonal system of linear equaitons. int solve(T* dl, T* d, T* du, T* b, int n) { for (int i = 0; i < n - 1; i++) { if (std::abs(dl[i]) == 0) { if (std::abs(d[i]) == 0) { return i + 1; } } else if (std::abs(d[i]) >= std::abs(dl[i])) { T mult = dl[i] / d[i]; d[i + 1] -= mult * du[i]; b[i + 1] -= mult * b[i]; if (i < n - 2) { dl[i] = 0; } } else { T mult = d[i] / dl[i]; d[i] = dl[i]; T tmp = d[i + 1]; d[i + 1] = du[i] - mult * tmp; if (i < n - 2) { dl[i] = du[i + 1]; du[i + 1] = -mult * dl[i]; } du[i] = tmp; tmp = b[i]; b[i] = b[i + 1]; b[i + 1] = tmp - mult * b[i + 1]; } } if (std::abs(d[n - 1]) == 0) { return n; } b[n - 1] /= d[n - 1]; if (n > 1) { b[n - 2] = (b[n - 2] - du[n - 2] * b[n - 1]) / d[n - 2]; } for (int i = n - 3; i >= 0; i--) { b[i] = (b[i] - du[i] * b[i + 1] - dl[i] * b[i + 2]) / d[i]; } return 0; } public: /// Default constructor. Spline() { } /// Constructor of a new empty spline. Spline(Radial_grid<U> const& radial_grid__) : radial_grid_(&radial_grid__) { coeffs_ = mdarray<T, 2>(num_points(), 4); coeffs_.zero(); } /// Constructor of a spline from a function. Spline(Radial_grid<U> const& radial_grid__, std::function<T(U)> f__) : radial_grid_(&radial_grid__) { coeffs_ = mdarray<T, 2>(num_points(), 4); for (int i = 0; i < num_points(); i++) { U x = (*radial_grid_)[i]; coeffs_(i, 0) = f__(x); } interpolate(); } /// Constructor of a spline from a list of values. Spline(Radial_grid<U> const& radial_grid__, std::vector<T> const& y__) : radial_grid_(&radial_grid__) { assert(radial_grid_->num_points() == (int)y__.size()); coeffs_ = mdarray<T, 2>(num_points(), 4); for (int i = 0; i < num_points(); i++) { coeffs_(i, 0) = y__[i]; } interpolate(); } /// Move constructor. Spline(Spline<T, U>&& src__) { radial_grid_ = src__.radial_grid_; coeffs_ = std::move(src__.coeffs_); } /// Move assigment operator. Spline<T, U>& operator=(Spline<T, U>&& src__) { if (this != &src__) { radial_grid_ = src__.radial_grid_; coeffs_ = std::move(src__.coeffs_); } return *this; } Spline<T, U>& operator=(std::function<T(U)> f__) { for (int ir = 0; ir < radial_grid_->num_points(); ir++) { U x = (*radial_grid_)[ir]; coeffs_(ir, 0) = f__(x); } return this->interpolate(); } /// Integrate with r^m weight. T integrate(int m__) const { std::vector<T> g(num_points()); return integrate(g, m__); } inline std::vector<T> values() const { std::vector<T> a(num_points()); for (int i = 0; i < num_points(); i++) { a[i] = coeffs_(i, 0); } return std::move(a); } /// Return number of spline points. inline int num_points() const { return radial_grid_->num_points(); } inline std::array<T, 4> coeffs(int i__) const { return {coeffs_(i__, 0), coeffs_(i__, 1), coeffs_(i__, 2), coeffs_(i__, 3)}; } inline mdarray<T, 2> const& coeffs() const { return coeffs_; } inline double x(int i__) const { return (*radial_grid_)[i__]; } inline double dx(int i__) const { return radial_grid_->dx(i__); } inline T operator()(U x) const { int j = radial_grid_->index_of(x); if (j == -1) { TERMINATE("point not found"); } U dx = x - (*radial_grid_)[j]; return (*this)(j, dx); } /// Return value at \f$ x_i \f$. inline T& operator[](const int i) { return coeffs_(i, 0); } inline T operator[](const int i) const { return coeffs_(i, 0); } inline T operator()(const int i, U dx) const { assert(i >= 0); assert(i < num_points() - 1); assert(dx >= 0); return coeffs_(i, 0) + dx * (coeffs_(i, 1) + dx * (coeffs_(i, 2) + dx * coeffs_(i, 3))); } inline T deriv(const int dm, const int i, const U dx) const { assert(i >= 0); assert(i < num_points() - 1); assert(dx >= 0); T result = 0; switch (dm) { case 0: { result = coeffs_(i, 0) + dx * (coeffs_(i, 1) + dx * (coeffs_(i, 2) + dx * coeffs_(i, 3))); break; } case 1: { result = coeffs_(i, 1) + (coeffs_(i, 2) * 2.0 + coeffs_(i, 3) * dx * 3.0) * dx; break; } case 2: { result = coeffs_(i, 2) * 2.0 + coeffs_(i, 3) * dx * 6.0; break; } case 3: { result = coeffs_(i, 3) * 6.0; break; } default: { TERMINATE("wrong order of derivative"); break; } } return result; } inline T deriv(int dm, int i) const { assert(i >= 0); assert(i < num_points()); assert(radial_grid_ != nullptr); if (i == num_points() - 1) { return deriv(dm, i - 1, radial_grid_->dx(i - 1)); } else { return deriv(dm, i, 0); } } inline Radial_grid<U> const& radial_grid() const { return *radial_grid_; } Spline<T, U>& interpolate() { int np = num_points(); /* lower diagonal */ std::vector<T> dl(np - 1); /* main diagonal */ std::vector<T> d(np); /* upper diagonal */ std::vector<T> du(np - 1); std::vector<T> x(np); std::vector<T> dy(np - 1); /* derivative of y */ for (int i = 0; i < np - 1; i++) { dy[i] = (coeffs_(i + 1, 0) - coeffs_(i, 0)) / radial_grid_->dx(i); } /* setup "B" vector of AX=B equation */ for (int i = 0; i < np - 2; i++) { x[i + 1] = (dy[i + 1] - dy[i]) * 6.0; } x[0] = -x[1]; x[np - 1] = -x[np - 2]; /* main diagonal of "A" matrix */ for (int i = 0; i < np - 2; i++) { d[i + 1] = static_cast<T>(2) * (static_cast<T>(radial_grid_->dx(i)) + static_cast<T>(radial_grid_->dx(i + 1))); } U h0 = radial_grid_->dx(0); U h1 = radial_grid_->dx(1); U h2 = radial_grid_->dx(np - 2); U h3 = radial_grid_->dx(np - 3); d[0] = (h1 / h0) * h1 - h0; d[np - 1] = (h3 / h2) * h3 - h2; /* subdiagonals of "A" matrix */ for (int i = 0; i < np - 1; i++) { du[i] = static_cast<T>(radial_grid_->dx(i)); dl[i] = static_cast<T>(radial_grid_->dx(i)); } du[0] = -(h1 * (1.0 + h1 / h0) + d[1]); dl[np - 2] = -(h3 * (1.0 + h3 / h2) + d[np - 2]); /* solve tridiagonal system */ //solve(a.data(), b.data(), c.data(), d.data(), np); //auto& x = d; //int info = linalg<CPU>::gtsv(np, 1, &a[0], &b[0], &c[0], &d[0], np); int info = solve(&dl[0], &d[0], &du[0], &x[0], np); if (info) { std::stringstream s; s << "error in tridiagonal solver: " << info; TERMINATE(s); } for (int i = 0; i < np - 1; i++) { coeffs_(i, 2) = x[i] / 2.0; T t = (x[i + 1] - x[i]) / 6.0; coeffs_(i, 1) = dy[i] - (coeffs_(i, 2) + t) * radial_grid_->dx(i); coeffs_(i, 3) = t / radial_grid_->dx(i); } coeffs_(np - 1, 1) = 0; coeffs_(np - 1, 2) = 0; coeffs_(np - 1, 3) = 0; return *this; } inline void scale(double a__) { for (int i = 0; i < num_points(); i++) { coeffs_(i, 0) *= a__; coeffs_(i, 1) *= a__; coeffs_(i, 2) *= a__; coeffs_(i, 3) *= a__; } } T integrate_simpson() const { std::vector<U> w(num_points(), 0); for (int i = 0; i < num_points() - 2; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; U x2 = (*radial_grid_)[i + 2]; w[i] += (2 * x0 + x1 - 3 * x2) * (x1 - x0) / (x0 - x2) / 6; w[i + 1] += (x0 - x1) * (x0 + 2 * x1 - 3 * x2) / 6 / (x2 - x1); w[i + 2] += std::pow(x0 - x1, 3) / 6 / (x2 - x0) / (x2 - x1); } //for (int i = 1; i < num_points() - 1; i++) { // w[i] *= 0.5; //} T res{0}; for (int i = 0; i < num_points(); i++) { res += w[i] * coeffs_(i, 0); } return res; } T integrate_simple() const { T res{0}; for (int i = 0; i < num_points() - 1; i++) { U dx = radial_grid_->dx(i); res += 0.5 * (coeffs_(i, 0) + coeffs_(i + 1, 0)) * dx; } return res; } T integrate(std::vector<T>& g__, int m__) const { g__ = std::vector<T>(num_points()); g__[0] = 0.0; switch (m__) { case 0: { T t = 1.0 / 3.0; for (int i = 0; i < num_points() - 1; i++) { U dx = radial_grid_->dx(i); g__[i + 1] = g__[i] + (((coeffs_(i, 3) * dx * 0.25 + coeffs_(i, 2) * t) * dx + coeffs_(i, 1) * 0.5) * dx + coeffs_(i, 0)) * dx; } break; } case 2: { for (int i = 0; i < num_points() - 1; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; U dx = radial_grid_->dx(i); T a0 = coeffs_(i, 0); T a1 = coeffs_(i, 1); T a2 = coeffs_(i, 2); T a3 = coeffs_(i, 3); U x0_2 = x0 * x0; U x0_3 = x0_2 * x0; U x1_2 = x1 * x1; U x1_3 = x1_2 * x1; g__[i + 1] = g__[i] + (20.0 * a0 * (x1_3 - x0_3) + 5.0 * a1 * (x0 * x0_3 + x1_3 * (3.0 * dx - x0)) - dx * dx * dx * (-2.0 * a2 * (x0_2 + 3.0 * x0 * x1 + 6.0 * x1_2) - a3 * dx * (x0_2 + 4.0 * x0 * x1 + 10.0 * x1_2))) / 60.0; } break; } case -1: { for (int i = 0; i < num_points() - 1; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; U dx = radial_grid_->dx(i); T a0 = coeffs_(i, 0); T a1 = coeffs_(i, 1); T a2 = coeffs_(i, 2); T a3 = coeffs_(i, 3); // obtained with the following Mathematica code: // FullSimplify[Integrate[x^(-1)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}], // Assumptions->{Element[{x0,x1},Reals],x1>x0>0}] g__[i + 1] = g__[i] + (dx / 6.0) * (6.0 * a1 + x0 * (-9.0 * a2 + 11.0 * a3 * x0) + x1 * (3.0 * a2 - 7.0 * a3 * x0 + 2.0 * a3 * x1)) + (-a0 + x0 * (a1 + x0 * (-a2 + a3 * x0))) * std::log(x0 / x1); } break; } case -2: { for (int i = 0; i < num_points() - 1; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; U dx = radial_grid_->dx(i); T a0 = coeffs_(i, 0); T a1 = coeffs_(i, 1); T a2 = coeffs_(i, 2); T a3 = coeffs_(i, 3); // obtained with the following Mathematica code: // FullSimplify[Integrate[x^(-2)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}], // Assumptions->{Element[{x0,x1},Reals],x1>x0>0}] //g__[i + 1] = g__[i] + (((x0 - x1) * (-2.0 * a0 + x0 * (2.0 * a1 - 2.0 * a2 * (x0 + x1) + // a3 * (2.0 * std::pow(x0, 2) + 5.0 * x0 * x1 - std::pow(x1, 2)))) + // 2.0 * x0 * (a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * x1 * std::log(x1 / x0)) / // (2.0 * x0 * x1)); g__[i + 1] = g__[i] + (a2 * dx - 5.0 * a3 * x0 * dx / 2.0 - a1 * (dx / x1) + a0 * (dx / x0 / x1) + (x0 / x1) * dx * (a2 - a3 * x0) + a3 * x1 * dx / 2.0) + (a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * std::log(x1 / x0); } break; } case -3: { for (int i = 0; i < num_points() - 1; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; U dx = radial_grid_->dx(i); T a0 = coeffs_(i, 0); T a1 = coeffs_(i, 1); T a2 = coeffs_(i, 2); T a3 = coeffs_(i, 3); // obtained with the following Mathematica code: // FullSimplify[Integrate[x^(-3)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}], // Assumptions->{Element[{x0,x1},Reals],x1>x0>0}] //g__[i + 1] = g__[i] + (-((x0 - x1) * (a0 * (x0 + x1) + x0 * (a1 * (-x0 + x1) + // x0 * (a2 * x0 - a3 * std::pow(x0, 2) - 3.0 * a2 * x1 + 5.0 * a3 * x0 * x1 + // 2.0 * a3 * std::pow(x1, 2)))) + 2.0 * std::pow(x0, 2) * (a2 - 3.0 * a3 * x0) * std::pow(x1, 2) * // std::log(x0 / x1)) / (2.0 * std::pow(x0, 2) * std::pow(x1, 2))); g__[i + 1] = g__[i] + dx * (a0 * (x0 + x1) + x0 * (a1 * dx + x0 * (a2 * x0 - a3 * std::pow(x0, 2) - 3.0 * a2 * x1 + 5.0 * a3 * x0 * x1 + 2.0 * a3 * std::pow(x1, 2)))) / std::pow(x0 * x1, 2) / 2.0 + (-a2 + 3.0 * a3 * x0) * std::log(x0 / x1); } break; } case -4: { for (int i = 0; i < num_points() - 1; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; U dx = radial_grid_->dx(i); T a0 = coeffs_(i, 0); T a1 = coeffs_(i, 1); T a2 = coeffs_(i, 2); T a3 = coeffs_(i, 3); // obtained with the following Mathematica code: // FullSimplify[Integrate[x^(-4)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}], // Assumptions->{Element[{x0,x1},Reals],x1>x0>0}] //g__[i + 1] = g__[i] + ((2.0 * a0 * (-std::pow(x0, 3) + std::pow(x1, 3)) + // x0 * (x0 - x1) * (a1 * (x0 - x1) * (2.0 * x0 + x1) + // x0 * (-2.0 * a2 * std::pow(x0 - x1, 2) + a3 * x0 * (2.0 * std::pow(x0, 2) - 7.0 * x0 * x1 + // 11.0 * std::pow(x1, 2)))) + 6.0 * a3 * std::pow(x0 * x1, 3) * std::log(x1 / x0)) / // (6.0 * std::pow(x0 * x1, 3))); g__[i + 1] = g__[i] + (2.0 * a0 * (-std::pow(x0, 3) + std::pow(x1, 3)) - x0 * dx * (-a1 * dx * (2.0 * x0 + x1) + x0 * (-2.0 * a2 * std::pow(dx, 2) + a3 * x0 * (2.0 * std::pow(x0, 2) - 7.0 * x0 * x1 + 11.0 * std::pow(x1, 2))))) / std::pow(x0 * x1, 3) / 6.0 + a3 * std::log(x1 / x0); } break; } default: { for (int i = 0; i < num_points() - 1; i++) { U x0 = (*radial_grid_)[i]; U x1 = (*radial_grid_)[i + 1]; T a0 = coeffs_(i, 0); T a1 = coeffs_(i, 1); T a2 = coeffs_(i, 2); T a3 = coeffs_(i, 3); // obtained with the following Mathematica code: // FullSimplify[Integrate[x^(m)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}], // Assumptions->{Element[{x0,x1},Reals],x1>x0>0}] g__[i + 1] = g__[i] + (std::pow(x0, 1 + m__) * (-(a0 * double((2 + m__) * (3 + m__) * (4 + m__))) + x0 * (a1 * double((3 + m__) * (4 + m__)) - 2.0 * a2 * double(4 + m__) * x0 + 6.0 * a3 * std::pow(x0, 2)))) / double((1 + m__) * (2 + m__) * (3 + m__) * (4 + m__)) + std::pow(x1, 1 + m__) * ((a0 - x0 * (a1 + x0 * (-a2 + a3 * x0))) / double(1 + m__) + ((a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * x1) / double(2 + m__) + ((a2 - 3.0 * a3 * x0) * std::pow(x1, 2)) / double(3 + m__) + (a3 * std::pow(x1, 3)) / double(4 + m__)); } break; } } return g__[num_points() - 1]; } uint64_t hash() const { return coeffs_.hash(); } #ifdef __GPU void copy_to_device() { coeffs_.allocate_on_device(); coeffs_.copy_to_device(); } void async_copy_to_device(int thread_id__) { coeffs_.allocate_on_device(); coeffs_.async_copy_to_device(thread_id__); } #endif }; template <typename T> inline Spline<T> operator*(Spline<T> const& a__, Spline<T> const& b__) { //assert(a__.radial_grid().hash() == b__.radial_grid().hash()); Spline<double> s12(a__.radial_grid()); auto& coeffs_a = a__.coeffs(); auto& coeffs_b = b__.coeffs(); auto& coeffs = const_cast<mdarray<double, 2>&>(s12.coeffs()); for (int ir = 0; ir < a__.radial_grid().num_points(); ir++) { coeffs(ir, 0) = coeffs_a(ir, 0) * coeffs_b(ir, 0); coeffs(ir, 1) = coeffs_a(ir, 1) * coeffs_b(ir, 0) + coeffs_a(ir, 0) * coeffs_b(ir, 1); coeffs(ir, 2) = coeffs_a(ir, 2) * coeffs_b(ir, 0) + coeffs_a(ir, 1) * coeffs_b(ir, 1) + coeffs_a(ir, 0) * coeffs_b(ir, 2); coeffs(ir, 3) = coeffs_a(ir, 3) * coeffs_b(ir, 0) + coeffs_a(ir, 2) * coeffs_b(ir, 1) + coeffs_a(ir, 1) * coeffs_b(ir, 2) + coeffs_a(ir, 0) * coeffs_b(ir, 3); } return std::move(s12); } #ifdef __GPU extern "C" double spline_inner_product_gpu_v2(int size__, double const* x__, double const* dx__, double const* f__, double const* g__, double* d_buf__, double* h_buf__, int stream_id__); extern "C" void spline_inner_product_gpu_v3(int const* idx_ri__, int num_ri__, int num_points__, double const* x__, double const* dx__, double const* f__, double const* g__, double* result__); #endif template<typename T> T inner(Spline<T> const& f__, Spline<T> const& g__, int m__, int num_points__) { //assert(f__.radial_grid().hash() == g__.radial_grid().hash()); T result = 0; switch (m__) { case 0: { for (int i = 0; i < num_points__ - 1; i++) { double dx = f__.dx(i); auto f = f__.coeffs(i); auto g = g__.coeffs(i); T faga = f[0] * g[0]; T fdgd = f[3] * g[3]; T k1 = f[0] * g[1] + f[1] * g[0]; T k2 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2]; T k3 = f[0] * g[3] + f[1] * g[2] + f[2] * g[1] + f[3] * g[0]; T k4 = f[1] * g[3] + f[2] * g[2] + f[3] * g[1]; T k5 = f[2] * g[3] + f[3] * g[2]; result += dx * (faga + dx * (k1 / 2.0 + dx * (k2 / 3.0 + dx * (k3 / 4.0 + dx * (k4 / 5.0 + dx * (k5 / 6.0 + dx * fdgd / 7.0)))))); } break; } case 1: { for (int i = 0; i < num_points__ - 1; i++) { double x0 = f__.x(i); double dx = f__.dx(i); auto f = f__.coeffs(i); auto g = g__.coeffs(i); T faga = f[0] * g[0]; T fdgd = f[3] * g[3]; T k1 = f[0] * g[1] + f[1] * g[0]; T k2 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2]; T k3 = f[0] * g[3] + f[1] * g[2] + f[2] * g[1] + f[3] * g[0]; T k4 = f[1] * g[3] + f[2] * g[2] + f[3] * g[1]; T k5 = f[2] * g[3] + f[3] * g[2]; result += dx * ((faga * x0) + dx * ((faga + k1 * x0) / 2.0 + dx * ((k1 + k2 * x0) / 3.0 + dx * ((k2 + k3 * x0) / 4.0 + dx * ((k3 + k4 * x0) / 5.0 + dx * ((k4 + k5 * x0) / 6.0 + dx * ((k5 + fdgd * x0) / 7.0 + dx * fdgd / 8.0))))))); } break; } case 2: { for (int i = 0; i < num_points__ - 1; i++) { double x0 = f__.x(i); double dx = f__.dx(i); auto f = f__.coeffs(i); auto g = g__.coeffs(i); T k0 = f[0] * g[0]; T k1 = f[3] * g[1] + f[2] * g[2] + f[1] * g[3]; T k2 = f[3] * g[0] + f[2] * g[1] + f[1] * g[2] + f[0] * g[3]; T k3 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2]; T k4 = f[3] * g[2] + f[2] * g[3]; T k5 = f[1] * g[0] + f[0] * g[1]; T k6 = f[3] * g[3]; // 25 OPS T r1 = k4 * 0.125 + k6 * x0 * 0.25; T r2 = (k1 + x0 * (2.0 * k4 + k6 * x0)) * 0.14285714285714285714; T r3 = (k2 + x0 * (2.0 * k1 + k4 * x0)) * 0.16666666666666666667; T r4 = (k3 + x0 * (2.0 * k2 + k1 * x0)) * 0.2; T r5 = (k5 + x0 * (2.0 * k3 + k2 * x0)) * 0.25; T r6 = (k0 + x0 * (2.0 * k5 + k3 * x0)) * 0.33333333333333333333; T r7 = (x0 * (2.0 * k0 + x0 * k5)) * 0.5; T v = dx * k6 * 0.11111111111111111111; v = dx * (r1 + v); v = dx * (r2 + v); v = dx * (r3 + v); v = dx * (r4 + v); v = dx * (r5 + v); v = dx * (r6 + v); v = dx * (r7 + v); result += dx * (k0 * x0 * x0 + v); } break; } /* canonical formula derived with Mathematica */ /*case 2: { for (int i = 0; i < num_points__ - 1; i++) { double x0 = f__.x(i); double dx = f__.dx(i); auto f = f__.coefs(i); auto g = g__.coefs(i); T k0 = f[0] * g[0]; T k1 = f[3] * g[1] + f[2] * g[2] + f[1] * g[3]; T k2 = f[3] * g[0] + f[2] * g[1] + f[1] * g[2] + f[0] * g[3]; T k3 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2]; T k4 = f[3] * g[2] + f[2] * g[3]; T k5 = f[1] * g[0] + f[0] * g[1]; T k6 = f[3] * g[3]; // 25 OPS result += dx * (k0 * x0 * x0 + dx * ((x0 * (2.0 * k0 + x0 * k5)) / 2.0 + dx * ((k0 + x0 * (2.0 * k5 + k3 * x0)) / 3.0 + dx * ((k5 + x0 * (2.0 * k3 + k2 * x0)) / 4.0 + dx * ((k3 + x0 * (2.0 * k2 + k1 * x0)) / 5.0 + dx * ((k2 + x0 * (2.0 * k1 + k4 * x0)) / 6.0 + dx * ((k1 + x0 * (2.0 * k4 + k6 * x0)) / 7.0 + dx * ((k4 + 2.0 * k6 * x0) / 8.0 + dx * k6 / 9.0)))))))); } break; }*/ default: { TERMINATE("wrong r^m prefactor"); } } return result; } template<typename T> T inner(Spline<T> const& f__, Spline<T> const& g__, int m__) { return inner(f__, g__, m__, f__.num_points()); } }; #endif // __SPLINE_H__
dithillobothrium/SIRIUS
src/spline.h
C
bsd-2-clause
30,186
// Set color based on frequency and brightness void setColor(int peak_index, int brightness) { if (peak_index == 0) { // signal was weak, turn lights off red = 0; green = 0; blue = 0; } else if (peak_index > 30) { red = current_palette[29].red; green = current_palette[29].green; blue = current_palette[29].blue; } else { red = current_palette[peak_index - 1].red; green = current_palette[peak_index - 1].green; blue = current_palette[peak_index - 1].blue; } strip_color = strip.Color( round((red / 100.0) * brightness), round((green / 100.0) * brightness), round((blue / 100.0) * brightness) ); if (DEBUG) { Serial.print((red / 100.0) * brightness); Serial.print("\t"); Serial.print((green / 100.0) * brightness); Serial.print("\t"); Serial.println((blue / 100.0) * brightness); } for (int i=0; i < strip.numPixels(); i++) { strip.setPixelColor(i, strip_color); } strip.show(); } void changeColorPalette() { // re-populate colors for color_palette from new palette choice if (palette_choice != new_palette_choice - 1) { palette_choice = new_palette_choice - 1; for (int i = 0; i < 30; i++) { current_palette[i].red = pgm_read_byte( &(palettes[i + (palette_color_count * palette_choice)].red) ); current_palette[i].green = pgm_read_byte( &(palettes[i + (palette_color_count * palette_choice)].green) ); current_palette[i].blue = pgm_read_byte( &(palettes[i + (palette_color_count * palette_choice)].blue) ); } } }
whitews/super-freq
super_freq/light_strip_controllers.h
C
bsd-2-clause
1,795
/******* * * FILE INFO: * project: RTP_lib * file: Types.h * started on: 03/26/03 * started by: Cedric Lacroix <[email protected]> * * * TODO: * * BUGS: * * UPDATE INFO: * updated on: 05/13/03 * updated by: Cedric Lacroix <[email protected]> * *******/ #ifndef TYPES_H #define TYPES_H #ifndef FALSE #define FALSE 0 #endif #ifndef TRUE #define TRUE 1 #endif typedef unsigned char u_int8; typedef unsigned short u_int16; typedef unsigned long u_int32; typedef unsigned int context; /** ** Declaration for unix **/ #ifdef UNIX #ifndef _WIN32 typedef int SOCKET; #endif typedef struct sockaddr SOCKADDR; typedef struct sockaddr_in SOCKADDR_IN; #endif /* UNIX */ #endif /* TYPES_H */
Devronium/ConceptApplicationServer
modules/standard.net.rtp.lite/src/Types.h
C
bsd-2-clause
762
/** * PatentPriority_type0.java * * This file was auto-generated from WSDL * by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST) */ package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene; /** * PatentPriority_type0 bean class */ @SuppressWarnings({"unchecked","unused"}) public class PatentPriority_type0 implements org.apache.axis2.databinding.ADBBean{ /* This type was generated from the piece of schema that had name = Patent-priority_type0 Namespace URI = http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene Namespace Prefix = ns1 */ /** * field for PatentPriority_country */ protected java.lang.String localPatentPriority_country ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getPatentPriority_country(){ return localPatentPriority_country; } /** * Auto generated setter method * @param param PatentPriority_country */ public void setPatentPriority_country(java.lang.String param){ this.localPatentPriority_country=param; } /** * field for PatentPriority_number */ protected java.lang.String localPatentPriority_number ; /** * Auto generated getter method * @return java.lang.String */ public java.lang.String getPatentPriority_number(){ return localPatentPriority_number; } /** * Auto generated setter method * @param param PatentPriority_number */ public void setPatentPriority_number(java.lang.String param){ this.localPatentPriority_number=param; } /** * field for PatentPriority_date */ protected gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 localPatentPriority_date ; /** * Auto generated getter method * @return gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 */ public gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 getPatentPriority_date(){ return localPatentPriority_date; } /** * Auto generated setter method * @param param PatentPriority_date */ public void setPatentPriority_date(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 param){ this.localPatentPriority_date=param; } /** * * @param parentQName * @param factory * @return org.apache.axiom.om.OMElement */ public org.apache.axiom.om.OMElement getOMElement ( final javax.xml.namespace.QName parentQName, final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{ org.apache.axiom.om.OMDataSource dataSource = new org.apache.axis2.databinding.ADBDataSource(this,parentQName); return factory.createOMElement(dataSource,parentQName); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ serialize(parentQName,xmlWriter,false); } public void serialize(final javax.xml.namespace.QName parentQName, javax.xml.stream.XMLStreamWriter xmlWriter, boolean serializeType) throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{ java.lang.String prefix = null; java.lang.String namespace = null; prefix = parentQName.getPrefix(); namespace = parentQName.getNamespaceURI(); writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter); if (serializeType){ java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){ writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", namespacePrefix+":Patent-priority_type0", xmlWriter); } else { writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type", "Patent-priority_type0", xmlWriter); } } namespace = "http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"; writeStartElement(null, namespace, "Patent-priority_country", xmlWriter); if (localPatentPriority_country==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("Patent-priority_country cannot be null!!"); }else{ xmlWriter.writeCharacters(localPatentPriority_country); } xmlWriter.writeEndElement(); namespace = "http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene"; writeStartElement(null, namespace, "Patent-priority_number", xmlWriter); if (localPatentPriority_number==null){ // write the nil attribute throw new org.apache.axis2.databinding.ADBException("Patent-priority_number cannot be null!!"); }else{ xmlWriter.writeCharacters(localPatentPriority_number); } xmlWriter.writeEndElement(); if (localPatentPriority_date==null){ throw new org.apache.axis2.databinding.ADBException("Patent-priority_date cannot be null!!"); } localPatentPriority_date.serialize(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_date"), xmlWriter); xmlWriter.writeEndElement(); } private static java.lang.String generatePrefix(java.lang.String namespace) { if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){ return "ns1"; } return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } /** * Utility method to write an element start tag. */ private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, localPart); } else { if (namespace.length() == 0) { prefix = ""; } else if (prefix == null) { prefix = generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, localPart, namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } /** * Util method to write an attribute with the ns prefix */ private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace,attName,attValue); } /** * Util method to write an attribute without the ns prefix */ private void writeAttribute(java.lang.String namespace,java.lang.String attName, java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{ if (namespace.equals("")) { xmlWriter.writeAttribute(attName,attValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace,attName,attValue); } } /** * Util method to write an attribute without the ns prefix */ private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName, javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String attributeNamespace = qname.getNamespaceURI(); java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace); if (attributePrefix == null) { attributePrefix = registerPrefix(xmlWriter, attributeNamespace); } java.lang.String attributeValue; if (attributePrefix.trim().length() > 0) { attributeValue = attributePrefix + ":" + qname.getLocalPart(); } else { attributeValue = qname.getLocalPart(); } if (namespace.equals("")) { xmlWriter.writeAttribute(attName, attributeValue); } else { registerPrefix(xmlWriter, namespace); xmlWriter.writeAttribute(namespace, attName, attributeValue); } } /** * method to handle Qnames */ private void writeQName(javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { java.lang.String namespaceURI = qname.getNamespaceURI(); if (namespaceURI != null) { java.lang.String prefix = xmlWriter.getPrefix(namespaceURI); if (prefix == null) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } else { // i.e this is the default namespace xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } else { xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname)); } } private void writeQNames(javax.xml.namespace.QName[] qnames, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException { if (qnames != null) { // we have to store this data until last moment since it is not possible to write any // namespace data after writing the charactor data java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer(); java.lang.String namespaceURI = null; java.lang.String prefix = null; for (int i = 0; i < qnames.length; i++) { if (i > 0) { stringToWrite.append(" "); } namespaceURI = qnames[i].getNamespaceURI(); if (namespaceURI != null) { prefix = xmlWriter.getPrefix(namespaceURI); if ((prefix == null) || (prefix.length() == 0)) { prefix = generatePrefix(namespaceURI); xmlWriter.writeNamespace(prefix, namespaceURI); xmlWriter.setPrefix(prefix,namespaceURI); } if (prefix.trim().length() > 0){ stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } else { stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i])); } } xmlWriter.writeCharacters(stringToWrite.toString()); } } /** * Register a namespace prefix */ private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException { java.lang.String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = generatePrefix(namespace); javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext(); while (true) { java.lang.String uri = nsContext.getNamespaceURI(prefix); if (uri == null || uri.length() == 0) { break; } prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } /** * databinding method to get an XML representation of this object * */ public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName) throws org.apache.axis2.databinding.ADBException{ java.util.ArrayList elementList = new java.util.ArrayList(); java.util.ArrayList attribList = new java.util.ArrayList(); elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "Patent-priority_country")); if (localPatentPriority_country != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localPatentPriority_country)); } else { throw new org.apache.axis2.databinding.ADBException("Patent-priority_country cannot be null!!"); } elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "Patent-priority_number")); if (localPatentPriority_number != null){ elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localPatentPriority_number)); } else { throw new org.apache.axis2.databinding.ADBException("Patent-priority_number cannot be null!!"); } elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene", "Patent-priority_date")); if (localPatentPriority_date==null){ throw new org.apache.axis2.databinding.ADBException("Patent-priority_date cannot be null!!"); } elementList.add(localPatentPriority_date); return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray()); } /** * Factory class that keeps the parse method */ public static class Factory{ /** * static method to create the object * Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable * If this object is not an element, it is a complex type and the reader is at the event just after the outer start element * Postcondition: If this object is an element, the reader is positioned at its end element * If this object is a complex type, the reader is positioned at the end element of its outer element */ public static PatentPriority_type0 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{ PatentPriority_type0 object = new PatentPriority_type0(); int event; java.lang.String nillableValue = null; java.lang.String prefix =""; java.lang.String namespaceuri =""; try { while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){ java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName!=null){ java.lang.String nsPrefix = null; if (fullTypeName.indexOf(":") > -1){ nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":")); } nsPrefix = nsPrefix==null?"":nsPrefix; java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1); if (!"Patent-priority_type0".equals(type)){ //find namespace for the prefix java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (PatentPriority_type0)gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.ExtensionMapper.getTypeObject( nsUri,type,reader); } } } // Note all attributes that were handled. Used to differ normal attributes // from anyAttributes. java.util.Vector handledAttributes = new java.util.Vector(); reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_country").equals(reader.getName())){ nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)){ throw new org.apache.axis2.databinding.ADBException("The element: "+"Patent-priority_country" +" cannot be null"); } java.lang.String content = reader.getElementText(); object.setPatentPriority_country( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_number").equals(reader.getName())){ nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil"); if ("true".equals(nillableValue) || "1".equals(nillableValue)){ throw new org.apache.axis2.databinding.ADBException("The element: "+"Patent-priority_number" +" cannot be null"); } java.lang.String content = reader.getElementText(); object.setPatentPriority_number( org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_date").equals(reader.getName())){ object.setPatentPriority_date(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0.Factory.parse(reader)); reader.next(); } // End of if for expected property start element else{ // A start element we are not expecting indicates an invalid parameter was passed throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } while (!reader.isStartElement() && !reader.isEndElement()) reader.next(); if (reader.isStartElement()) // A start element we are not expecting indicates a trailing invalid property throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName()); } catch (javax.xml.stream.XMLStreamException e) { throw new java.lang.Exception(e); } return object; } }//end of factory class }
milot-mirdita/GeMuDB
Vendor/NCBI eutils/src/gov/nih/nlm/ncbi/www/soap/eutils/efetch_gene/PatentPriority_type0.java
Java
bsd-2-clause
28,888
/* Copyright (c) 2013, Anthony Cornehl * 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 "check/twinshadow.h" #include "twinshadow/string.h" char *buf_strstrip; START_TEST(strstrip_removes_preceding_and_trailing_whitespace) { ts_strstrip(buf_strstrip); ck_assert_str_eq(buf_strstrip, "one two three"); } END_TEST void setup_strstrip_test(void) { buf_strstrip = strdup(" one two three "); } void teardown_strstrip_test(void) { free(buf_strstrip); } TCase * tcase_strstrip(void) { TCase *tc = tcase_create("strstrip"); tcase_add_checked_fixture(tc, setup_strstrip_test, teardown_strstrip_test); tcase_add_test(tc, strstrip_removes_preceding_and_trailing_whitespace); return tc; } CHECK_MAIN_STANDALONE(strstrip);
twinshadow/tslibc
src/string/check_strstrip.c
C
bsd-2-clause
2,026