code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
package digilib.conf; /* * #%L * * ManifesteServletConfiguration.java * * Digital Image Library servlet components * %% * Copyright (C) 2003 - 2017 MPIWG Berlin * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% * Author: Robert Casties (robcast@sourceforge.net) * Created on 24.5.2017 */ import javax.servlet.ServletContext; import javax.servlet.annotation.WebListener; /** * Class to hold the digilib servlet configuration parameters. The parameters * can be read from the digilib-config file and be passed to other servlets or * beans. * * @author casties */ @WebListener public class ManifestServletConfiguration extends DigilibServletConfiguration { public static final String MANIFEST_SERVLET_CONFIG_KEY = "digilib.manifest.servlet.configuration"; public static String getClassVersion() { return DigilibConfiguration.getClassVersion() + " manif"; } /** non-static getVersion for Java inheritance */ @Override public String getVersion() { return getClassVersion(); } /** * Constructs DigilibServletConfiguration and defines all parameters and * their default values. */ public ManifestServletConfiguration() { super(); // base URL used in constructing IIIF manifests including servlet name and iiif-prefix (optional) newParameter("iiif-manifest-base-url", null, null, 'f'); // web-application base URL used in constructing API paths (optional) newParameter("webapp-base-url", null, null, 'f'); // Scaler servlet name used in constructing IIIF image API paths newParameter("scaler-servlet-name", "Scaler", null, 'f'); // how to generate label for pages newParameter("iiif-manifest-page-label", "filename", null, 'f'); } /* * (non-Javadoc) * * @see digilib.conf.DigilibServletConfiguration#configure(javax.servlet. * ServletContext) */ @Override public void configure(ServletContext context) { super.configure(context); // set version setValue("servlet.version", getVersion()); } /* * Sets the current DigilibConfiguration in the context. * @param context */ @Override public void setContextConfig(ServletContext context) { context.setAttribute(ManifestServletConfiguration.MANIFEST_SERVLET_CONFIG_KEY, this); } /** * Returns the current ManifestServletConfiguration from the context. * * @param context the ServletContext * @return the DigilibServletConfiguration */ public static DigilibServletConfiguration getCurrentConfig(ServletContext context) { DigilibServletConfiguration config = (DigilibServletConfiguration) context .getAttribute(ManifestServletConfiguration.MANIFEST_SERVLET_CONFIG_KEY); return config; } /** * Returns the current DigilibConfiguration from the context. * (non-static method, for Java inheritance) * * @param context the ServletContext * @return the DigilibServletConfiguration */ @Override protected DigilibServletConfiguration getContextConfig(ServletContext context) { return getCurrentConfig(context); } }
robcast/digilib
iiif-presentation/src/main/java/digilib/conf/ManifestServletConfiguration.java
Java
lgpl-3.0
3,907
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.engine.util; import java.text.AttributedCharacterIterator.Attribute; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.swing.JEditorPane; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import javax.swing.text.Element; import javax.swing.text.AbstractDocument.LeafElement; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * @author Teodor Danciu (teodord@users.sourceforge.net) * @version $Id: JEditorPaneRtfMarkupProcessor.java 5878 2013-01-07 20:23:13Z teodord $ */ public class JEditorPaneRtfMarkupProcessor extends JEditorPaneMarkupProcessor { private static final Log log = LogFactory.getLog(JEditorPaneRtfMarkupProcessor.class); private static JEditorPaneRtfMarkupProcessor instance; /** * */ public static JEditorPaneRtfMarkupProcessor getInstance() { if (instance == null) { instance = new JEditorPaneRtfMarkupProcessor(); } return instance; } /** * */ public String convert(String srcText) { JEditorPane editorPane = new JEditorPane("text/rtf", srcText); editorPane.setEditable(false); List<Element> elements = new ArrayList<Element>(); Document document = editorPane.getDocument(); Element root = document.getDefaultRootElement(); if (root != null) { addElements(elements, root); } String chunk = null; Element element = null; int startOffset = 0; int endOffset = 0; JRStyledText styledText = new JRStyledText(); styledText.setGlobalAttributes(new HashMap<Attribute,Object>()); for(int i = 0; i < elements.size(); i++) { if (chunk != null) { styledText.append(chunk); styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset)); } chunk = null; element = elements.get(i); startOffset = element.getStartOffset(); endOffset = element.getEndOffset(); try { chunk = document.getText(startOffset, endOffset - startOffset); } catch(BadLocationException e) { if (log.isDebugEnabled()) { log.debug("Error converting markup.", e); } } } if (chunk != null && !"\n".equals(chunk)) { styledText.append(chunk); styledText.addRun(new JRStyledText.Run(getAttributes(element.getAttributes()), startOffset, endOffset)); } return JRStyledTextParser.getInstance().write(styledText); } /** * */ protected void addElements(List<Element> elements, Element element) { if(element instanceof LeafElement) { elements.add(element); } for(int i = 0; i < element.getElementCount(); i++) { Element child = element.getElement(i); addElements(elements, child); } } }
sikachu/jasperreports
src/net/sf/jasperreports/engine/util/JEditorPaneRtfMarkupProcessor.java
Java
lgpl-3.0
3,734
big = 2000000 # B = the number below which primes are summed p = [True] * big # P = whether a number is prime, all are initially true and will later be falsified print("running sieve...") s = 0 # S = the sum of primes less than big which begins as 0 for a in range(2, big): # loop A over all divisors less than BIG if p[a]: # if A is prime s += a # then add A to S for b in range(a * a, big, a): # loop over multiples of A from A*A (first relatively prime) less than BIG, inc. by A p[b] = False # the multiple isn't prime print(s)
rck109d/projectEuler
src/euler/p10_sieve.py
Python
lgpl-3.0
748
<?php //file: view/users/register.php require_once(__DIR__."/../../core/ViewManager.php"); $view = ViewManager::getInstance(); $errors = $view->getVariable("errors"); $user = $view->getVariable("user"); $view->setVariable("title", "Register"); ?> <div class="row registrarE"> <div class="divLogin col-xs-12 col-sm-12 col-md-12"> <h2>Jurado</h2> <form id="form-login" action="index.php?controller=users&amp;action=registerPopular" method="POST"> <label for="usuario">Usuario *</label><p class="error"><?= isset($errors["usuario"])?$errors["usuario"]:"" ?></p> <input name="usuario" class="registrar" type="text" id="usuario" required/></p> <label for="nombre">Nombre *</label> <input name="nombre" class="registrar" type="text" id="nombre" required/ ></p> <label for="correo">Correo *</label> <input name="correo" class="registrar" type="email" id="correo" required/></p> <label for="residencia">Residencia *</label> <input name="residencia" class="registrar" type="text" id="residencia" required/></p> <label for="pass">Contraseña *</label> <input name="pass" class="registrar" type="password" id="pass" required/></p> <label for="repass">Repetir contraseña *</label><p class="error"><?= isset($errors["pass"])?$errors["pass"]:"" ?></p> <input name="repass" class="registrar" type="password" id="repass" required/></p> <p id="bot"><input name="submit" type="submit" id="boton" value="Registrar" class="boton"/></p> </form> </div> </div>
xrlopez/ABP
view/users/registerPopular.php
PHP
lgpl-3.0
1,547
<!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 (1.8.0_92) on Tue Jan 16 10:58:46 PST 2018 --> <title>AccountGroup</title> <meta name="date" content="2018-01-16"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="AccountGroup"; } } catch(err) { } //--> var methods = {"i0":10,"i1":10,"i2":10,"i3":10,"i4":10,"i5":10,"i6":10,"i7":10,"i8":10,"i9":10,"i10":10,"i11":10,"i12":10,"i13":10}; var tabs = {65535:["t0","All Methods"],2:["t2","Instance Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <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="class-use/AccountGroup.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/Account.html" title="class in com.poesys.accounting.dataloader.oldaccounting"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountMap.html" title="class in com.poesys.accounting.dataloader.oldaccounting"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" target="_top">Frames</a></li> <li><a href="AccountGroup.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;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="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&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">com.poesys.accounting.dataloader.oldaccounting</div> <h2 title="Class AccountGroup" class="title">Class AccountGroup</h2> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">com.poesys.accounting.dataloader.oldaccounting.AbstractReaderDto</a></li> <li> <ul class="inheritance"> <li>com.poesys.accounting.dataloader.oldaccounting.AccountGroup</li> </ul> </li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <dl> <dt>All Implemented Interfaces:</dt> <dd>java.lang.Comparable&lt;<a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AccountGroup</a>&gt;</dd> </dl> <hr> <br> <pre>public class <span class="typeNameLabel">AccountGroup</span> extends <a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AbstractReaderDto</a> implements java.lang.Comparable&lt;<a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AccountGroup</a>&gt;</pre> <div class="block"><p> Data transfer object representing old-accounting account group data; groups the accounts into categories like Cash or Accounts Receivable by grouping the account numbers into ranges. Each account group has a starting account number and and ending account number that defines the range of accounts in the group. The contains() method lets the client determine whether an account number is in this group. The groups within a year should be mutually exclusive; that is, the start-end intervals must not overlap. The equals() method tests for equality based on name, year, and account type. </p> <p> Reads the data from a tab-delimited file with three fields: start, end, name </p> <p> This test suite tests the branches for the AbstractReaderDto superclass constructor by instantiating a concrete subclass and verifying the appropriate exceptions. The test suites for the other concrete subclasses thus do not test these cases. </p></div> <dl> <dt><span class="simpleTagLabel">Author:</span></dt> <dd>Robert J. Muller</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- =========== FIELD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="field.summary"> <!-- --> </a> <h3>Field Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Field Summary table, listing fields, and an explanation"> <caption><span>Fields</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Field and Description</th> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.lang.Float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#end">end</a></span></code> <div class="block">last account number in group</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#name">name</a></span></code> <div class="block">the name of the group</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#orderNumber">orderNumber</a></span></code> <div class="block">rank order of group within account type</div> </td> </tr> <tr class="rowColor"> <td class="colFirst"><code>private java.lang.Float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#start">start</a></span></code> <div class="block">first account number in group</div> </td> </tr> <tr class="altColor"> <td class="colFirst"><code>private java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#year">year</a></span></code> <div class="block">the fiscal year to which the account group applies</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="fields.inherited.from.class.com.poesys.accounting.dataloader.oldaccounting.AbstractReaderDto"> <!-- --> </a> <h3>Fields inherited from class&nbsp;com.poesys.accounting.dataloader.oldaccounting.<a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AbstractReaderDto</a></h3> <code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#DELIMITER">DELIMITER</a>, <a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#END_OF_STREAM_MSG">END_OF_STREAM_MSG</a>, <a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#INVALID_FIELDS_ERROR">INVALID_FIELDS_ERROR</a>, <a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#IO_EXCEPTION_ERROR">IO_EXCEPTION_ERROR</a>, <a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#NULL_PARAMETER_ERROR">NULL_PARAMETER_ERROR</a>, <a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#NULL_READER_ERROR">NULL_READER_ERROR</a></code></li> </ul> </li> </ul> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#AccountGroup-java.lang.Integer-java.io.BufferedReader-">AccountGroup</a></span>(java.lang.Integer&nbsp;year, java.io.BufferedReader&nbsp;reader)</code> <div class="block">Create an AccountGroup object reading from a tab-delimited line.</div> </td> </tr> <tr class="rowColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#AccountGroup-java.lang.Integer-java.lang.String-java.lang.Float-java.lang.Float-">AccountGroup</a></span>(java.lang.Integer&nbsp;year, java.lang.String&nbsp;name, java.lang.Float&nbsp;start, java.lang.Float&nbsp;end)</code> <div class="block">Create a AccountGroup object.</div> </td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t2" class="tableTab"><span><a href="javascript:show(2);">Instance Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#compareTo-com.poesys.accounting.dataloader.oldaccounting.AccountGroup-">compareTo</a></span>(<a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AccountGroup</a>&nbsp;o)</code>&nbsp;</td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#contains-java.lang.Integer-java.lang.Float-">contains</a></span>(java.lang.Integer&nbsp;year, java.lang.Float&nbsp;account)</code> <div class="block">Does this account group contain the account?</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>boolean</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#equals-java.lang.Object-">equals</a></span>(java.lang.Object&nbsp;obj)</code>&nbsp;</td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code><a href="../../../../../com/poesys/accounting/dataloader/newaccounting/AccountType.html" title="enum in com.poesys.accounting.dataloader.newaccounting">AccountType</a></code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#getAccountType--">getAccountType</a></span>()</code> <div class="block">Get the account type of the group.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#getEnd--">getEnd</a></span>()</code> <div class="block">Get the ending account number.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#getName--">getName</a></span>()</code> <div class="block">Get the name.</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#getOrderNumber--">getOrderNumber</a></span>()</code> <div class="block">Get the group order number.</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>java.lang.Float</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#getStart--">getStart</a></span>()</code> <div class="block">Get the starting account.</div> </td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>java.lang.Integer</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#getYear--">getYear</a></span>()</code> <div class="block">Get the year.</div> </td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#hashCode--">hashCode</a></span>()</code>&nbsp;</td> </tr> <tr id="i10" class="altColor"> <td class="colFirst"><code>protected void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#init-java.lang.String:A-">init</a></span>(java.lang.String[]&nbsp;fields)</code> <div class="block">Callback to initialize the fields specific to a concrete DTO subclass</div> </td> </tr> <tr id="i11" class="rowColor"> <td class="colFirst"><code>protected int</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#numberOfFields--">numberOfFields</a></span>()</code> <div class="block">Get the number of fields expected from a line of input data.</div> </td> </tr> <tr id="i12" class="altColor"> <td class="colFirst"><code>void</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#setOrderNumber-java.lang.Integer-">setOrderNumber</a></span>(java.lang.Integer&nbsp;orderNumber)</code> <div class="block">Set the group order number.</div> </td> </tr> <tr id="i13" class="rowColor"> <td class="colFirst"><code>java.lang.String</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html#toString--">toString</a></span>()</code>&nbsp;</td> </tr> </table> <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>clone, finalize, getClass, notify, notifyAll, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ============ FIELD DETAIL =========== --> <ul class="blockList"> <li class="blockList"><a name="field.detail"> <!-- --> </a> <h3>Field Detail</h3> <a name="year"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>year</h4> <pre>private final&nbsp;java.lang.Integer year</pre> <div class="block">the fiscal year to which the account group applies</div> </li> </ul> <a name="name"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>name</h4> <pre>private&nbsp;java.lang.String name</pre> <div class="block">the name of the group</div> </li> </ul> <a name="start"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>start</h4> <pre>private&nbsp;java.lang.Float start</pre> <div class="block">first account number in group</div> </li> </ul> <a name="end"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>end</h4> <pre>private&nbsp;java.lang.Float end</pre> <div class="block">last account number in group</div> </li> </ul> <a name="orderNumber"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>orderNumber</h4> <pre>private&nbsp;java.lang.Integer orderNumber</pre> <div class="block">rank order of group within account type</div> </li> </ul> </li> </ul> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="AccountGroup-java.lang.Integer-java.lang.String-java.lang.Float-java.lang.Float-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>AccountGroup</h4> <pre>public&nbsp;AccountGroup(java.lang.Integer&nbsp;year, java.lang.String&nbsp;name, java.lang.Float&nbsp;start, java.lang.Float&nbsp;end)</pre> <div class="block">Create a AccountGroup object.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>year</code> - the fiscal year to which the account group applies</dd> <dd><code>name</code> - the name of the group</dd> <dd><code>start</code> - first account number in group</dd> <dd><code>end</code> - last account number in group</dd> </dl> </li> </ul> <a name="AccountGroup-java.lang.Integer-java.io.BufferedReader-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>AccountGroup</h4> <pre>public&nbsp;AccountGroup(java.lang.Integer&nbsp;year, java.io.BufferedReader&nbsp;reader)</pre> <div class="block">Create an AccountGroup object reading from a tab-delimited line. The client is responsible for opening and closing the reader. The client should catch the EndOfStream throwable to determine when reading is complete and to then close the reader.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>year</code> - the fiscal year being read</dd> <dd><code>reader</code> - the buffered reader set at the current line to read</dd> </dl> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="init-java.lang.String:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>init</h4> <pre>protected&nbsp;void&nbsp;init(java.lang.String[]&nbsp;fields)</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from class:&nbsp;<code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#init-java.lang.String:A-">AbstractReaderDto</a></code></span></div> <div class="block">Callback to initialize the fields specific to a concrete DTO subclass</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#init-java.lang.String:A-">init</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AbstractReaderDto</a></code></dd> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>fields</code> - the array of data values</dd> </dl> </li> </ul> <a name="numberOfFields--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>numberOfFields</h4> <pre>protected&nbsp;int&nbsp;numberOfFields()</pre> <div class="block"><span class="descfrmTypeLabel">Description copied from class:&nbsp;<code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#numberOfFields--">AbstractReaderDto</a></code></span></div> <div class="block">Get the number of fields expected from a line of input data. The concrete subclass overrides this to return the correct integer.</div> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#numberOfFields--">numberOfFields</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AbstractReaderDto</a></code></dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>the number of fields</dd> </dl> </li> </ul> <a name="getYear--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getYear</h4> <pre>public&nbsp;java.lang.Integer&nbsp;getYear()</pre> <div class="block">Get the year.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>a year</dd> </dl> </li> </ul> <a name="getName--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getName</h4> <pre>public&nbsp;java.lang.String&nbsp;getName()</pre> <div class="block">Get the name.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>a name</dd> </dl> </li> </ul> <a name="getStart--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getStart</h4> <pre>public&nbsp;java.lang.Float&nbsp;getStart()</pre> <div class="block">Get the starting account.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>an account number</dd> </dl> </li> </ul> <a name="getEnd--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getEnd</h4> <pre>public&nbsp;java.lang.Float&nbsp;getEnd()</pre> <div class="block">Get the ending account number.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>an account number</dd> </dl> </li> </ul> <a name="getOrderNumber--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getOrderNumber</h4> <pre>public&nbsp;java.lang.Integer&nbsp;getOrderNumber()</pre> <div class="block">Get the group order number.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>an integer</dd> </dl> </li> </ul> <a name="setOrderNumber-java.lang.Integer-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>setOrderNumber</h4> <pre>public&nbsp;void&nbsp;setOrderNumber(java.lang.Integer&nbsp;orderNumber)</pre> <div class="block">Set the group order number.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>orderNumber</code> - an integer rank ordering of the group</dd> </dl> </li> </ul> <a name="contains-java.lang.Integer-java.lang.Float-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>contains</h4> <pre>public&nbsp;boolean&nbsp;contains(java.lang.Integer&nbsp;year, java.lang.Float&nbsp;account)</pre> <div class="block">Does this account group contain the account?</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>year</code> - the fiscal year</dd> <dd><code>account</code> - the account to look up</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>true if the group includes the account number</dd> </dl> </li> </ul> <a name="getAccountType--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getAccountType</h4> <pre>public&nbsp;<a href="../../../../../com/poesys/accounting/dataloader/newaccounting/AccountType.html" title="enum in com.poesys.accounting.dataloader.newaccounting">AccountType</a>&nbsp;getAccountType()</pre> <div class="block">Get the account type of the group.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>an account type or null if the interval does not correspond to a known account type</dd> </dl> </li> </ul> <a name="hashCode--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>hashCode</h4> <pre>public&nbsp;int&nbsp;hashCode()</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#hashCode--">hashCode</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AbstractReaderDto</a></code></dd> </dl> </li> </ul> <a name="equals-java.lang.Object-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>equals</h4> <pre>public&nbsp;boolean&nbsp;equals(java.lang.Object&nbsp;obj)</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html#equals-java.lang.Object-">equals</a></code>&nbsp;in class&nbsp;<code><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AbstractReaderDto.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AbstractReaderDto</a></code></dd> </dl> </li> </ul> <a name="compareTo-com.poesys.accounting.dataloader.oldaccounting.AccountGroup-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>compareTo</h4> <pre>public&nbsp;int&nbsp;compareTo(<a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AccountGroup</a>&nbsp;o)</pre> <dl> <dt><span class="overrideSpecifyLabel">Specified by:</span></dt> <dd><code>compareTo</code>&nbsp;in interface&nbsp;<code>java.lang.Comparable&lt;<a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" title="class in com.poesys.accounting.dataloader.oldaccounting">AccountGroup</a>&gt;</code></dd> </dl> </li> </ul> <a name="toString--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>toString</h4> <pre>public&nbsp;java.lang.String&nbsp;toString()</pre> <dl> <dt><span class="overrideSpecifyLabel">Overrides:</span></dt> <dd><code>toString</code>&nbsp;in class&nbsp;<code>java.lang.Object</code></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> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <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="class-use/AccountGroup.html">Use</a></li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-files/index-1.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/Account.html" title="class in com.poesys.accounting.dataloader.oldaccounting"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../../../com/poesys/accounting/dataloader/oldaccounting/AccountMap.html" title="class in com.poesys.accounting.dataloader.oldaccounting"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html" target="_top">Frames</a></li> <li><a href="AccountGroup.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All&nbsp;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="#field.summary">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li><a href="#field.detail">Field</a>&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Poesys-Associates/dataloader
dataloader/doc/com/poesys/accounting/dataloader/oldaccounting/AccountGroup.html
HTML
lgpl-3.0
30,698
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import Marionette from 'backbone.marionette'; import CreateView from './create-view'; import Template from './templates/custom-measures-header.hbs'; export default Marionette.ItemView.extend({ template: Template, events: { 'click #custom-measures-create': 'onCreateClick' }, onCreateClick (e) { e.preventDefault(); this.createCustomMeasure(); }, createCustomMeasure () { new CreateView({ collection: this.collection, projectId: this.options.projectId }).render(); } });
Builders-SonarSource/sonarqube-bis
server/sonar-web/src/main/js/apps/custom-measures/header-view.js
JavaScript
lgpl-3.0
1,367
package net.ghue.jelenium.demo.guice; public final class MyServiceImpl implements MyService { @Override public String getStuff() { return "IMPLEMENTATION"; } }
lukelast/jelenium
demo/src/main/java/net/ghue/jelenium/demo/guice/MyServiceImpl.java
Java
lgpl-3.0
177
<?php /** * This file is part of the highcharts-bundle package. * * (c) 2017 WEBEWEB * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace WBW\Bundle\HighchartsBundle\Tests\API\Chart\NoData; use WBW\Bundle\HighchartsBundle\Tests\AbstractTestCase; /** * Highcharts position test. * * @author webeweb <https://github.com/webeweb/> * @package WBW\Bundle\HighchartsBundle\Tests\API\Chart\NoData * @version 5.0.14 */ final class HighchartsPositionTest extends AbstractTestCase { /** * Tests the __construct() method. * * @return void */ public function testConstructor() { $obj1 = new \WBW\Bundle\HighchartsBundle\API\Chart\NoData\HighchartsPosition(true); $this->assertNull($obj1->getAlign()); $this->assertNull($obj1->getVerticalAlign()); $this->assertNull($obj1->getX()); $this->assertNull($obj1->getY()); $obj0 = new \WBW\Bundle\HighchartsBundle\API\Chart\NoData\HighchartsPosition(false); $this->assertEquals("center", $obj0->getAlign()); $this->assertEquals("middle", $obj0->getVerticalAlign()); $this->assertEquals(0, $obj0->getX()); $this->assertEquals(0, $obj0->getY()); } /** * Tests the jsonSerialize() method. * * @return void */ public function testJsonSerialize() { $obj = new \WBW\Bundle\HighchartsBundle\API\Chart\NoData\HighchartsPosition(true); $this->assertEquals([], $obj->jsonSerialize()); } /** * Tests the toArray() method. * * @return void */ public function testToArray() { $obj = new \WBW\Bundle\HighchartsBundle\API\Chart\NoData\HighchartsPosition(true); $obj->setAlign("right"); $res1 = ["align" => "right"]; $this->assertEquals($res1, $obj->toArray()); $obj->setVerticalAlign("bottom"); $res2 = ["align" => "right", "verticalAlign" => "bottom"]; $this->assertEquals($res2, $obj->toArray()); $obj->setX(15); $res3 = ["align" => "right", "verticalAlign" => "bottom", "x" => 15]; $this->assertEquals($res3, $obj->toArray()); $obj->setY(92); $res4 = ["align" => "right", "verticalAlign" => "bottom", "x" => 15, "y" => 92]; $this->assertEquals($res4, $obj->toArray()); } }
webeweb/WBWHighchartsBundle
Tests/API/Chart/NoData/HighchartsPositionTest.php
PHP
lgpl-3.0
2,410
/** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.widgets; import android.content.ComponentName; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.graphics.Rect; import android.graphics.drawable.BitmapDrawable; import android.os.Handler; import android.util.AttributeSet; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.csipsimple.R; import com.csipsimple.api.SipProfile; import com.csipsimple.utils.AccountListUtils; import com.csipsimple.utils.AccountListUtils.AccountStatusDisplay; import com.csipsimple.utils.CallHandlerPlugin; import com.csipsimple.utils.CallHandlerPlugin.OnLoadListener; import com.csipsimple.utils.Compatibility; import com.csipsimple.utils.Log; import com.csipsimple.wizards.WizardUtils; import java.util.Map; public class AccountChooserButton extends LinearLayout implements OnClickListener { protected static final String THIS_FILE = "AccountChooserButton"; private static final String[] ACC_PROJECTION = new String[] { SipProfile.FIELD_ID, SipProfile.FIELD_ACC_ID, // Needed for default domain SipProfile.FIELD_REG_URI, // Needed for default domain SipProfile.FIELD_PROXY, // Needed for default domain SipProfile.FIELD_TRANSPORT, // Needed for default scheme SipProfile.FIELD_DISPLAY_NAME, SipProfile.FIELD_WIZARD }; private final TextView textView; private final ImageView imageView; private HorizontalQuickActionWindow quickAction; private SipProfile account = null; private Long targetAccountId = null; private boolean showExternals = true; private final ComponentName telCmp; private OnAccountChangeListener onAccountChange = null; /** * Interface definition for a callback to be invoked when PjSipAccount is * choosen */ public interface OnAccountChangeListener { /** * Called when the user make an action * * @param keyCode keyCode pressed * @param dialTone corresponding dialtone */ void onChooseAccount(SipProfile account); } public AccountChooserButton(Context context) { this(context, null); } public AccountChooserButton(Context context, AttributeSet attrs) { super(context, attrs); telCmp = new ComponentName(getContext(), com.csipsimple.plugins.telephony.CallHandler.class); // UI management setClickable(true); setFocusable(true); setBackgroundResource(R.drawable.abs__spinner_ab_holo_dark); setOrientation(VERTICAL); setPadding(6, 0, 6, 0); setGravity(Gravity.CENTER); // Inflate sub views LayoutInflater inflater = LayoutInflater.from(context); inflater.inflate(R.layout.account_chooser_button, this, true); setOnClickListener(this); textView = (TextView) findViewById(R.id.quickaction_text); imageView = (ImageView) findViewById(R.id.quickaction_icon); // Init accounts setAccount(null); } public AccountChooserButton(Context context, AttributeSet attrs, int style) { this(context, attrs); } private final Handler mHandler = new Handler(); private AccountStatusContentObserver statusObserver = null; private boolean canChangeIfValid = true; /** * Observer for changes of account registration status */ class AccountStatusContentObserver extends ContentObserver { public AccountStatusContentObserver(Handler h) { super(h); } public void onChange(boolean selfChange) { Log.d(THIS_FILE, "Accounts status.onChange( " + selfChange + ")"); updateRegistration(); } } /** * Allow this widget to automatically change the current account without * user interaction if a new account is registered with higher priority * * @param changeable Whether the widget is allowed to change selected * account by itself */ public void setChangeable(boolean changeable) { canChangeIfValid = changeable; } /** * Set the account id that should be tried to be adopted by this button if * available If null it will try to select account with higher priority * * @param aTargetAccountId id of the account to try to select */ public void setTargetAccount(Long aTargetAccountId) { targetAccountId = aTargetAccountId; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if(statusObserver == null) { statusObserver = new AccountStatusContentObserver(mHandler); getContext().getContentResolver().registerContentObserver(SipProfile.ACCOUNT_STATUS_URI, true, statusObserver); } if(!isInEditMode()) { updateRegistration(); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (statusObserver != null) { getContext().getContentResolver().unregisterContentObserver(statusObserver); statusObserver = null; } } @Override public void onClick(View v) { Log.d(THIS_FILE, "Click the account chooser button"); int[] xy = new int[2]; v.getLocationInWindow(xy); Rect r = new Rect(xy[0], xy[1], xy[0] + v.getWidth(), xy[1] + v.getHeight()); if (quickAction == null) { quickAction = new HorizontalQuickActionWindow(getContext(), this); } quickAction.setAnchor(r); quickAction.removeAllItems(); Cursor c = getContext().getContentResolver().query(SipProfile.ACCOUNT_URI, ACC_PROJECTION, SipProfile.FIELD_ACTIVE + "=?", new String[] { "1" }, null); if (c != null) { try { if (c.moveToFirst()) { do { final SipProfile account = new SipProfile(c); AccountStatusDisplay accountStatusDisplay = AccountListUtils .getAccountDisplay(getContext(), account.id); if (accountStatusDisplay.availableForCalls) { BitmapDrawable drawable = new BitmapDrawable(getResources(), WizardUtils.getWizardBitmap(getContext(), account)); quickAction.addItem(drawable, account.display_name, new OnClickListener() { public void onClick(View v) { setAccount(account); quickAction.dismiss(); } }); } } while (c.moveToNext()); } } catch (Exception e) { Log.e(THIS_FILE, "Error on looping over sip profiles", e); } finally { c.close(); } } if (showExternals) { // Add external rows Map<String, String> callHandlers = CallHandlerPlugin.getAvailableCallHandlers(getContext()); boolean includeGsm = Compatibility.canMakeGSMCall(getContext()); for (String packageName : callHandlers.keySet()) { Log.d(THIS_FILE, "Compare "+packageName+" to "+telCmp.flattenToString()); // We ensure that GSM integration is not prevented if(!includeGsm && packageName.equals(telCmp.flattenToString())) { continue; } // Else we can add CallHandlerPlugin ch = new CallHandlerPlugin(getContext()); ch.loadFrom(packageName, null, new OnLoadListener() { @Override public void onLoad(final CallHandlerPlugin ch) { quickAction.addItem(ch.getIconDrawable(), ch.getLabel().toString(), new OnClickListener() { @Override public void onClick(View v) { setAccount(ch.getFakeProfile()); quickAction.dismiss(); } }); } }); } } quickAction.show(); } /** * Set the currently selected account for this widget * It will change internal state, * Change icon and label of the account * @param aAccount */ public void setAccount(SipProfile aAccount) { account = aAccount; if (account == null) { if(isInEditMode() || Compatibility.canMakeGSMCall(getContext())) { textView.setText(getResources().getString(R.string.gsm)); imageView.setImageResource(R.drawable.ic_wizard_gsm); }else { textView.setText(getResources().getString(R.string.acct_inactive)); imageView.setImageResource(android.R.drawable.ic_dialog_alert); } } else { textView.setText(account.display_name); imageView.setImageDrawable(new BitmapDrawable(getResources(), WizardUtils.getWizardBitmap(getContext(), account))); } if (onAccountChange != null) { onAccountChange.onChooseAccount(account); } } /** * Update user interface when registration of account has changed * This include change selected account if we are in canChangeIfValid mode */ private void updateRegistration() { Cursor c = getContext().getContentResolver().query(SipProfile.ACCOUNT_URI, ACC_PROJECTION, SipProfile.FIELD_ACTIVE + "=?", new String[] { "1" }, null); SipProfile toSelectAcc = null; SipProfile firstAvail = null; if (c != null) { try { if (c.getCount() > 0 && c.moveToFirst()) { do { final SipProfile acc = new SipProfile(c); AccountStatusDisplay accountStatusDisplay = AccountListUtils .getAccountDisplay(getContext(), acc.id); if (accountStatusDisplay.availableForCalls) { if (firstAvail == null) { firstAvail = acc; } if (canChangeIfValid) { // We can change even if valid, so select this // account if valid for outgoings if(targetAccountId != null) { // Check if this is the target one if(targetAccountId == acc.id) { toSelectAcc = acc; break; } }else { // Select first toSelectAcc = acc; break; } } else if (account != null && account.id == acc.id) { // Current is valid toSelectAcc = acc; break; } } } while (c.moveToNext()); } } catch (Exception e) { Log.e(THIS_FILE, "Error on looping over sip profiles", e); } finally { c.close(); } } if (toSelectAcc == null) { // Nothing to force select, fallback to first avail toSelectAcc = firstAvail; } // Finally, set the account to be valid setAccount(toSelectAcc); } /** * Retrieve account that is currently selected by this widget * @return The SipProfile selected */ public SipProfile getSelectedAccount() { if (account == null) { SipProfile retAcc = new SipProfile(); if(showExternals) { Map<String, String> handlers = CallHandlerPlugin.getAvailableCallHandlers(getContext()); boolean includeGsm = Compatibility.canMakeGSMCall(getContext()); if(includeGsm) { for (String callHandler : handlers.keySet()) { // Try to prefer the GSM handler if (callHandler.equalsIgnoreCase(telCmp.flattenToString())) { retAcc.id = CallHandlerPlugin.getAccountIdForCallHandler(getContext(), callHandler); return retAcc; } } } // Fast way to get first if exists for (String callHandler : handlers.values()) { // Ignore tel handler if we do not include gsm in settings if(callHandler.equals(telCmp.flattenToString()) && !includeGsm) { continue; } retAcc.id = CallHandlerPlugin.getAccountIdForCallHandler(getContext(), callHandler); return retAcc; } } retAcc.id = SipProfile.INVALID_ID; return retAcc; } return account; } /** * Attach listened to the widget that will fire when account selection change * @param anAccountChangeListener the listener */ public void setOnAccountChangeListener(OnAccountChangeListener anAccountChangeListener) { onAccountChange = anAccountChangeListener; } /** * Set whether this button should consider plugins account as selectable accounts * @param b true if you want the widget to show external accounts */ public void setShowExternals(boolean b) { showExternals = b; } }
fingi/csipsimple
src/com/csipsimple/widgets/AccountChooserButton.java
Java
lgpl-3.0
15,559
#pragma once #include <logicalaccess/lla_core_api.hpp> #include <logicalaccess/services/cardservice.hpp> #include <logicalaccess/services/accesscontrol/formats/format.hpp> #include <nlohmann/json_fwd.hpp> #include <logicalaccess/services/accesscontrol/formatinfos.hpp> namespace logicalaccess { #define JSON_DUMP_CARDSERVICE "JSONDump" /** * A high level service that read data from a card and return * its content. * * The content to fetch, from format to keys, is described by JSON. * Similarly, the output is a JSON string representing the data * that have been extracted from the card. * * The input JSON format is RFID.onl format. Todo better documentation ? */ class LLA_CORE_API JsonDumpCardService : public CardService { public: constexpr static const CardServiceType service_type_ = CST_JSON_DUMP; virtual ~JsonDumpCardService(); explicit JsonDumpCardService(const std::shared_ptr<Chip> &chip); std::string getCSType() override { return JSON_DUMP_CARDSERVICE; } /** * Configure the service, providing the input JSON that will be used * to create internal object required to properly dump the content of the card. * * It is required to call configure() before calling dump(). */ void configure(const std::string &json_template); /** * Dump the content of the content of the card, according the configuration * provided at the configure() call. */ std::string dump(); std::map<std::string, std::shared_ptr<Format>> formats_; std::map<std::string, std::shared_ptr<Key>> keys_; std::map<std::string, std::shared_ptr<FormatInfos>> format_infos_; private: void extract_formats(const nlohmann::json & json); /** * Create a properly typed key object that can be used against the given * card. */ virtual std::shared_ptr<Key> create_key(const nlohmann::json &key_description) = 0; void extract_keys(const nlohmann::json & json); /** * Populate the format_infos_ map. * The subclass is expected to parse the provided JSON and create corresponding * FormatInfo with proper Format, Location and AccessInfo. */ virtual void configure_format_infos(const nlohmann::json & json) = 0; bool configured_; }; }
islog/liblogicalaccess
include/logicalaccess/services/json/json_dump_card_service.hpp
C++
lgpl-3.0
2,292
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of Qbs. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef QBS_ARTIFACTCLEANER_H #define QBS_ARTIFACTCLEANER_H #include <QtCore/qlist.h> #include <language/forward_decls.h> #include <logging/logger.h> namespace qbs { class CleanOptions; namespace Internal { class ProgressObserver; class ArtifactCleaner { public: ArtifactCleaner(const Logger &logger, ProgressObserver *observer); void cleanup(const TopLevelProjectPtr &project, const QList<ResolvedProductPtr> &products, const CleanOptions &options); private: void removeEmptyDirectories(const QString &rootDir, const CleanOptions &options, bool *isEmpty = 0); Logger m_logger; bool m_hasError; ProgressObserver *m_observer; }; } // namespace Internal } // namespace qbs #endif // QBS_ARTIFACTCLEANER_H
jakepetroules/qbs
src/lib/corelib/buildgraph/artifactcleaner.h
C
lgpl-3.0
2,673
package net.minecraft.src; import net.minecraft.client.Minecraft; import net.minecraft.src.Block; import net.minecraft.src.Entity; import net.minecraft.src.EntityPlayer; import net.minecraft.src.EntityPlayerSP; import net.minecraft.src.ItemStack; import net.minecraft.src.World; public abstract class PlayerController { protected final Minecraft mc; public boolean isInTestMode = false; public PlayerController(Minecraft var1) { this.mc = var1; } public void func_717_a(World var1) {} public abstract void clickBlock(int var1, int var2, int var3, int var4); public boolean sendBlockRemoved(int var1, int var2, int var3, int var4) { World var5 = this.mc.theWorld; Block var6 = Block.blocksList[var5.getBlockId(var1, var2, var3)]; if(var6 == null) { return false; } else { var5.playAuxSFX(2001, var1, var2, var3, var6.blockID + var5.getBlockMetadata(var1, var2, var3) * 256); int var7 = var5.getBlockMetadata(var1, var2, var3); boolean var8 = var5.setBlockWithNotify(var1, var2, var3, 0); if(var6 != null && var8) { var6.onBlockDestroyedByPlayer(var5, var1, var2, var3, var7); } return var8; } } public abstract void sendBlockRemoving(int var1, int var2, int var3, int var4); public abstract void resetBlockRemoving(); public void setPartialTime(float var1) {} public abstract float getBlockReachDistance(); public boolean sendUseItem(EntityPlayer var1, World var2, ItemStack var3) { //Spout Start if (var3 == null) return true; //Spout End int var4 = var3.stackSize; ItemStack var5 = var3.useItemRightClick(var2, var1); if(var5 == var3 && (var5 == null || var5.stackSize == var4)) { return false; } else { var1.inventory.mainInventory[var1.inventory.currentItem] = var5; if(var5.stackSize == 0) { var1.inventory.mainInventory[var1.inventory.currentItem] = null; } return true; } } public void flipPlayer(EntityPlayer var1) {} public void updateController() {} public abstract boolean shouldDrawHUD(); public void func_6473_b(EntityPlayer var1) {} public abstract boolean sendPlaceBlock(EntityPlayer var1, World var2, ItemStack var3, int var4, int var5, int var6, int var7); public EntityPlayer createPlayer(World var1) { return new EntityPlayerSP(this.mc, var1, this.mc.session, var1.worldProvider.worldType); } public void interactWithEntity(EntityPlayer var1, Entity var2) { var1.useCurrentItemOnEntity(var2); } public void attackEntity(EntityPlayer var1, Entity var2) { var1.attackTargetEntityWithCurrentItem(var2); } public ItemStack windowClick(int var1, int var2, int var3, boolean var4, EntityPlayer var5) { return var5.craftingInventory.slotClick(var2, var3, var4, var5); } public void func_20086_a(int var1, EntityPlayer var2) { var2.craftingInventory.onCraftGuiClosed(var2); var2.craftingInventory = var2.inventorySlots; } public boolean func_35643_e() { return false; } public void func_35638_c(EntityPlayer var1) { var1.func_35206_ab(); } public boolean func_35642_f() { return false; } public boolean func_35641_g() { return true; } public boolean isInCreativeMode() { return false; } public boolean func_35636_i() { return false; } public void func_35637_a(ItemStack var1, int var2) {} public void func_35639_a(ItemStack var1) {} }
copyliu/Spoutcraft_CJKPatch
src/minecraft/net/minecraft/src/PlayerController.java
Java
lgpl-3.0
3,449
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import { filter } from 'lodash'; import * as React from 'react'; import { Link } from 'react-router'; import { activateRule, deactivateRule, Profile } from '../../../api/quality-profiles'; import InstanceMessage from '../../../components/common/InstanceMessage'; import { Button } from '../../../components/controls/buttons'; import ConfirmButton from '../../../components/controls/ConfirmButton'; import Tooltip from '../../../components/controls/Tooltip'; import SeverityHelper from '../../../components/shared/SeverityHelper'; import { translate, translateWithParameters } from '../../../helpers/l10n'; import { getQualityProfileUrl } from '../../../helpers/urls'; import { Dict, RuleActivation, RuleDetails } from '../../../types/types'; import BuiltInQualityProfileBadge from '../../quality-profiles/components/BuiltInQualityProfileBadge'; import ActivationButton from './ActivationButton'; import RuleInheritanceIcon from './RuleInheritanceIcon'; interface Props { activations: RuleActivation[] | undefined; canWrite: boolean | undefined; onActivate: () => Promise<void>; onDeactivate: () => Promise<void>; referencedProfiles: Dict<Profile>; ruleDetails: RuleDetails; } export default class RuleDetailsProfiles extends React.PureComponent<Props> { handleActivate = () => this.props.onActivate(); handleDeactivate = (key?: string) => { if (key) { deactivateRule({ key, rule: this.props.ruleDetails.key }).then(this.props.onDeactivate, () => {}); } }; handleRevert = (key?: string) => { if (key) { activateRule({ key, rule: this.props.ruleDetails.key, reset: true }).then(this.props.onActivate, () => {}); } }; renderInheritedProfile = (activation: RuleActivation, profile: Profile) => { if (!profile.parentName) { return null; } const profilePath = getQualityProfileUrl(profile.parentName, profile.language); return ( <div className="coding-rules-detail-quality-profile-inheritance"> {(activation.inherit === 'OVERRIDES' || activation.inherit === 'INHERITED') && ( <> <RuleInheritanceIcon className="text-middle" inheritance={activation.inherit} /> <Link className="link-base-color little-spacer-left text-middle" to={profilePath}> {profile.parentName} </Link> </> )} </div> ); }; renderSeverity = (activation: RuleActivation, parentActivation?: RuleActivation) => ( <td className="coding-rules-detail-quality-profile-severity"> <Tooltip overlay={translate('coding_rules.activation_severity')}> <span> <SeverityHelper className="display-inline-flex-center" severity={activation.severity} /> </span> </Tooltip> {parentActivation !== undefined && activation.severity !== parentActivation.severity && ( <div className="coding-rules-detail-quality-profile-inheritance"> {translate('coding_rules.original')} {translate('severity', parentActivation.severity)} </div> )} </td> ); renderParameter = (param: { key: string; value: string }, parentActivation?: RuleActivation) => { const originalParam = parentActivation && parentActivation.params.find(p => p.key === param.key); const originalValue = originalParam && originalParam.value; return ( <div className="coding-rules-detail-quality-profile-parameter" key={param.key}> <span className="key">{param.key}</span> <span className="sep">: </span> <span className="value" title={param.value}> {param.value} </span> {parentActivation && param.value !== originalValue && ( <div className="coding-rules-detail-quality-profile-inheritance"> {translate('coding_rules.original')} <span className="value">{originalValue}</span> </div> )} </div> ); }; renderParameters = (activation: RuleActivation, parentActivation?: RuleActivation) => ( <td className="coding-rules-detail-quality-profile-parameters"> {activation.params.map(param => this.renderParameter(param, parentActivation))} </td> ); renderActions = (activation: RuleActivation, profile: Profile) => { const canEdit = profile.actions && profile.actions.edit && !profile.isBuiltIn; const { ruleDetails } = this.props; const hasParent = activation.inherit !== 'NONE' && profile.parentKey; return ( <td className="coding-rules-detail-quality-profile-actions"> {canEdit && ( <> {!ruleDetails.isTemplate && ( <ActivationButton activation={activation} buttonText={translate('change_verb')} className="coding-rules-detail-quality-profile-change" modalHeader={translate('coding_rules.change_details')} onDone={this.handleActivate} profiles={[profile]} rule={ruleDetails} /> )} {hasParent ? ( activation.inherit === 'OVERRIDES' && profile.parentName && ( <ConfirmButton confirmButtonText={translate('yes')} confirmData={profile.key} modalBody={translateWithParameters( 'coding_rules.revert_to_parent_definition.confirm', profile.parentName )} modalHeader={translate('coding_rules.revert_to_parent_definition')} onConfirm={this.handleRevert}> {({ onClick }) => ( <Button className="coding-rules-detail-quality-profile-revert button-red spacer-left" onClick={onClick}> {translate('coding_rules.revert_to_parent_definition')} </Button> )} </ConfirmButton> ) ) : ( <ConfirmButton confirmButtonText={translate('yes')} confirmData={profile.key} modalBody={translate('coding_rules.deactivate.confirm')} modalHeader={translate('coding_rules.deactivate')} onConfirm={this.handleDeactivate}> {({ onClick }) => ( <Button className="coding-rules-detail-quality-profile-deactivate button-red spacer-left" onClick={onClick}> {translate('coding_rules.deactivate')} </Button> )} </ConfirmButton> )} </> )} </td> ); }; renderActivation = (activation: RuleActivation) => { const { activations = [], ruleDetails } = this.props; const profile = this.props.referencedProfiles[activation.qProfile]; if (!profile) { return null; } const parentActivation = activations.find(x => x.qProfile === profile.parentKey); return ( <tr data-profile={profile.key} key={profile.key}> <td className="coding-rules-detail-quality-profile-name"> <Link to={getQualityProfileUrl(profile.name, profile.language)}>{profile.name}</Link> {profile.isBuiltIn && <BuiltInQualityProfileBadge className="spacer-left" />} {this.renderInheritedProfile(activation, profile)} </td> {this.renderSeverity(activation, parentActivation)} {!ruleDetails.templateKey && this.renderParameters(activation, parentActivation)} {this.renderActions(activation, profile)} </tr> ); }; render() { const { activations = [], referencedProfiles, ruleDetails } = this.props; const canActivate = Object.values(referencedProfiles).some(profile => Boolean(profile.actions && profile.actions.edit && profile.language === ruleDetails.lang) ); return ( <div className="js-rule-profiles coding-rule-section"> <div className="coding-rules-detail-quality-profiles-section"> <div className="coding-rule-section-separator" /> <h3 className="coding-rules-detail-title"> <InstanceMessage message={translate('coding_rules.quality_profiles')} /> </h3> {canActivate && ( <ActivationButton buttonText={translate('coding_rules.activate')} className="coding-rules-quality-profile-activate spacer-left" modalHeader={translate('coding_rules.activate_in_quality_profile')} onDone={this.handleActivate} profiles={filter( this.props.referencedProfiles, profile => !activations.find(activation => activation.qProfile === profile.key) )} rule={ruleDetails} /> )} {activations.length > 0 && ( <table className="coding-rules-detail-quality-profiles width-100" id="coding-rules-detail-quality-profiles"> <tbody>{activations.map(this.renderActivation)}</tbody> </table> )} </div> </div> ); } }
SonarSource/sonarqube
server/sonar-web/src/main/js/apps/coding-rules/components/RuleDetailsProfiles.tsx
TypeScript
lgpl-3.0
10,058
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_24) on Thu Feb 09 13:44:18 GMT 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class gate.creole.test.DynamicRegistrationTest.TestResource (GATE JavaDoc (including private members)) </TITLE> <META NAME="date" CONTENT="2012-02-09"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class gate.creole.test.DynamicRegistrationTest.TestResource (GATE JavaDoc (including private members))"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../gate/creole/test/DynamicRegistrationTest.TestResource.html" title="class in gate.creole.test"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?gate/creole/test//class-useDynamicRegistrationTest.TestResource.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DynamicRegistrationTest.TestResource.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>gate.creole.test.DynamicRegistrationTest.TestResource</B></H2> </CENTER> No usage of gate.creole.test.DynamicRegistrationTest.TestResource <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../gate/creole/test/DynamicRegistrationTest.TestResource.html" title="class in gate.creole.test"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?gate/creole/test//class-useDynamicRegistrationTest.TestResource.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="DynamicRegistrationTest.TestResource.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
liuhongchao/GATE_Developer_7.0
doc/javadoc/internal/gate/creole/test/class-use/DynamicRegistrationTest.TestResource.html
HTML
lgpl-3.0
6,177
# Copyright (C) 2015-2022 by the RBniCS authors # # This file is part of RBniCS. # # SPDX-License-Identifier: LGPL-3.0-or-later from rbnics.utils.decorators import ABCMeta, AbstractBackend, abstractmethod @AbstractBackend class ReducedVertices(object, metaclass=ABCMeta): def __init__(self, space): pass @abstractmethod def append(self, vertex_and_component): pass @abstractmethod def save(self, directory, filename): pass @abstractmethod def load(self, directory, filename): pass @abstractmethod def __getitem__(self, key): pass
mathLab/RBniCS
rbnics/backends/abstract/reduced_vertices.py
Python
lgpl-3.0
613
# # GdbLib - A Gdb python library. # Copyright (C) 2012 Fernando Castillo # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # import os def change(values): pass def removeFile(path): index = path.rfind(os.sep) return path[:index]
skibyte/gdblib
gdblib/util.py
Python
lgpl-3.0
864
/* Copyright (C) 2010 Gaetan Guidet This file is part of ofxpp. ofxpp is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. ofxpp is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /** \file exception.h * Exception classes. */ #ifndef __ofx_exception_h__ #define __ofx_exception_h__ #include <ofxCore.h> #include <exception> #include <stdexcept> #include <string> namespace ofx { //! Base exception class. class Exception : public std::runtime_error { public: explicit Exception(OfxStatus s, const std::string &msg="", const char *statusString=0); virtual ~Exception() throw(); //! Get associated OpenFX status. inline OfxStatus status() const { return mStat; } protected: OfxStatus mStat; }; //! Failed exception. class FailedError : public Exception { public: explicit FailedError(const std::string &msg=""); virtual ~FailedError() throw(); }; //! Fatal exception. class FatalError : public Exception { public: explicit FatalError(const std::string &msg=""); virtual ~FatalError() throw(); }; //! Unknown exception. class UnknownError : public Exception { public: explicit UnknownError(const std::string &msg=""); virtual ~UnknownError() throw(); }; //! Missing host feature exception. class MissingHostFeatureError : public Exception { public: explicit MissingHostFeatureError(const std::string &msg=""); virtual ~MissingHostFeatureError() throw(); }; //! Unsupported exception. class UnsupportedError : public Exception { public: explicit UnsupportedError(const std::string &msg=""); virtual ~UnsupportedError() throw(); }; //! Exists exception. class ExistsError : public Exception { public: explicit ExistsError(const std::string &msg=""); virtual ~ExistsError() throw(); }; //! Format exception. class FormatError : public Exception { public: explicit FormatError(const std::string &msg=""); virtual ~FormatError() throw(); }; //! Memory exception. class MemoryError : public Exception { public: explicit MemoryError(const std::string &msg=""); virtual ~MemoryError() throw(); }; //! Bad handle exception. class BadHandleError : public Exception { public: explicit BadHandleError(const std::string &msg=""); virtual ~BadHandleError() throw(); }; //! Bad index exception. class BadIndexError : public Exception { public: explicit BadIndexError(const std::string &msg=""); virtual ~BadIndexError() throw(); }; //! Value exception. class ValueError : public Exception { public: explicit ValueError(const std::string &msg=""); virtual ~ValueError() throw(); }; //! Image format exception class ImageFormatError : public Exception { public: explicit ImageFormatError(const std::string &msg=""); virtual ~ImageFormatError() throw(); }; #ifdef OFX_API_1_3 class GLOutOfMemory : public Exception { public: explicit GLOutOfMemory(const std::string &msg=""); virtual ~GLOutOfMemory() throw(); }; class GLRenderFailed : public Exception { public: explicit GLRenderFailed(const std::string &msg=""); virtual ~GLRenderFailed() throw(); }; #endif } #endif
gatgui/ofxpp
include/ofx/exception.h
C
lgpl-3.0
3,985
<?php /** * Isotope eCommerce for Contao Open Source CMS * * Copyright (C) 2009-2014 terminal42 gmbh & Isotope eCommerce Workgroup * * @package Isotope * @link http://isotopeecommerce.org * @license http://opensource.org/licenses/lgpl-3.0.html */ namespace Isotope; use Isotope\Automator; use Isotope\Model\Config; use Isotope\Model\ProductCollection\Wishlist; /** * Class Isotope\WishlistAutomator * * Provide methods to run Isotope automated jobs. * @copyright Isotope eCommerce Workgroup 2009-2012 * @author Andreas Schempp <andreas.schempp@terminal42.ch> * @author Fred Bliss <fred.bliss@intelligentspark.com> */ class WishlistAutomator extends Automator { /** * Remove wishlists that have not been accessed for a given number of days */ public function deleteOldWishlists() { $t = Wishlist::getTable(); $objCarts = Wishlist::findBy(array("type='wishlist'", "$t.member=0", "$t.tstamp<?"), array(time() - $GLOBALS['TL_CONFIG']['iso_cartTimeout'])); if (($intPurged = $this->deleteOldCollections($objCarts)) > 0) { \System::log('Deleted ' . $intPurged . ' old guest wishlists', __METHOD__, TL_CRON); } } }
hb-agency/isotope_wishlist
library/Isotope/WishlistAutomator.php
PHP
lgpl-3.0
1,221
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2013 Jaspersoft Corporation. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports 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. * * JasperReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.crosstabs; import net.sf.jasperreports.crosstabs.type.CrosstabColumnPositionEnum; /** * Crosstab column group interface. * * @author Lucian Chirita (lucianc@users.sourceforge.net) * @version $Id: JRCrosstabColumnGroup.java 5960 2013-03-07 14:54:18Z lucianc $ */ public interface JRCrosstabColumnGroup extends JRCrosstabGroup { /** * Returns the height of the group headers. * * @return the height of the group headers * @see JRCrosstabGroup#getHeader() * @see JRCrosstabGroup#getTotalHeader() */ public int getHeight(); /** * Returns the position of the header contents for header stretching. * <p> * The column group headers stretch horizontally when there are multiple sub group entries. * The header contents will be adjusted to the new width depending on this attribute: * <ul> * <li>{@link CrosstabColumnPositionEnum#LEFT CrosstabColumnPositionEnum.LEFT} - the contents will be rendered on the left side of the header</li> * <li>{@link CrosstabColumnPositionEnum#CENTER CrosstabColumnPositionEnum.CENTER} - the contents will be rendered on the center of the header</li> * <li>{@link CrosstabColumnPositionEnum#RIGHT CrosstabColumnPositionEnum.RIGHT} - the contents will be rendered on the right side of the header</li> * <li>{@link CrosstabColumnPositionEnum#STRETCH CrosstabColumnPositionEnum.STRETCH} - the contents will be proportionally stretched to the new header size</li> * </ul> * * @return the position of the header contents for header stretching */ public CrosstabColumnPositionEnum getPositionValue(); /** * Returns the crosstab header cell of the column group. * * <p> * The cell will be rendered at the left of the corresponding row of column headers, * potentially overlapping {@link JRCrosstab#getHeaderCell() the crosstab header cell}. * </p> * * <p> * The width of the cell is the total width of row group headers, * and the height is the height of the corresponding column header. * </p> * * @return the crosstab header cell of the column group, or <code>null</code> if no header cell is present * * @see JRCrosstab#getHeaderCell() * @see #getHeight() */ public JRCellContents getCrosstabHeader(); }
sikachu/jasperreports
src/net/sf/jasperreports/crosstabs/JRCrosstabColumnGroup.java
Java
lgpl-3.0
3,249
#include "hough-recog.h" #include <math.h> #include <stdlib.h> #define SQUARE(x) ((x) * (x)) #define RADIAN(angle, pi) ((float)(angle) * pi / 180) #define MAX_ANGLE 90 #define ANGLE_STEP 45 #define EPS 0.0001 #define DIAG_LENGTH(width , height) (round(sqrt(((width) - 1) * ((width) - 1) +\ ((height) - 1) * ((height) - 1)))) #define MAX_DISTANCE(diag) (round(sqrt(2) * (diag))) #define THRESHOLD 100 #define DIST_DIFF_THRESHOLD 50 #define DIAG_ANGLE 45 #define N_OF_MAX 7 int* accum_matrix_from_image_with_length(const GdkPixbuf *image, int *matrix_width, int *matrix_height) { int *matrix, width, height; int rowstride, channels, diag; guchar *pixels; int max_distance, min_distance; int max_angle, min_angle, index; int matrix_size, matr_width, matr_height; width = gdk_pixbuf_get_width(image); height = gdk_pixbuf_get_height(image); rowstride = gdk_pixbuf_get_rowstride(image); channels = gdk_pixbuf_get_n_channels(image); pixels = gdk_pixbuf_get_pixels(image); diag = round(sqrt(SQUARE(width - 1) + SQUARE(height - 1))); // diag2 = DIAG_LENGTH(width, height); // if(diag != diag2) // g_print("bad"); max_distance = MAX_DISTANCE(diag); min_distance = -max_distance; max_angle = MAX_ANGLE; min_angle = -max_angle; matr_width = max_distance * 2 + 1; //matr_height = (max_angle * 2) / ANGLE_STEP + 1; matr_height = (max_angle * 2) / ANGLE_STEP; matrix_size = matr_width * matr_height; matrix = calloc(matrix_size, sizeof (int)); for(int i = 0; i < height; ++i) for(int j = 0; j < width; ++j) { index = i * rowstride + j * channels; if(pixels[index] != 0) continue; for(int angle = min_angle; angle < max_angle/*angle <= max_angle*/; angle+= ANGLE_STEP) { float phi = RADIAN(angle, M_PI); float distance = i * sin(phi) + j * cos(phi); if(distance >= min_distance && distance <= max_distance) { index = (angle + max_angle) / ANGLE_STEP * matr_width + (distance + max_distance); matrix[index]++; } } } *matrix_width = matr_width; *matrix_height = matr_height; return matrix; } typedef struct slist_value { int points; int dist; } sl_value; typedef struct dist_flag_pair { int dist; int flag; } df_pair; static int contains_line (GSList *list, int dist) { GSList *iter; sl_value *value; for(iter = list; iter != NULL; iter = iter->next) { value = (sl_value*)iter->data; if(abs(value->dist - dist) < DIST_DIFF_THRESHOLD) return 1; } return 0; } static void free_htable_elems(gpointer elem) { g_slist_free_full((GSList*)elem, free); } GHashTable* filter_accum_matrix(const int *matrix, int width, int height) { GHashTable *table; int matr_size; int angle, dist; int n_of_points; /* TODO: добавить функцию очистки памяти */ table = g_hash_table_new_full(g_direct_hash, g_direct_equal, NULL, NULL); matr_size = width * height; for(int i = 0; i < matr_size; ++i) { n_of_points = matrix[i]; if(n_of_points > THRESHOLD) { GSList *lines = NULL; sl_value *new_line; angle = (i / width) * ANGLE_STEP - MAX_ANGLE; dist = abs((i % width) - (width - 1) / 2); lines = (GSList*)g_hash_table_lookup(table, GINT_TO_POINTER(angle)); if(!contains_line(lines, dist)) { new_line = malloc(sizeof(sl_value)); new_line->dist = dist; new_line->points = n_of_points; lines = g_slist_prepend(lines, new_line); g_hash_table_insert(table, GINT_TO_POINTER(angle), lines); } } } return table; } static void count_lines (gpointer key, gpointer value, gpointer user_data) { GSList *val; int *sum; val = (GSList*)value; sum = (int*)user_data; *sum += g_slist_length(val); } static void check_diag (gpointer key, gpointer value, gpointer user_data) { int angle; int *is_diag; angle = GPOINTER_TO_INT(key); is_diag = (int*)user_data; if(!(*is_diag)) *is_diag = abs(angle) == DIAG_ANGLE; } static void count_diags (gpointer key, gpointer value, gpointer user_data) { int angle; GSList *lines; int *diags; angle = GPOINTER_TO_INT(key); lines = (GSList*)value; diags = (int*)user_data; if(abs(angle) == DIAG_ANGLE) *diags += g_slist_length(lines); } static void get_first_diag_dist (gpointer key, gpointer value, gpointer user_data) { int angle; GSList *lines; sl_value *line; int *dist; angle = GPOINTER_TO_INT(key); lines = (GSList*)value; dist = (int*)user_data; if(abs(angle) == DIAG_ANGLE) if(lines != NULL) { line = (sl_value*)lines->data; *dist = line->dist; } } typedef struct angle_sum_pair { int angle; int sum; } as_pair; static void count_points_by_angle (gpointer key, gpointer value, gpointer user_data) { int angle; GSList *lines, *iter; sl_value *line; as_pair *pair; angle = GPOINTER_TO_INT(key); lines = (GSList*)value; pair = (as_pair*)user_data; if(abs(angle) == pair->angle) { for(iter = lines; iter; iter = iter->next) { line = (sl_value*)iter->data; pair->sum += line->points; } } } int identify_number(GdkPixbuf *image, GHashTable *table) { int n_of_lines, n_of_diags; int has_diag, img_width, img_height; int img_diag_length; int first_diag_line_dist; #define FOREACH(seq, func, acc)\ {\ acc = 0;\ g_hash_table_foreach(seq, func, &acc);\ } img_width = gdk_pixbuf_get_width(image); img_height = gdk_pixbuf_get_height(image); img_diag_length = DIAG_LENGTH(img_width, img_height); FOREACH(table, count_lines, n_of_lines); switch (n_of_lines) { case 2: return 1; case 3: { FOREACH(table, check_diag, has_diag); if(has_diag) return 7; else return 4; } case 4: { FOREACH(table, check_diag, has_diag); if(has_diag) { FOREACH(table, count_diags, n_of_diags); if(n_of_diags == 2) return 3; else return 2; } else return 0; } case 5: { FOREACH(table, check_diag, has_diag); if(has_diag) { FOREACH(table, get_first_diag_dist, first_diag_line_dist); if(first_diag_line_dist < img_diag_length / 2) return 6; else return 9; } else { as_pair pair; pair.angle = 0; pair.sum = 0; g_hash_table_foreach(table, count_points_by_angle, &pair); if((pair.sum - img_height) < (img_height / 2)) return 5; else return 8; } } default: break; } return -1; }
voyagerok/hough-recognition
src/hough-recog.c
C
lgpl-3.0
7,443
class Organization < ActiveRecord::Base acts_as_nested_set has_many :kits end
Skookum-Nightshift/kit-starter
app/models/organization.rb
Ruby
lgpl-3.0
82
package io.github.reggert.reb4j.test import org.scalacheck.{Arbitrary, Gen} import Arbitrary.arbitrary import io.github.reggert.reb4j.Adopted import java.util.regex.Pattern trait AdoptedGenerators { implicit val arbAdopted: Arbitrary[Adopted] = Arbitrary(Gen.sized { size => if (size < 1) Gen.fail else Gen.choose(1, size) flatMap genAdopted }) // This generator only generates patterns for quoted strings private def genPattern(size : Int) : Gen[Pattern] = for { s <- Gen.listOfN(size, arbitrary[Char]) } yield Pattern.compile(Pattern.quote(s.mkString)) def genAdopted(size : Int) : Gen[Adopted] = for { p <- genPattern(size) } yield Adopted.fromPattern(p) }
reggert/reb4j
src/test/scala/io/github/reggert/reb4j/test/AdoptedGenerators.scala
Scala
lgpl-3.0
680
#ifndef _XFUNCTIONS_H #define _XFUNCTIONS_H #include <stdio.h> #include <strings.h> #include <stdlib.h> #include <errno.h> #include <setjmp.h> #ifdef __GNUC__ #define no_return __attribute__ ((noreturn)) #else #define no_return #endif void * xmalloc(size_t size); void * xcalloc(size_t nelem, size_t elsize); char * xstrdup(const char * str); FILE * xfopen(const char *pathname, const char *type); int yfclose(FILE * stream); int yfflush(FILE * stream); long xatol(const char *str); int xatoi(const char *str); unsigned long xatoul(const char *str); unsigned int xatoui(const char *str); double xatof(const char *str); long yatol(const char *str); int yatoi(const char *str); unsigned long yatoul(const char *str); unsigned int yatoui(const char *str); double yatof(const char *str); bool xatob(const char * str); bool yatob(const char * str); void xexit(int exitCode) no_return; // The program should define xexit somewhere, i.e. // void xexit(int exitCode) { exit(exitCode); } // #endif /* _XFUNCTIONS_H */
ibukanov/ahome
writes/bergen_master_thesis/prog/src/xfunctions.h
C
unlicense
1,028
<?php /** * This module was built specifically with Danish volleyball leagues in mind, * but the abstraction should be distant enough to allow for practically any * sport that has a generic tournament structure, different leagues (or series, * or .... you know), players, coaches and a team description. * * @author Johannes L. Borresen * @website http://the.homestead.dk * @package sports **/ require_once('admin_base.php'); /** * Admin controller for seasons. * @package sports * @subpackage seasons */ class Admin_Seasons extends Admin_SportsBase { /** * Used by the PyroCMS admin code to match shortcuts in details.php to * controllers' admin views. */ protected $section = 'seasons'; /** * Basic controller constructor. Pulls in models, validation rules, assets. * @return ? */ public function __construct() { parent::__construct(); // Load the required classes $this->load->model(array( 'season_m', 'membership_m', )); $this->load->library(array( 'calendar', )); // Set the validation rules $this->item_validation_rules = array( array( 'field' => 'name', 'label' => 'sports:name', 'rules' => 'trim|max_length[50]|required|is_unique[sports_teams.name'), ); // We'll set the partials and metadata here since they're used everywhere $this->template->append_js('module::admin.js') ->append_css('module::admin.css'); } /** * Displays all seasons in a small, convenient list. They can be created, * edited and deleted from here. * @param int $offset Pagination offset. * @todo Check if this is even accessible. If it is, implement pagination, * too. */ public function index($offset = 0) { // Build the view with sample/views/admin/items.php $this->data->seasons =& $this->season_m->get_all(); $this->template->title($this->module_details['name']) ->build('admin/seasons', $this->data); } /** * Displays create/edit view for seasons and parses the create submissions. * Redirects back to seasons admin overview on success. * @return ? */ public function create() { // Secure values. $this->form_validation->set_rules($this->item_validation_rules); // Did the form submit correctly? if ($this->form_validation->run()) { if ($this->season_m->create($this->input->post())) { $this->session->set_flashdata('success', lang('success_label')); redirect('admin/sports/seasons'); } else { $this->session->set_flashdata('error', lang('general_error_label')); redirect('admin/sports/seasons/create'); } } // Assuming validation failed, foreach ($this->item_validation_rules as $rule) { $this->data->{$rule['field']} = $this->input->post($rule['field']); } // Build, or rebuild, view. $this->template->title($this->module_details['name'], lang('global:add')) ->build('admin/seasons_create', $this->data); } /** * Edit single season. Renders view and treats submission. * Redireects to admin season overview on success. * @param int $id Season id to edit. * @return ? */ public function edit($id) { $this->data = $this->season_m->get($id); $this->form_validation->set_rules($this->item_validation_rules); // check if the form validation passed if($this->form_validation->run()) { // get rid of the btnAction item that tells us which button was clicked. // If we don't unset it MY_Model will try to insert it unset($_POST['btnAction']); // See if the model can create the record if($this->season_m->update($id, $this->input->post())) { // All good... $this->session->set_flashdata('success', lang('success_label')); redirect('admin/sports/seasons'); } // Something went wrong. Show them an error else { $this->session->set_flashdata('error', lang('general_error_label')); redirect('admin/sports/seasons/create'); } } // Build the view using sports/views/admin/team_create $this->template->title($this->module_details['name'], lang('global:add')) ->build('admin/seasons_create', $this->data); } }
Tellus/pyro-sports
controllers/admin_seasons.php
PHP
unlicense
4,719
# Into compose make sure that you add and entry to your `/etc/hosts` file for `docker.localhost`: ``` 127.0.0.1 localhost localunixsocket.local localunixsocket docker.localhost ``` 1. clean up from before: ``` # check what's there docker ps -a # remove old containers docker container prune # check again! docker ps ``` 2. Build Arguments ``` docker build -t cop2/nginx . docker build -t cop2/nginx-blue --build-arg COLOR=blue . docker run --rm -p 8080:80 cop2/nginx # detour image clean up docker images docker image prune docker images # docker compose! docker-compose build docker-compose up -d docker-compose ps # checkout the proxy page # http://docker.localhost:8080/dashboard/#/ # and the service: # http://color.docker.localhost:8888/ # refresh a couple of times to see the load balancing work # let's scale red docker-compose scale red=4 docker-compose ps #clean up docker-compose stop docker-compose rm docker network prune ```
healthbridgeltd/zava-cop
docker/2/README.md
Markdown
unlicense
1,067
Snake grid fill toy. See: http://www.reddit.com/r/dailyprogrammer/comments/1eyipq/052413_challenge_123_hard_snakefill/
skeeto/snake-fill-js
README.md
Markdown
unlicense
120
package Chap03; /* * ÀÛ¼ºÀÏÀÚ:2017_03_07 * ÀÛ¼ºÀÚ:±æ°æ¿Ï * booelean ŸÀÔÀÇ º¯¼ö¸¦ ¼±¾ðÇØ¼­ »ç¿ëÇÏ´Â ¿¹¸¦ º¸¿©ÁÖ´Â ÇÁ·Î±×·¥ * ¿¹Á¦ 3-1 */ public class BooleanExample1 { public static void main(String[] args){ int num=10+20; boolean trueth; trueth = num>10; if (trueth) System.out.println("numÀÌ 10º¸´Ù Å­"); } }
WALDOISCOMING/Java_Study
Java_BP/src/Chap03/BooleanExample1.java
Java
unlicense
347
A non exhaustive list of bots, tools, news and mirrors account on the Fediverse to get you started.
ialisme/fed.ialis.me
_i18n/en/directory/content.md
Markdown
unlicense
101
package mytown.proxies; import mytown.MyTown; import mytown.config.Config; import myessentials.economy.Economy; public class EconomyProxy { private static Economy economy = null; private EconomyProxy() { } public static void init() { economy = new Economy(Config.costItemName); MyTown.instance.LOG.info("Successfully initialized economy!"); } public static Economy getEconomy() { return economy; } public static boolean isItemEconomy() { if(Config.costItemName.equals(Economy.CURRENCY_FORGE_ESSENTIALS)) { return false; } else if(Config.costItemName.equals(Economy.CURRENCY_VAULT)) { return false; } return true; } /** * Returns a formatted currency string. For example: "32 Diamonds" or "15 $" */ public static String getCurrency(int amount) { String currency = economy.getCurrency(amount); if(Character.isDigit(currency.charAt(0)) || Character.isDigit(currency.charAt(currency.length() - 1))) return currency; else return amount + " " + currency; } }
blasterdude9/MyTown2
src/main/java/mytown/proxies/EconomyProxy.java
Java
unlicense
1,147
/* * Monte Carlo.cpp * * Copyright 2017 Benjamin Church <ben@U430> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_sf_hyperg.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_integration.h> #include <time.h> #define ADIABATIC_CUTOFF 1 #define INTEGRATION_POINTS 81 #define INTEGRAL_FUDGE_FACTOR 1.0125 #define INTEGRATION_SECTIONS 8 #define CUTOFF_SCALE 1E3 #define min(x,y) (x < y? x : y) #define sign(x) (x >= 0? 1.0 : -1.0) #define dot_macro(A, B) ((A).x * (B).x + (A).y * (B).y + (A).z * (B).z) #define mag_sq(A) dot_macro(A, A) #define mag(A) sqrt(dot_macro(A, A)) #define assign_vec(A, x_val, y_val, z_val) {(A).x = x_val; (A).y = y_val; (A).z = z_val;} #define assign_vec_diff(d, A, B) {(d).x = (A).x - (B).x; (d).y = (A).y - (B).y; (d).z = (A).z - (B).z;} #define make_unit(A) {double len = mag(A); assign_vec(A, (A.x)/len, (A.y)/len, (A.z)/len);} #define rho_profile(x, a, b) (pow(x, 2 - a)*pow((1 + x), a - b)) gsl_rng *RNG; gsl_integration_workspace * w; const int default_log_num_trials = 6; int num_trials, num_points = 100; const double pi = 3.14159265; double crit_density = 1.3211775E-7, f = 0.1, g = 1E-4, p = 1.9, G = 0.0045, k = 2, M_prim = 1E12, T_age = 1E4; double m_max, m_min, expected_num, R_core_prim, R_max_prim, c_prim; double MaxRadius(double M) { return pow(3.0*M/(4.0 * pi * 200.0 * crit_density), 1.0/3.0); } typedef struct { double x, y, z; } vector; typedef struct { double m, s, max_val; }data_cell; void update_cell(data_cell *ptr, double new_data, int k) { double old_m = ptr->m; ptr->m += (new_data - old_m)/(double) k; ptr->s += (new_data - old_m)*(new_data - ptr->m); if(ptr->max_val < new_data) ptr->max_val = new_data; } void reset_cell(data_cell *ptr) { ptr->m = 0; ptr->s = 0; ptr->max_val = 0; } typedef struct { double R, theta, phi; double cos_theta; double M, r_core, r_max, alpha, beta, c, normalization; double integs[INTEGRATION_SECTIONS]; vector v, position; } halo; double Power(double x, int y) { if(y > 0) { double result = 1; while(y > 0) { if(y % 2 == 0) { x = x*x; y = y/2; } else { result = x*result; y--; } } return result; } else if(y < 0) return 1/Power(x, -y); else return 1; } void print_vector(vector *A) { printf("(%.3f, %.3f, %.3f)\n", A->x, A->y, A->z); } double perp_mag_sq(vector *A, vector *u) { double dot_prod = dot_macro(*A, *u); return mag_sq(*A) - dot_prod*dot_prod/mag_sq(*u); } double MFreeNFW(double r) { if(r < R_max_prim) return M_prim*(log(1 + r/R_core_prim)-r/(r + R_core_prim))/(log(1 + c_prim) - c_prim/( 1 + c_prim)); else return M_prim; } double DFreeNFW(double r) { if(r < R_max_prim) return 200.0/3.0 * crit_density / (log(1 + c_prim) - c_prim/(1 + c_prim))*pow(c_prim, 3) * 1.0/(r/R_core_prim*pow(1+r/R_core_prim, 2.0)); else return 0.0; } double PhiFreeNFW(double r) { if(r < R_max_prim) return -M_prim*G*((R_max_prim/r * log(1 + r/R_core_prim) - log(1 + c_prim))/(log(1 + c_prim) - c_prim/(1 + c_prim)) + 1)/R_max_prim; else return -M_prim*G/r; } double TidalRadius(double M, double R) { return R*pow(M/(2*MFreeNFW(R)), 1.0/3.0); } double NFW_func(double x, double r) { return (log(1.0 + x) - x/(1.0 + x))/(log(1.0 + c_prim) - c_prim/(1.0 + c_prim)) - r; } double df (double x) { return x/((1.0 + x)*(1.0 + x)) * 1.0/(log(1.0 + c_prim) - c_prim/(1.0 + c_prim)); } double newton(double r) { int itr, maxmitr = 100; double h, x0 = 0.1, x1, allerr = pow(10, -6); for (itr = 0; itr < maxmitr; itr++) { h = NFW_func(x0, r)/df(x0); x1 = x0 - h; if (fabs(h) < allerr) { return x1; } x0 = x1; } return x1; } double rho_profile_func(double x, void *params) { double *param_ptr = (double *)params; return pow(x, 2 - param_ptr[0])*pow((1 + x), param_ptr[0] - param_ptr[1]); } double integ_profile(double alpha, double beta, double r) { /*if(alpha > 3) return 1; double dist = 0, step = r/INTEGRATION_POINTS, sum = 0; int i; for(i = 0; i < INTEGRATION_POINTS; i++) { if(i == 0 && alpha > 2 && alpha < 3) sum += 8.0/(3.0*step) * 1/(3.0 - alpha) * pow(step, 3 - alpha); else if(i == 0 || i == INTEGRATION_POINTS - 1) sum += rho_profile(dist, alpha, beta); else if(i%3 == 0) sum += 2*rho_profile(dist, alpha, beta); else sum += 3*rho_profile(dist, alpha, beta); dist += step; } return 3.0*step/8.0*sum * INTEGRAL_FUDGE_FACTOR;*/ //printf("int %f\n", 3*step/8*sum); double result, error; double arr[2]; arr[0] = alpha; arr[1] = beta; gsl_function F; F.function = &rho_profile_func; F.params = arr; gsl_integration_qags (&F, 0, r, 0, 1e-7, 1000, w, &result, &error); if(error/result > 1e-7)printf("LARGE INTEG ERROR WARNING %f for result %f", error, result); //printf("alpha: %.3f beta: %.3f r: %.3f err %f\n", alpha, beta, r, (result - quick_result)/result); return result; } double worst_thing_ever(int lr, double a, double b, double r) { switch(lr) { case -2: return pow(2,-2 + b)*pow(3,-4 + a - b)*(-20.25 - ((8*a*a*a + 12*a*a*(-2 + b) + b*(38 + (-15 + b)*b) + 2*a*(8 + 3*(-7 + b)*b))*(-0.0078125 + Power(1 - 2*r,4)/8.))/2. + 81*r - 27*(-6 + 2*a + b)*(0.1875 + (-1 + r)*r) + (3*(4*a*a + 4*a*(-4 + b) + (-9 + b)*(-2 + b))*(-1 + 4*r)*(7 + 4*r*(-5 + 4*r)))/32.); break; case -1: return (pow(2,-4 + a - b)*(-24 + 48*r - ((-2 + a + b)*(a*a + (-7 + b)*b + a*(-1 + 2*b))*(-3 + 2*r)*(-1 + 2*r)*(5 + 4*(-2 + r)*r))/64. - 3*(-4 + a + b)*(3 - 8*r + 4*r*r) + 6*(8 + a*a - 7*b + b*b + a*(-5 + 2*b))*(-0.2916666666666667 + (r*(3 + (-3 + r)*r))/3.)))/3.0; break; case 0: return pow(2,-4 - a)*pow(3,-4 + a - b)*(-(a*a*a*(-1 + Power(-2 + r,4))) - 16*(27 + (3*b)/4. + (b*b*b*(-1 + Power(-2 + r,4)))/2. + 40*b*r - 48*b*r*r - 27*r*r*r + 4*b*r*r*r + (13*b*r*r*r*r)/4. - 3*b*b*(1 + Power(-2 + r,3)*r)) - 3*a*a*(-1 + r)*(-41 + 2*b*(-3 + r)*(5 + (-4 + r)*r) - r*(-23 + r + r*r)) - 2*a*(-1 + r)*(-75 + 6*b*b*(-3 + r)*(5 + (-4 + r)*r) + r*(-187 + r*(77 + r)) - 3*b*(37 + r*(5 + r*(-19 + 5*r))))); break; case 1: return -(pow(2,-5 - 2*a)*pow(5,-3 + a - b)*(-2 + r)*(a*a*a*(-120 + 68*r - 14*r*r + r*r*r) + a*a*(-1880 + 596*r - 38*r*r - 3*r*r*r + 12*b*(-120 + 68*r - 14*r*r + r*r*r)) + 2*a*(-2200 - 1932*r + 426*r*r + r*r*r + b*(-3920 + 344*r + 268*r*r - 42*r*r*r) + 24*b*b*(-120 + 68*r - 14*r*r + r*r*r)) + 8*(-500*(4 + 2*r + r*r) + 8*b*b*b*(-120 + 68*r - 14*r*r + r*r*r) - 4*b*b*(40 + 212*r - 86*r*r + 9*r*r*r) + b*(-200 - 1892*r + 206*r*r + 31*r*r*r))))/3.0; break; case 2: return pow(2,-4 - 3*a)*pow(3,-7 + 2*a - 2*b)*(-8957952 - ((-2 + a)*(-1 + a)*a + 8*(182 + 3*(-11 + a)*a)*b + 192*(-10 + a)*b*b + 512*b*b*b)* (-64 + Power(-8 + r,4)/4.) + 2239488*r - 15552*(-18 + a + 8*b)*(48 - 16*r + r*r) + 72*(162 + a*a - 224*b + 64*b*b + a*(-19 + 16*b))*(-448 + r*(192 + (-24 + r)*r))); break; case 3: return (pow(2,-5 - 4*a)*pow(17,-3 + a - b)*(-965935104 - (a*a*a + a*a*(-3 + 48*b) + 32*b*(307 - 432*b + 128*b*b) + a*(2 - 912*b + 768*b*b))* (-1024 + Power(-16 + r,4)/4.) + 120741888*r - 221952*(-34 + a + 16*b)*(192 - 32*r + r*r) + 272*(578 + a*a - 832*b + 256*b*b + a*(-35 + 32*b))*(-3584 + r*(768 + (-48 + r)*r))))/3.0; break; case 4: return pow(2,-6 - 5*a)*pow(33,-4 + a - b)*11*(-113048027136 - (a*a*a + a*a*(-3 + 96*b) + 64*b*(1123 - 1632*b + 512*b*b) + a*(2 - 3360*b + 3072*b*b))*(-16384 + Power(-32 + r,4)/4.) + 7065501696*r - 3345408*(-66 + a + 32*b)*(768 - 64*r + r*r) + 1056*(2178 + a*a - 3200*b + 1024*b*b + a*(-67 + 64*b))*(-28672 + r*(3072 + (-96 + r)*r))); break; case 5: return (pow(2,-7 - 6*a)*pow(65,-3 + a - b)* (-13822328832000 + 431947776000*r - (((-2 + a)*(-1 + a)*a + 64*(8582 + 3*(-67 + a)*a)*b + 12288*(-66 + a)*b*b + 262144*b*b*b)*(-96 + r)*(-32 + r)* (5120 + (-128 + r)*r))/4. - 51916800*(-130 + a + 64*b)*(3072 - 128*r + r*r) + 4160*(8450 + a*a - 12544*b + 4096*b*b + a*(-131 + 128*b))* (-229376 + r*(12288 + (-192 + r)*r))))/3.0; break; }; return 1; } double sec_integ_profile(halo *ptr, double r) { double a = ptr->alpha, b = ptr->beta; int lr = floor(log2(r)); //MAKE BETTER! if(lr < -2) return pow(r, 3-a)*(1/(3-a) + r*(a-b)/(4-a) + (a*a - a + b - 2*a*b + b*b)/(5-a)*r*r/2.0); if(lr >= INTEGRATION_SECTIONS - 2) return integ_profile(a, b, r); //MAKE BETTER return ptr->integs[lr + 2] + worst_thing_ever(lr, a, b, r); } double get_M() { double r = gsl_rng_uniform(RNG); return M_prim*pow(pow(m_max/M_prim, 1.0-p)*r + pow(m_min/M_prim, 1.0-p)*(1.0-r), 1.0/(1.0-p)); } double c_bar(double M) { return pow(10.0, 1.0 - 0.1 * (log10(M) - 12)); } void set_shape(halo *ptr, double M, double R) { ptr->r_max = pow(3*M/(4 * pi * 200.0 * crit_density), 1.0/3.0); ptr->alpha = gsl_ran_gaussian_ziggurat(RNG, 0.2) + 1.25; //suggested by J. Ostriker ptr->beta = 3; //probalby need to change ptr->c = gsl_ran_lognormal(RNG, log(c_bar(M)), 0.25); //Ludlow el. al. (2013) and Frank van den Bosch ptr->r_core = ptr->r_max/ptr->c; int i; double r = 1.0/4.0, a = ptr->alpha, b = ptr->beta; ptr->integs[0] = pow(r, 3-a)*(1/(3-a) + r*(a-b)/(4-a) + (a*a - a + b - 2*a*b + b*b)/(5-a)*r*r/2.0); r *= 2; for(i = 0; i < INTEGRATION_SECTIONS - 1; i++) { ptr->integs[i + 1] = ptr->integs[i] + worst_thing_ever(i - 2, ptr->alpha, ptr->beta, r); r *= 2; } ptr->normalization = sec_integ_profile(ptr, ptr->c); } void set_velocity(halo *ptr, double R) { double v_sigma = sqrt(1.0/3.0)*sqrt(-PhiFreeNFW(R)); ptr->v.x = gsl_ran_gaussian_ziggurat(RNG, v_sigma); ptr->v.y = gsl_ran_gaussian_ziggurat(RNG, v_sigma); ptr->v.z = gsl_ran_gaussian_ziggurat(RNG, v_sigma); } double enclosed_mass(halo *ptr, double r) { double x = r/(ptr->r_core); if(x > ptr->c) return ptr->M; else { /* double sec = sec_integ_profile(ptr, x), integ = integ_profile(ptr->alpha, ptr->beta, x); double lerr = log(fabs(sec - integ)); if(lerr > -4) { printf("alpha: %f beta: %f r: %f \n", ptr->alpha, ptr->beta, x); printf("lerr: %f sec: %f real: %f r: \n", lerr, sec, integ); }*/ return ptr->M * sec_integ_profile(ptr, x)/ptr->normalization; } } void truncate(halo *ptr, double R) { double l2 = R*R*perp_mag_sq(&(ptr->v), &(ptr->position)); double r0 = l2/(M_prim * G); double E = 0.5*mag_sq(ptr->v) + PhiFreeNFW(R); double ecc = sqrt(1.0 + 2.0*E*l2/(M_prim * G * M_prim * G)); double R_min = min(fabs(r0/(1.0 + ecc)), fabs(r0/(1.0 - ecc))); /*printf("velocity: "); print_vector(ptr->v); printf("position "); print_vector(halo_pos(ptr)); printf("R = %.3f theta = %.3f phi = %.3f\n l2 = %.3f e = %.3f \n", ptr->R, ptr->theta, ptr->phi, l2, ecc);*/ if(E > 0 || R_min < 0.1) { ptr->M = 0; } else { double Rt = TidalRadius(ptr->M, R_min); double R_max = min(ptr->r_max, Rt); double new_M = enclosed_mass(ptr, R_max); ptr->r_max = R_max; ptr->c = R_max/ptr->r_core; ptr->normalization *= (new_M/ptr->M); ptr->M = new_M; } } halo *make_halo(halo *ptr) { ptr->R = newton(gsl_rng_uniform(RNG)) * R_core_prim; ptr->cos_theta = 2*gsl_rng_uniform(RNG) - 1; ptr->theta = acos(ptr->cos_theta); ptr->phi = 2*pi*gsl_rng_uniform(RNG); assign_vec(ptr->position, ptr->R * sin(ptr->theta) * cos(ptr->phi), ptr->R * sin(ptr->theta) * sin(ptr->phi), ptr->R * ptr->cos_theta); ptr->M = get_M(); set_shape(ptr, ptr->M, ptr->R); set_velocity(ptr, ptr->R); truncate(ptr, ptr->R); return ptr; } void print_halo_basic(halo *ptr) { printf("\n R = %3f \n theta = %3f \n M = %3f \n", ptr->R, ptr->theta, ptr->M); } double Fluc(halo *halos, int num_halos, double D) { double sum = 0; int i; vector my_pos = {0, 0, D}, diff; double natural_fluc = 2 * pi* pow(D, 3.0/2.0)/sqrt(MFreeNFW(D) * G) * 1/(PhiFreeNFW(D)); for(i = 0; i < num_halos; i++) { double R = halos[i].R; double r = sqrt(R*R + D*D - 2.0*R*D*halos[i].cos_theta); assign_vec_diff(diff, halos[i].position, my_pos); make_unit(diff) double v_r = dot_macro(halos[i].v, diff); double produced_fluc = ((r > CUTOFF_SCALE) ? (enclosed_mass(halos + i, r) * G /(r*r) * v_r) : 0); //sum += produced_fluc; //KILLEM // kill heating which is adiabtic if(produced_fluc/natural_fluc > 1 || ! ADIABATIC_CUTOFF) sum += produced_fluc; /*printf("%.3f\n", D); printf("velocity: "); print_vector(halos[i]->v); printf("position "); print_vector(halo_pos(halos[i])); printf("R = %.3f theta = %.3f phi = %.3f\n v_r = %.3f \n", halos[i]->R, halos[i]->theta, halos[i]->phi, v_r);*/ } return sum*sum; } double Fluc_mass_range(halo *halos, int num_halos, double D, double min_mass, double max_mass) { double sum = 0; int i; vector my_pos = {0, 0, D}, diff; double natural_fluc = 2 * pi* pow(D, 3.0/2.0)/sqrt(MFreeNFW(D) * G) * 1/(PhiFreeNFW(D)); for(i = 0; i < num_halos; i++) { double R = halos[i].R; double r = sqrt(R*R + D*D - 2.0*R*D*halos[i].cos_theta); if(halos[i].M < max_mass && halos[i].M > min_mass) { assign_vec_diff(diff, halos[i].position, my_pos); make_unit(diff) double v_r = dot_macro(halos[i].v, diff); double produced_fluc = ((r > CUTOFF_SCALE) ? (enclosed_mass(halos + i, r) * G /(r*r) * v_r) : 0); //sum += produced_fluc; //KILLEM // kill heating which is adiabtic if(produced_fluc/natural_fluc > 1 || ! ADIABATIC_CUTOFF) sum += produced_fluc; /*printf("%.3f\n", D); printf("velocity: "); print_vector(halos[i]->v); printf("position "); print_vector(halo_pos(halos[i])); printf("R = %.3f theta = %.3f phi = %.3f\n v_r = %.3f \n", halos[i]->R, halos[i]->theta, halos[i]->phi, v_r);*/ } } return sum*sum; } double H_Density(halo *halos, int num_halos, double D, double dD) { double sum = 0; int i; for(i = 0; i < num_halos; i++) { if(halos[i].R < D && halos[i].R > D - dD) sum += halos[i].M; } return sum/(4.0*pi*D*D*dD); } int print_out = 0; void init(int argc, char **argv) { const gsl_rng_type *T; gsl_rng_env_setup(); T = gsl_rng_default; RNG = gsl_rng_alloc (T); w = gsl_integration_workspace_alloc (1000); if(argc >= 2) num_trials = (int)pow(10, atoi(argv[1])); else num_trials = (int)pow(10, default_log_num_trials); if(argc > 2) print_out = 1; R_max_prim = MaxRadius(M_prim); c_prim = c_bar(M_prim); R_core_prim = R_max_prim/c_prim; m_max = f*M_prim; m_min = g*M_prim; expected_num = (2.0-p)/(1.0-p)*f*(pow(m_max/M_prim, 1.0-p) - pow(m_min/M_prim, 1.0-p)) / (pow(m_max/M_prim, 2.0-p) - pow(m_min/M_prim, 2.0-p)); } double std_err_mean(double sum_of_squares) { return sqrt(sum_of_squares/((double) num_trials*(num_trials - 1))); } void sq_root_data(data_cell *data, int num) { int i; for(i = 0; i < num; i++) { data[i].m = sqrt(data[i].m); data[i].s *= pow(1.0/(2.0*data[i].m), 2); data[i].max_val = sqrt(data[i].max_val); } } void print_to_file(char *name, double *Ds, data_cell *data) { int j; char path[100], filename[50], snum[10], addendum[10]; strcpy(path, "data_files/"); strcpy(filename, name); strcpy(addendum, ".txt"); snprintf(snum, 10, "%d_%d", (int)gsl_rng_default_seed, (int)log10(num_trials)); strcat(path, filename); strcat(path, snum); strcat(path, addendum); FILE *f = NULL; if(!print_out) f = fopen(path, "w"); if(!print_out && f != NULL) { for(j = 0; j < num_points; j++) { double sig = std_err_mean(data[j].s)/data[j].m/log(10); printf("%f, %f, %f, %f\n", data[j].m, data[j].s, sig, log10(data[j].m)); if(data[j].m > 0) fprintf(f, "%f %f %f %f\n", log10(Ds[j]), log10(data[j].m), sig, log10(data[j].max_val)); } fclose(f); } else { for(j = 0; j < num_points; j++) { double sig = std_err_mean(data[j].s)/data[j].m/log(10); printf("%f, %f, %f, %f\n", data[j].m, data[j].s, sig, log10(data[j].m)); if(data[j].m > 0) printf("%f : %f +/- %f\n", log10(Ds[j]), log10(data[j].m), sig); } } } int main(int argc, char **argv) { init(argc, argv); unsigned int max_allowed_halos = (int)(10*expected_num); double Ds[num_points]; data_cell Flucs[num_points], Dens[num_points]; halo *halolist = malloc(max_allowed_halos*sizeof(halo)); double mass = 0, avg_mass = 0; int i,j; for(i = 0; i < num_points; i++) { Ds[i] = pow(10, 5.0*i/(double) num_points); reset_cell(&Flucs[i]); reset_cell(&Dens[i]); } int hist_num = 10; data_cell Hist_Flucs[hist_num]; for(int i = 0; i < hist_num; i++) reset_cell(Hist_Flucs + i); for(i = 0; i < num_trials; i++) { if(i % 100 == 0)printf("%d out of %d \n", i/100, num_trials/100); unsigned int num_halos = gsl_ran_poisson(RNG, expected_num); if(num_halos > max_allowed_halos) { max_allowed_halos *= 2; free(halolist); halolist = malloc(max_allowed_halos*sizeof(halo)); printf("ALLOCATING\n"); } mass = 0; //printf("Expect: %f Have: %lu \n", expected_num, num_halos); for(j = 0; j < num_halos; j++) { make_halo(halolist + j); //print_halo_basic(halolist + j); mass += halolist[j].M; if(mass != mass) { print_halo_basic(halolist + j); printf("%f %f %d %f\n", mass, halolist[j].M, j, halolist[j].alpha); return -1; } } for(j = 0; j < num_points; j++) { update_cell(Flucs + j, Fluc(halolist, num_halos, Ds[j]), i + 1); update_cell(Dens + j, (j == 0 ? H_Density(halolist, num_halos, Ds[j], Ds[j]) : H_Density(halolist, num_halos, Ds[j], Ds[j] - Ds[j-1])), i + 1); } //printf("Mass frac: %f \n", mass/M_prim); avg_mass += mass/num_trials; for(int j = 0; j < hist_num; j++) update_cell(Hist_Flucs + j, Fluc_mass_range(halolist, num_halos, 1e4, M_prim*g*pow(f/g, (double) j/ (double) hist_num), M_prim*g*pow(f/g, (double) (j + 1)/ (double) hist_num)), i + 1); /*for(j = 0; j < num_points; j++) { //printf("%f : %f\n", pow(10, 5.0*j/num_points), log10(Flucs[j])); //printf("%f : %f\n", pow(10, 5.0*j/num_points), log10(Dens[j])); //printf("%f : %f\n", pow(10, 5.0*j/num_points), Hist[j]); }*/ } print_to_file("Density", Ds, Dens); sq_root_data(Flucs, num_points); print_to_file("Flucs", Ds, Flucs); printf("Mass frac: %f \n", avg_mass/M_prim); sq_root_data(Hist_Flucs, hist_num); for(int i = 0; i < hist_num; i++) printf("Mass: %f Fluc: %f SDEV: %f\n", M_prim*g*pow(f/g, (double) i/ (double) hist_num), Hist_Flucs[i].m, std_err_mean(Hist_Flucs[i].s)); gsl_rng_free (RNG); gsl_integration_workspace_free (w); return 0; }
benvchurch/project-eva
Monte_Carlo/Monte_Carlo.c
C
unlicense
19,228
//$Id$ package org.hibernate.ejb.test.cascade; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * @author Emmanuel Bernard */ @Entity public class Author { @Id @GeneratedValue private Long id; }
codeApeFromChina/resource
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/project/hibernate-entitymanager/src/test/java/org/hibernate/ejb/test/cascade/Author.java
Java
unlicense
276
.error { color: red; padding: 10px; text-align: center; } .lista-artigiani { border-top: 1px solid #eee; -webkit-transition: all .3s cubic-bezier(.1, .8, .9, 1); -moz-transition: all .3s cubic-bezier(.1, .8, .9, 1); transition: all .3s cubic-bezier(.1, .8, .9, 1); } .lista-artigiani.landed { -webkit-transform: translateY(0); -moz-transform: translateY(0); transform: translateY(0); } .lista-artigiani li { border-bottom: 1px solid #eee; height: 80px; overflow: hidden; position: relative; -webkit-transition: all .3s cubic-bezier(.1, .8, .9, 1); -moz-transition: all .3s cubic-bezier(.1, .8, .9, 1); transition: all .3s cubic-bezier(.1, .8, .9, 1); } .main-data, .back-data { height: 100%; position: relative; } .main-data { z-index: 2; } .slide { align-items: center; background-color: #fff; display: flex; float: left; height: 100%; padding: 5px; width: 85%; -webkit-transform: translateX(0); -moz-transform: translateX(0); transform: translateX(0); -webkit-transition: all .3s cubic-bezier(.1, .2, .3, 1); -moz-transition: all .3s cubic-bezier(.1, .2, .3, 1); transition: all .3s cubic-bezier(.1, .2, .3, 1); } .active .slide { -webkit-transform: translateX(-100%); -moz-transform: translateX(-100%); transform: translateX(-100%); } .img-wrapper { background-position: center; background-size: cover; border-radius: 50%; float: left; height: 50px; margin: 0 10px; overflow: hidden; width: 50px; } h1 { color: #bf360c; font-size: 18px; font-weight: 300; margin: 0; } h1 span { color: #dd2c00; font-size: 13px; } .toggle { background-color: #fff; border-left: 1px solid #eee; color: #600202; float: right; font-size: 32px; line-height: 80px; text-align: center; width: 15%; } .toggle span { color: #bf360c; display: block; -webkit-transform: rotate(0); -moz-transform: rotate(0); transform: rotate(0); -webkit-transition: all .3s cubic-bezier(.1, .2, .3, 1); -moz-transition: all .3s cubic-bezier(.1, .2, .3, 1); transition: all .3s cubic-bezier(.1, .2, .3, 1); } .active .toggle span { -webkit-transform: rotate(135deg); -moz-transform: rotate(135deg); transform: rotate(135deg); } .back-data { align-items: center; display: flex; font-size: 18px; justify-content: space-evenly; justify-content: center; width: 85%; z-index: 1; -webkit-transform: translateY(-100%); -moz-transform: translateY(-100%); transform: translateY(-100%); } .back-data a { /*border: 1px solid #fff; border-radius: 50%; color: #fff; height: 32px; line-height: 30px; margin: 0; opacity: 0; text-align: center; width: 32px; -webkit-transform: translateX(-100%); -moz-transform: translateX(-100%); transform: translateX(-100%); -webkit-transition: all .3s; -moz-transition: all .3s; transition: all .3s;*/ } .back-data i { border: 1px solid #fff; border-radius: 50%; color: #fff; height: 32px; line-height: 30px; margin: 0; opacity: 0; text-align: center; width: 32px; -webkit-transform: translateX(-100%); -moz-transform: translateX(-100%); transform: translateX(-100%); -webkit-transition: all .3s; -moz-transition: all .3s; transition: all .3s; } .active .back-data { z-index: 3; } .active .back-data i { margin: 0 15px; opacity: 1; -webkit-transform: translateX(0); -moz-transform: translateX(0); transform: translateX(0); } @media only screen and (min-width: 768px) { .lista-artigiani { display: flex; flex-wrap: wrap; } .lista-artigiani li { margin: 1%; width: 48%; } } @media only screen and (min-width: 1024px) { .lista-artigiani li { box-shadow: 0 0 4px #888888; height: 80px; margin: 20px; overflow: hidden; position: relative; -webkit-transition: all .3s cubic-bezier(.1, .8, .9, 1); -moz-transition: all .3s cubic-bezier(.1, .8, .9, 1); transition: all .3s cubic-bezier(.1, .8, .9, 1); width: 31%; } } @media only screen and (min-width: 1200px) { .lista-artigiani li { width: 23%; } }
hcvitto/ng-app-slim-api
src/app/lista/lista.component.css
CSS
unlicense
3,924
/** * Copyright (c) 2014,Egret-Labs.org * 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 the Egret-Labs.org 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 EGRET-LABS.ORG 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 EGRET-LABS.ORG AND 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. */ declare module p2 { export class AABB { upperBound: number[]; lowerBound: number[]; constructor(options?: { upperBound?: number[]; lowerBound?: number[]; }); setFromPoints(points: number[][], position: number[], angle: number, skinSize: number): void; copy(aabb: AABB): void; extend(aabb: AABB): void; overlaps(aabb: AABB): boolean; } export class Broadphase { static AABB: number; static BOUNDING_CIRCLE: number; static NAIVE: number; static SAP: number; static boundingRadiusCheck(bodyA: Body, bodyB: Body): boolean; static aabbCheck(bodyA: Body, bodyB: Body): boolean; static canCollide(bodyA: Body, bodyB: Body): boolean; constructor(type: number); type: number; result: Body[]; world: World; boundingVolumeType: number; setWorld(world: World): void; getCollisionPairs(world: World): Body[]; boundingVolumeCheck(bodyA: Body, bodyB: Body): boolean; } export class GridBroadphase extends Broadphase { constructor(options?: { xmin?: number; xmax?: number; ymin?: number; ymax?: number; nx?: number; ny?: number; }); xmin: number; xmax: number; ymin: number; ymax: number; nx: number; ny: number; binsizeX: number; binsizeY: number; } export class NativeBroadphase extends Broadphase { } export class Narrowphase { contactEquations: ContactEquation[]; frictionEquations: FrictionEquation[]; enableFriction: boolean; slipForce: number; frictionCoefficient: number; surfaceVelocity: number; reuseObjects: boolean; resuableContactEquations: any[]; reusableFrictionEquations: any[]; restitution: number; stiffness: number; relaxation: number; frictionStiffness: number; frictionRelaxation: number; enableFrictionReduction: boolean; contactSkinSize: number; collidedLastStep(bodyA: Body, bodyB: Body): boolean; reset(): void; createContactEquation(bodyA: Body, bodyB: Body, shapeA: Shape, shapeB: Shape): ContactEquation; createFrictionFromContact(c: ContactEquation): FrictionEquation; } export class SAPBroadphase extends Broadphase { axisList: Body[]; axisIndex: number; } export class Constraint { static DISTANCE: number; static GEAR: number; static LOCK: number; static PRISMATIC: number; static REVOLUTE: number; constructor(bodyA: Body, bodyB: Body, type: number, options?: { collideConnected?: boolean; wakeUpBodies?: boolean; }); type: number; equeations: Equation[]; bodyA: Body; bodyB: Body; collideConnected: boolean; update(): void; setStiffness(stiffness: number): void; setRelaxation(relaxation: number): void; } export class DistanceConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: { collideConnected?: boolean; wakeUpBodies?: boolean; distance?: number; localAnchorA?: number[]; localAnchorB?: number[]; maxForce?: number; }); localAnchorA: number[]; localAnchorB: number[]; distance: number; maxForce: number; upperLimitEnabled: boolean; upperLimit: number; lowerLimitEnabled: boolean; lowerLimit: number; position: number; setMaxForce(f: number): void; getMaxForce(): number; } export class GearConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: { collideConnected?: boolean; wakeUpBodies?: boolean; angle?: number; ratio?: number; maxTorque?: number; }); ratio: number; angle: number; setMaxTorque(torque: number): void; getMaxTorque(): number; } export class LockConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: { collideConnected?: boolean; wakeUpBodies?: boolean; localOffsetB?: number[]; localAngleB?: number; maxForce?: number; }); localOffsetB: number[]; localAngleB: number; setMaxForce(force: number): void; getMaxForce(): number; } export class PrismaticConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: { collideConnected?: boolean; wakeUpBodies?: boolean; maxForce?: number; localAnchorA?: number[]; localAnchorB?: number[]; localAxisA?: number[]; disableRotationalLock?: boolean; upperLimit?: number; lowerLimit?: number; }); localAnchorA: number[]; localAnchorB: number[]; localAxisA: number[]; position: number; velocity: number; lowerLimitEnabled: boolean; upperLimitEnabled: boolean; lowerLimit: number; upperLimit: number; upperLimitEquation: ContactEquation; lowerLimitEquation: ContactEquation; motorEquation: Equation; motorEnabled: boolean; motorSpeed: number; disableRotationalLock: boolean; enableMotor(): void; disableMotor(): void; setLimits(lower: number, upper: number): void; } export class RevoluteConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: { collideConnected?: boolean; wakeUpBodies?: boolean; worldPivot?: number[]; localPivotA?: number[]; localPivotB?: number[]; maxForce?: number; }); pivotA: number[]; pivotB: number[]; motorEquation: RotationalVelocityEquation; motorEnabled: boolean; angle: number; lowerLimitEnabled: boolean; upperLimitEnabled: boolean; lowerLimit: number; upperLimit: number; upperLimitEquation: ContactEquation; lowerLimitEquation: ContactEquation; enableMotor(): void; disableMotor(): void; motorIsEnabled(): boolean; setLimits(lower: number, upper: number): void; setMotorSpeed(speed: number): void; getMotorSpeed(): number; } export class AngleLockEquation extends Equation { constructor(bodyA: Body, bodyB: Body, options?: { angle?: number; ratio?: number; }); computeGq(): number; setRatio(ratio: number): number; setMaxTorque(torque: number): number; } export class ContactEquation extends Equation { constructor(bodyA: Body, bodyB: Body); contactPointA: number[]; penetrationVec: number[]; contactPointB: number[]; normalA: number[]; restitution: number; firstImpact: boolean; shapeA: Shape; shapeB: Shape; computeB(a: number, b: number, h: number): number; } export class Equation { static DEFAULT_STIFFNESS: number; static DEFAULT_RELAXATION: number; constructor(bodyA: Body, bodyB: Body, minForce?: number, maxForce?: number); minForce: number; maxForce: number; bodyA: Body; bodyB: Body; stiffness: number; relaxation: number; G: number[]; offset: number; a: number; b: number; epsilon: number; timeStep: number; needsUpdate: boolean; multiplier: number; relativeVelocity: number; enabled: boolean; gmult(G: number[], vi: number[], wi: number[], vj: number[], wj: number[]): number; computeB(a: number, b: number, h: number): number; computeGq(): number; computeGW(): number; computeGWlambda(): number; computeGiMf(): number; computeGiMGt(): number; addToWlambda(deltalambda: number): number; computeInvC(eps: number): number; update():void; } export class FrictionEquation extends Equation { constructor(bodyA: Body, bodyB: Body, slipForce: number); contactPointA: number[]; contactPointB: number[]; t: number[]; shapeA: Shape; shapeB: Shape; frictionCoefficient: number; setSlipForce(slipForce: number): number; getSlipForce(): number; computeB(a: number, b: number, h: number): number; } export class RotationalLockEquation extends Equation { constructor(bodyA: Body, bodyB: Body, options?: { angle?: number; }); angle: number; computeGq(): number; } export class RotationalVelocityEquation extends Equation { constructor(bodyA: Body, bodyB: Body); computeB(a: number, b: number, h: number): number; } export class EventEmitter { on(type: string, listener: Function): EventEmitter; has(type: string, listener: Function): boolean; off(type: string, listener: Function): EventEmitter; emit(event: any): EventEmitter; } export class ContactMaterialOptions { friction: number; restitution: number; stiffness: number; relaxation: number; frictionStiffness: number; frictionRelaxation: number; surfaceVelocity: number; } export class ContactMaterial { static idCounter: number; constructor(materialA: Material, materialB: Material, options?: ContactMaterialOptions); id: number; materialA: Material; materialB: Material; friction: number; restitution: number; stiffness: number; relaxation: number; frictionStuffness: number; frictionRelaxation: number; surfaceVelocity: number; contactSkinSize: number; } export class Material { static idCounter: number; constructor(id: number); id: number; } export class vec2 { static crossLength(a: number[], b: number[]): number; static crossVZ(out: number[], vec: number[], zcomp: number): number; static crossZV(out: number[], zcomp: number, vec: number[]): number; static rotate(out: number[], a: number[], angle: number): void; static rotate90cw(out: number[], a: number[]): number; static centroid(out: number[], a: number[], b: number[], c: number[]): number[]; static create(): number[]; static clone(a: number[]): number[]; static fromValues(x: number, y: number): number[]; static copy(out: number[], a: number[]): number[]; static set(out: number[], x: number, y: number): number[]; static toLocalFrame(out: number[], worldPoint: number[], framePosition: number[], frameAngle: number): void; static toGlobalFrame(out: number[], localPoint: number[], framePosition: number[], frameAngle: number): void; static add(out: number[], a: number[], b: number[]): number[]; static subtract(out: number[], a: number[], b: number[]): number[]; static sub(out: number[], a: number[], b: number[]): number[]; static multiply(out: number[], a: number[], b: number[]): number[]; static mul(out: number[], a: number[], b: number[]): number[]; static divide(out: number[], a: number[], b: number[]): number[]; static div(out: number[], a: number[], b: number[]): number[]; static scale(out: number[], a: number[], b: number): number[]; static distance(a: number[], b: number[]): number; static dist(a: number[], b: number[]): number; static squaredDistance(a: number[], b: number[]): number; static sqrDist(a: number[], b: number[]): number; static length(a: number[]): number; static len(a: number[]): number; static squaredLength(a: number[]): number; static sqrLen(a: number[]): number; static negate(out: number[], a: number[]): number[]; static normalize(out: number[], a: number[]): number[]; static dot(a: number[], b: number[]): number; static str(a: number[]): string; } // export class BodyOptions { // // mass: number; // position: number[]; // velocity: number[]; // angle: number; // angularVelocity: number; // force: number[]; // angularForce: number; // fixedRotation: number; // // } /** * 刚体。有质量、位置、速度等属性以及一组被用于碰撞的形状 * * @class Body * @constructor * @extends EventEmitter * @param {Object} [options] * @param {Number} [options.mass=0] 一个大于0的数字。如果设置成0,其type属性将被设置为 Body.STATIC. * @param {Array} [options.position] * @param {Array} [options.velocity] * @param {Number} [options.angle=0] * @param {Number} [options.angularVelocity=0] * @param {Array} [options.force] * @param {Number} [options.angularForce=0] * @param {Number} [options.fixedRotation=false] * * @example * // 创建一个刚体 * var body = new Body({ * mass: 1, * position: [0, 0], * angle: 0, * velocity: [0, 0], * angularVelocity: 0 * }); * * // 将一个圆形形状添加到刚体 * body.addShape(new Circle(1)); * * // 将刚体加入 world * world.addBody(body); */ export class Body extends EventEmitter { sleepyEvent: { type: string; }; sleepEvent: { type: string; }; wakeUpEvent: { type: string; }; static DYNAMIC: number; static STATIC: number; static KINEMATIC: number; static AWAKE: number; static SLEEPY: number; static SLEEPING: number; constructor(options?); /** * 刚体id * @property id * @type {Number} */ id: number; /** * 刚体被添加到的 world。如果没有被添加到 world 该属性将被设置为 null * @property world * @type {World} */ world: World; /** * 刚体的碰撞形状 * * @property shapes * @type {Array} */ shapes: Shape[]; /** * 碰撞形状相对于刚体中心的偏移 * @property shapeOffsets * @type {Array} */ //shapeOffsets: number[][]; /** * 碰撞形状的角度变换 * @property shapeAngles * @type {Array} */ //shapeAngles: number[]; /** * 质量 * @property mass * @type {number} */ mass: number; /** * 惯性 * @property inertia * @type {number} */ inertia: number; /** * 是否固定旋转 * @property fixedRotation * @type {Boolean} */ fixedRotation: boolean; /** * 位置 * @property position * @type {Array} */ position: number[]; /** * 位置插值 * @property interpolatedPosition * @type {Array} */ interpolatedPosition: number[]; /** * 角度插值 * @property interpolatedAngle * @type {Number} */ interpolatedAngle: number; /** * 速度 * @property velocity * @type {Array} */ velocity: number[]; /** * 角度 * @property angle * @type {number} */ angle: number; /** * 力 * @property force * @type {Array} */ force: number[]; /** * 角力 * @property angularForce * @type {number} */ angularForce: number; /** * 限行阻尼。取值区间[0,1] * @property damping * @type {Number} * @default 0.1 */ damping: number; /** * 角阻尼。取值区间[0,1] * @property angularDamping * @type {Number} * @default 0.1 */ angularDamping: number; /** * 运动类型。 应该是Body.STATIC,Body.DYNAMIC,Body.KINEMATIC之一 * * * Static 刚体不会动,不响应力或者碰撞 * * Dynamic 刚体会动,响应力和碰撞 * * Kinematic 刚体仅根据自身属性运动,不响应力或者碰撞 * * @property type * @type {number} * * @example * // 默认值是STATIC * var body = new Body(); * console.log(body.type == Body.STATIC); // true * * @example * // 将质量设置为非0的值,会变为DYNAMIC * var dynamicBody = new Body({ * mass : 1 * }); * console.log(dynamicBody.type == Body.DYNAMIC); // true * * @example * // KINEMATIC刚体只会运动,如果你改变它的速度 * var kinematicBody = new Body({ * type: Body.KINEMATIC * }); */ type: number; /** * 边界圆半径 * @property boundingRadius * @type {Number} */ boundingRadius: number; /** * 边框 * @property aabb * @type {AABB} */ aabb: AABB; /** * 设置AABB是否会更新。通过调用 updateAABB 方法更新它 * @property aabbNeedsUpdate * @type {Boolean} * @see updateAABB * * @example * body.aabbNeedsUpdate = true; * body.updateAABB(); * console.log(body.aabbNeedsUpdate); // false */ aabbNeedsUpdate: boolean; /** * 设置为true,刚体会自动进入睡眠。需要在 World 中允许刚体睡眠 * @property allowSleep * @type {Boolean} * @default true */ allowSleep: boolean; wantsToSleep: boolean; /** * Body.AWAKE,Body.SLEEPY,Body.SLEEPING之一 * * 默认值是 Body.AWAKE。如果刚体速度低于 sleepSpeedLimit,该属性将变为 Body.SLEEPY。如果持续 Body.SLEEPY 状态 sleepTimeLimit 秒,该属性将变为 Body.SLEEPY。 * * @property sleepState * @type {Number} * @default Body.AWAKE */ sleepState: number; /** * 如果速度小于该值,sleepState 将变为 Body.SLEEPY 状态 * @property sleepSpeedLimit * @type {Number} * @default 0.2 */ sleepSpeedLimit: number; /** * 如果持续 Body.SLEEPY 状态 sleepTimeLimit 秒,sleepState 将变为 Body.SLEEPING * @property sleepTimeLimit * @type {Number} * @default 1 */ sleepTimeLimit: number; /** * 重力缩放因子。如果你想忽略刚体重心,设置为零。如果你想反转重力,将其设置为-1。 * @property {Number} gravityScale * @default 1 */ gravityScale: number; /** * 与每个形状对应的显示对象 */ displays: egret.DisplayObject[]; userData: any; updateSolveMassProperties(): void; /** * 设置刚体总密度 * @method setDensity */ setDensity(density: number): void; /** * 得到所有形状的总面积 * @method getArea * @return {Number} */ getArea(): number; /** * 获得AABB * @method getAABB */ getAABB(): AABB; /** * 更新AABB * @method updateAABB */ updateAABB(): void; /** * 更新外边界 * @method updateBoundingRadius */ updateBoundingRadius(): void; /** * 添加一个形状 * * @method addShape * @param {Shape} shape 形状 * @param {Array} [offset] 偏移 * @param {Number} [angle] 角度 * * @example * var body = new Body(), * shape = new Circle(); * * // 位于中心 * body.addShape(shape); * * // 偏移量为x轴一个单位 * body.addShape(shape,[1,0]); * * // 偏移量为y轴一个单位,同时逆时针旋转90度 * body.addShape(shape,[0,1],Math.PI/2); */ addShape(shape: Shape, offset?: number[], angle?: number): void; /** * 移除形状 * @method removeShape * @param {Shape} shape * @return {Boolean} */ removeShape(shape: Shape): boolean; /** * 更新属性,结构或者质量改变时会被调用 * * @method updateMassProperties * * @example * body.mass += 1; * body.updateMassProperties(); */ updateMassProperties(): void; /** * 相对于 world 中的一个点施加力 * @method applyForce * @param {Array} force 力 * @param {Array} worldPoint world 中的点 */ applyForce(force: number[], worldPoint: number[]): void; /** * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. * @method wakeUp */ wakeUp(): void; /** * Force body sleep * @method sleep */ sleep(): void; /** * Called every timestep to update internal sleep timer and change sleep state if needed. * @method sleepTick * @param {number} time The world time in seconds * @param {boolean} dontSleep * @param {number} dt */ sleepTick(time: number, dontSleep: boolean, dt: number): void; getVelocityFromPosition(story: number[], dt: number): number[]; getAngularVelocityFromPosition(timeStep: number): number; /** * Check if the body is overlapping another body. Note that this method only works if the body was added to a World and if at least one step was taken. * @method overlaps * @param {Body} body * @return {boolean} */ overlaps(body: Body): boolean; // functions below was added by ladeng6666 angularVelocity: number; toWorldFrame(out: number[], localPoint: number[]): void; toLocalFrame(out: number[], worldPoint: number[]): void; adjustCenterOfMass(): void; fromPolygon(vertices: number[][], options?: any): Body; applyDamping(dt: number): void; applyImpulse(force: number[], worldPoint: number[]): void; collisionResponse: boolean; } export class Spring { constructor(bodyA: Body, bodyB: Body, options?: { stiffness?: number; damping?: number; localAnchorA?: number[]; localAnchorB?: number[]; worldAnchorA?: number[]; worldAnchorB?: number[]; }); stiffness: number; damping: number; bodyA: Body; bodyB: Body; applyForce(): void; } export class LinearSpring extends Spring { localAnchorA: number[]; localAnchorB: number[]; restLength: number; setWorldAnchorA(worldAnchorA: number[]): void; setWorldAnchorB(worldAnchorB: number[]): void; getWorldAnchorA(result: number[]): number[]; getWorldAnchorB(result: number[]): number[]; applyForce(): void; } export class RotationalSpring extends Spring { constructor(bodyA: Body, bodyB: Body, options?: { restAngle?: number; stiffness?: number; damping?: number; }); restAngle: number; } export class Capsule extends Shape { constructor(length?: number, radius?: number); length: number; radius: number; } export class Circle extends Shape { constructor(radius: number); /** * 半径 * @property radius * @type {number} */ radius: number; } export class Convex extends Shape { static triangleArea(a: number[], b: number[], c: number[]): number; constructor(vertices: number[][], axes?: number[]); vertices: number[][]; axes: number[]; centerOfMass: number[]; triangles: number[]; boundingRadius: number; projectOntoLocalAxis(localAxis: number[], result: number[]): void; projectOntoWorldAxis(localAxis: number[], shapeOffset: number[], shapeAngle: number, result: number[]): void; updateCenterOfMass(): void; } export class Heightfield extends Shape { constructor(data: number[], options?: { minValue?: number; maxValue?: number; elementWidth: number; }); data: number[]; maxValue: number; minValue: number; elementWidth: number; } export class Shape { static idCounter: number; static CIRCLE: number; static PARTICLE: number; static PLANE: number; static CONVEX: number; static LINE: number; static RECTANGLE: number; static CAPSULE: number; static HEIGHTFIELD: number; constructor(type?: number); type: number; id: number; boundingRadius: number; collisionGroup: number; collisionMask: number; material: Material; area: number; sensor: boolean; vertices: number[][]; //2015-05-12 ladeng6666 angle: number; position: number[]; computeMomentOfInertia(mass: number): number; updateBoundingRadius(): number; updateArea(): void; computeAABB(out: AABB, position: number[], angle: number): void; } export class Line extends Shape { constructor(length?: number); length: number; } export class Particle extends Shape { } export class Plane extends Shape { } export class Rectangle extends Shape { constructor(width?: number, height?: number); width: number; height: number; } export class Solver extends EventEmitter { static GS: number; static ISLAND: number; constructor(options?: {}, type?: number); type: number; equations: Equation[]; equationSortFunction: Equation; //Equation | boolean solve(dy: number, world: World): void; solveIsland(dy: number, island: Island): void; sortEquations(): void; addEquation(eq: Equation): void; addEquations(eqs: Equation[]): void; removeEquation(eq: Equation): void; removeAllEquations(): void; tolerance: number; frictionIterations: number; } export class GSSolver extends Solver { constructor(options?: { iterations?: number; tolerance?: number; }); iterations: number; tolerance: number; useZeroRHS: boolean; frictionIterations: number; usedIterations: number; solve(h: number, world: World): void; } export class OverlapKeeper { constructor(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape); shapeA: Shape; shapeB: Shape; bodyA: Body; bodyB: Body; tick(): void; setOverlapping(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Body): void; bodiesAreOverlapping(bodyA: Body, bodyB: Body): boolean; set(bodyA: Body, shapeA: Shape, bodyB: Body, shapeB: Shape): void; } export class TupleDictionary { data: number[]; keys: number[]; getKey(id1: number, id2: number): string; getByKey(key: number): number; get(i: number, j: number): number; set(i: number, j: number, value: number): number; reset(): void; copy(dict: TupleDictionary): void; } export class Utils { static appendArray<T>(a: Array<T>, b: Array<T>): Array<T>; static splice<T>(array: Array<T>, index: number, howMany: number): void; static extend(a: any, b: any): void; static defaults(options: any, defaults: any): any; } export class Island { equations: Equation[]; bodies: Body[]; reset(): void; getBodies(result: any): Body[]; wantsToSleep(): boolean; sleep(): boolean; } export class IslandManager extends Solver { static getUnvisitedNode(nodes: Node[]): IslandNode; // IslandNode | boolean equations: Equation[]; islands: Island[]; nodes: IslandNode[]; visit(node: IslandNode, bds: Body[], eqs: Equation[]): void; bfs(root: IslandNode, bds: Body[], eqs: Equation[]): void; split(world: World): Island[]; } export class IslandNode { constructor(body: Body); body: Body; neighbors: IslandNode[]; equations: Equation[]; visited: boolean; reset(): void; } /** * world,包含所有刚体 * * @class World * @constructor * @param {Object} [options] * @param {Solver} [options.solver] 默认值 GSSolver. * @param {Array} [options.gravity] 默认值 [0,-9.78] * @param {Broadphase} [options.broadphase] 默认值 NaiveBroadphase * @param {Boolean} [options.islandSplit=false] * @param {Boolean} [options.doProfiling=false] * @extends EventEmitter * * @example * var world = new World({ * gravity: [0, -9.81], * broadphase: new SAPBroadphase() * }); */ export class World extends EventEmitter { /** * step() 执行之后调用 * @event postStep */ postStepEvent: { type: string; }; /** * Body 加入时调用 * @event addBody * @param {Body} body */ addBodyEvent: { type: string; }; /** * Body移除时调用 * @event removeBody * @param {Body} body */ removeBodyEvent: { type: string; }; /** * Spring 加入时调用 * @event addSpring * @param {Spring} spring */ addSpringEvent: { type: string; }; /** * 当两个刚体第一次碰撞时调用。调用时碰撞步骤已经完成 * @event impact * @param {Body} bodyA * @param {Body} bodyB */ impactEvent: { type: string; bodyA: Body; bodyB: Body; shapeA: Shape; shapeB: Shape; contactEquation: ContactEquation; }; /** * 当 Broadphase 手机对碰之后被调用 * @event postBroadphase * @param {Array} 对碰数组 */ postBroadphaseEvent: { type: string; pairs: Body[]; }; /** * 当两个形状重叠时调用 * @event beginContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ beginContactEvent: { type: string; shapeA: Shape; shapeB: Shape; bodyA: Body; bodyB: Body; contactEquations: ContactEquation[]; }; /** * 当两个形状停止重叠时调用 * @event endContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ endContactEvent: { type: string; shapeA: Shape; shapeB: Shape; bodyA: Body; bodyB: Body; }; /** * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver. * @event preSolve * @param {Array} contactEquations An array of contacts to be solved. * @param {Array} frictionEquations An array of friction equations to be solved. */ preSolveEvent: { type: string; contactEquations: ContactEquation[]; frictionEquations: FrictionEquation[]; }; /** * 从不让刚体睡眠 * @static * @property {number} NO_SLEEPING */ static NO_SLEEPING: number; /** * 刚体睡眠 * @static * @property {number} BODY_SLEEPING */ static BODY_SLEEPING: number; /** * 取消激活在接触中的刚体,如果所有刚体都接近睡眠。必须设置 World.islandSplit * @static * @property {number} ISLAND_SLEEPING */ static ISLAND_SLEEPING: number; constructor(options?: { solver?: Solver; gravity?: number[]; broadphase?: Broadphase; islandSplit?: boolean; doProfiling?: boolean; }); /** * 所有 Spring * @property springs * @type {Array} */ springs: Spring[]; /** * 所有 Body * @property {Array} bodies */ bodies: Body[]; /** * 所使用的求解器,以满足约束条件和接触。 默认值是 GSSolver * @property {Solver} solver */ solver: Solver; /** * @property narrowphase * @type {Narrowphase} */ narrowphase: Narrowphase; /** * The island manager of this world. * @property {IslandManager} islandManager */ islandManager: IslandManager; /** * 重力。在每个 step() 开始对所有刚体生效 * * @property gravity * @type {Array} */ gravity: number[]; /** * 重力摩擦 * @property {Number} frictionGravity */ frictionGravity: number; /** * 设置为true,frictionGravity 会被自动设置为 gravity 长度. * @property {Boolean} useWorldGravityAsFrictionGravity */ useWorldGravityAsFrictionGravity: boolean; /** * @property broadphase * @type {Broadphase} */ broadphase: Broadphase; /** * 用户添加限制 * * @property constraints * @type {Array} */ constraints: Constraint[]; /** * 默认材料,defaultContactMaterial 时使用 * @property {Material} defaultMaterial */ defaultMaterial: Material; /** * 使用的默认接触材料,如果没有接触材料被设置为碰撞的材料 * @property {ContactMaterial} defaultContactMaterial */ defaultContactMaterial: ContactMaterial; /** * 设置自动使用弹簧力 * @property applySpringForces * @type {Boolean} */ applySpringForces: boolean; /** * 设置自动使用阻尼 * @property applyDamping * @type {Boolean} */ applyDamping: boolean; /** * 设置自动使用重力 * @property applyGravity * @type {Boolean} */ applyGravity: boolean; /** * 使用约束求解 * @property solveConstraints * @type {Boolean} */ solveConstraints: boolean; /** * 接触材料 * @property contactMaterials * @type {Array} */ contactMaterials: ContactMaterial[]; /** * 世界时间 * @property time * @type {Number} */ time: number; /** * 是否正在 step 阶段 * @property {Boolean} stepping */ stepping: boolean; /** * 是否启用岛内分裂 * @property {Boolean} islandSplit */ islandSplit: boolean; /** * 设置为true,world会派发 impact 事件,关闭可以提高性能 * @property emitImpactEvent * @type {Boolean} */ emitImpactEvent: boolean; /** * 刚体睡眠策略。取值是 World.NO_SLEEPING,World.BODY_SLEEPING,World.ISLAND_SLEEPING 之一 * @property sleepMode * @type {number} * @default World.NO_SLEEPING */ sleepMode: number; /** * 添加约束 * @method addConstraint * @param {Constraint} c */ addConstraint(c: Constraint): void; /** * 添加触点材料 * @method addContactMaterial * @param {ContactMaterial} contactMaterial */ addContactMaterial(contactMaterial: ContactMaterial): void; /** * 移除触点材料 * @method removeContactMaterial * @param {ContactMaterial} cm */ removeContactMaterial(cm: ContactMaterial): void; /** * 通过2个材料获得触点材料 * @method getContactMaterial * @param {Material} materialA * @param {Material} materialB * @return {ContactMaterial} 获得的触点材料或者false */ getContactMaterial(materialA: Material, materialB: Material): ContactMaterial; /** * 移除约束 * @method removeConstraint * @param {Constraint} c */ removeConstraint(c: Constraint): void; /** * 使物理系统向前经过一定时间 * * @method step * @param {Number} dt 时长 * @param {Number} [timeSinceLastCalled=0] * @param {Number} [maxSubSteps=10] * * @example * var world = new World(); * world.step(0.01); */ step(dt: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; /** * 添加一个 Spring * * @method addSpring * @param {Spring} s */ addSpring(s: Spring): void; /** * 移除一个 Spring * * @method removeSpring * @param {Spring} s */ removeSpring(s: Spring): void; /** * 添加一个 Body * * @method addBody * @param {Body} body * * @example * var world = new World(), * body = new Body(); * world.addBody(body); */ addBody(body: Body): void; /** * 移除一个 Body。如果在 step()阶段调用,将会在阶段之后移除 * * @method removeBody * @param {Body} body */ removeBody(body: Body): void; /** * 通过id获取一个 Body * @method getBodyById * @return {Body|Boolean} 得到的刚体或者false */ getBodyByID(id: number): Body; /** * 两个刚体之间禁用碰撞 * @method disableCollision * @param {Body} bodyA * @param {Body} bodyB */ disableBodyCollision(bodyA: Body, bodyB: Body): void; /** * 两个刚体之间启用碰撞 * @method enableCollision * @param {Body} bodyA * @param {Body} bodyB */ enableBodyCollision(bodyA: Body, bodyB: Body): void; /** * 重置 world * @method clear */ clear(): void; /** * 获得克隆 * @method clone * @return {World} */ clone(): World; /** * [ladeng6666] 检测world中,与一组全局坐标点worldPoint,与一组刚体是否发生碰撞,并返回碰撞的刚体列表 * @param {Array} worldPoint 一组全局要检测的全局坐标点. * @param {Array} bodies 要检测的刚体列表. * @param {number} precision 检测的精确度. */ hitTest(worldPoint: number[], bodies: Body[], precision?: number): Body[]; //functions below were added by ladeng6666 /*raycastAll(from: number[], to: number[], options: { collisionMask?: number; collisionGroup?: number; skipBackfaces?: boolean; checkCollisionResponse?:boolean}, callback: Function): void; raycastAny(from: number[], to: number[], options: Object, result: RayCastResult): void; raycastClosed(from: number[], to: number[], options: Object, callback: Function): void; */ raycast(result: RaycastResult, ray: Ray); } export class RaycastResult { constructor(); body: Body; fraction: number; shape: Shape; faceIndex: number; isStopped: boolean; normal: number[]; getHitPoint(out:number[],ray:Ray):number[]; getHitDistance(ray:Ray): number; hasHit(): boolean; reset(); stop(); } export class Ray { static ANY: number; static CLOSEST: number; static ALL: number; constructor(options?: { to?: number[]; from?: number[]; mode?: number; callback?: Function; collisionMask?: number; collisionGroup?: number; checkCollisionResponse?: boolean; skipBackfaces?: boolean; direction?: number[]; length?: number; }); to: number[]; from: number[]; mode: number; callback: Function; collisionMask: number; collisionGroup: number; checkCollisionResponse: boolean; skipBackfaces: boolean; direction: number[]; length: number; } }
ladeng6666/p2DebugDraw
p2.d.ts
TypeScript
unlicense
45,342
# todo - kibana https://search-hawk-eye-lrpsjeduj6pzee4mgujz4z6egu.ap-northeast-1.es.amazonaws.com/_plugin/kibana/app/kibana#/visualize/step/1?_g=() - https://temona.backlog.jp/alias/find/UKOKKEI/n1tTr - Sửa flow checkout backend 🌟 二、三月にやる - https://temona.backlog.jp/view/UKOKKEI-8058#comment-55515625 - https://temona.backlog.jp/ViewAttachmentPdf.action?attachmentId=5922577 バックエンドの受注フォーロの修正したワイヤーは共有します。 更新ところは - 金額が全部出す(まだ計算できないところは (ー) を出す、) - inputを満たせば再計算する (point - coupon) - 調整金額は総合計を調整する (Need confirm) - Ticket https://temona.backlog.jp/view/UKOKKEI-8417 - Viết test case cho edit order - 4月のバグ https://temona.backlog.jp/view/UKOKKEI-8385 - Staging 3月 https://temona.backlog.jp/view/UKOKKEI-8430 # Need confirm - Cancel shipment https://temona.backlog.jp/view/UKOKKEI-8387 - https://docs.google.com/document/d/1t90LkqI3Kgca4WpfDtbEvnvH_KttVk1WsGR0Lz9C_Jc/edit# ”たまごリピートNextの現たま超えにおける時短計画” # doing - Review code: - Show price of course_order https://github.com/TEMONA/ukokkei_core/pull/3064/files - order histories https://github.com/TEMONA/umls/pull/699 - テストケースの翻訳 - https://github.com/TEMONA/ukokkei_dummy/pull/177 Share member for active bullet and check N+1 when create PR - Test - https://temona.backlog.jp/view/UKOKKEI-8405 - https://temona.backlog.jp/view/UKOKKEI-8418 - 負荷テスト結果 - https://github.com/TEMONA/apache_jmeter/wiki - https://drive.google.com/drive/u/0/folders/13Boj-IbKBTE6EMqOK-CA76t31vTfNhgG - Fix N+1 - Improve import speed - Gem j-meter https://github.com/flood-io/ruby-jmeter - https://docs.google.com/document/d/10ceMbYaEvZzG_YDgX3lnlTezWCHDwfF6Bq00mOtO97E/edit# ⭐️ - Check logic campaign https://github.com/TEMONA/ukokkei_core/wiki/Campaign https://github.com/TEMONA/ukokkei_core/wiki/CampaignLogic https://github.com/TEMONA/umls/pull/664 - test NP xem có gửi mail khi chuyển từ NP sang 代引き # done - Rebase staging with production OK - Merge production to develop OK - Push tags OK - 移行 https://github.com/TEMONA/ukokkei_core/pull/3065/files OK - 再deploy staging # etc バグ - image variant をコーピできない 相談したい - ミスが多い - 仕事が多い SELECT SUM(lost_points.value) AS sum_value, lost_points.lost_on AS lost_points_lost_on FROM lost_points WHERE lost_points.deleted_at IS NULL AND lost_points.lostable_type = 'AdminUser' AND lost_points.user_id IN (13,11,4,6,1,3,2,7,14,15,9,8,5,10,12) AND (lost_points.lost_on BETWEEN '2018-03-01' AND '2018-03-31') GROUP BY lost_points.lost_on; SELECT SUM(lost_points.value) AS sum_value, lost_points.lost_on AS lost_points_lost_on FROM lost_points WHERE lost_points.deleted_at IS NULL AND lost_points.lostable_type = $1 AND lost_points.user_id IN (13, 11, 4, 6, 3, 2, 7, 14, 15, 9, 8, 5, 10, 12) AND (lost_points.lost_on BETWEEN '2018-03-01' AND '2018-03-31') GROUP BY lost_points.lost_on [[lostable_type, UkokkeiBackend::AdminUser]] https://stackoverflow.com/questions/10809176/regular-expressions-regex-in-japanese # encoding: utf-8 regex = /[\u30A0-\u30FF  ]+$/ DestinationAddress.select{|abc| !regex.match(abc.name_kana)}.count グルーマン 62 ハム 226 UCC 0 DestinationAddress.select{|abc| abc.name_kana.contains_kanji?}.count Lan2 グルーマン 62 ハム 226 UCC 0
nguyenduyta/note
2018/03/16.md
Markdown
unlicense
3,595
<?php namespace twtrpic\Http\Controllers; use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Routing\Controller as BaseController; use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests; class Controller extends BaseController { use AuthorizesRequests, DispatchesJobs, ValidatesRequests; }
linnit/TwtrPic
app/Http/Controllers/Controller.php
PHP
unlicense
365
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define WIDTH 1000 #define HEIGHT 1000 typedef struct { bool on; int brightness; } state; enum action { INVALID, TOGGLE, ON, OFF }; int max(int a, int b) { return a > b ? a : b; } int min(int a, int b) { return a < b ? a : b; } size_t rdline(FILE *in, char **out, size_t *size) { size_t bufsize, written = 0; char *buf = NULL; int c; if (out == NULL || in == NULL || size == NULL) { return UINT_MAX; } buf = *out; bufsize = *size; if ((c = fgetc(in)) == EOF) { return UINT_MAX; } else if (buf == NULL) { bufsize = 128; buf = (char*)malloc(bufsize * sizeof(char)); if (buf == NULL) { return UINT_MAX; } *size = bufsize; } do { if (written > (bufsize - 1)) { bufsize += 128; char *tmp = (char*)realloc(buf, bufsize * sizeof(char)); if (tmp == NULL) { return UINT_MAX; } buf = tmp; *size = bufsize; } buf[written++] = c; } while (c != '\n' && (c = fgetc(in)) != EOF); buf[written] = '\0'; *out = buf; return written; } int main(int argc, char **argv) { char *line = NULL, *rd = NULL; int n = 0; size_t len; state *grid = (state*) malloc(WIDTH * HEIGHT * sizeof(state)); memset(grid, 0, WIDTH * HEIGHT * sizeof(state)); while ((len = rdline(stdin, &line, &n)) != UINT_MAX) { enum action cmd = INVALID; rd = line; if (strncmp(rd, "toggle", 6) == 0) { rd += 7; cmd = TOGGLE; } else if (strncmp(rd, "turn", 4) == 0) { rd += 5; if (strncmp(rd, "on", 2) == 0) { rd += 3; cmd = ON; } else if (strncmp(rd, "off", 3) == 0) { rd += 4; cmd = OFF; } } if (cmd == INVALID) { continue; } int xstart = max(atoi(rd), 0); while (*rd++ != ','); int ystart = max(atoi(rd), 0); while (*rd++ != ' '); if (strncmp(rd, "through", 7) != 0) { continue; } rd += 8; int xend = min(atoi(rd), WIDTH - 1); while (*rd++ != ','); int yend = min(atoi(rd), HEIGHT - 1); for (int y = ystart; y <= yend; ++y) { state *line = &grid[y * WIDTH]; for (int x = xstart; x <= xend; ++x) { state *s = &line[x]; switch (cmd) { case TOGGLE: s->on = !s->on; s->brightness += 2; break; case ON: s->on = true; s->brightness += 1; break; case OFF: s->on = false; if (s->brightness) { s->brightness -= 1; } break; } } } } int lit = 0, brightness = 0; for (int y = 0; y < HEIGHT; ++y) { state *line = &grid[y * WIDTH]; for (int x = 0; x < WIDTH; ++x) { state *s = &line[x]; if (s->on) { ++lit; } brightness += s->brightness; } } printf("Part 1: %d\n", lit); printf("Part 2: %d\n", brightness); }
Nextra/adventofcode2015
C/Day06/day06.c
C
unlicense
2,716
import string import uuid import random from util import iDict import exception # Nothing is validating the Redir section in the xml. I may get nonexistent # params. # __all__ = ['RedirectionManager', 'LocalRedirection', 'RemoteRedirection'] def str2bool(x): if x is None: return False if x.lower() in ('true', 't', '1'): return True else: return False def strip_xpath(x): if not x: return x if x.startswith('/'): return "" else: return x def is_identifier(x): if not x: return False else: if x[0] in string.digits: return False else: return True def rand_port(): RAND_PORT_MIN = 1025 RAND_PORT_MAX = 65535 return str(random.randint(RAND_PORT_MIN, RAND_PORT_MAX)) class LocalRedirection(object): """ listenaddr: Name of parameter to give the IP addr of listening tunnel on local LP listenport: Name of parameter to give the port of the listening tunnel on local LP destaddr: Name of parameter that contains the IP of the target computer destport: Name of parameter that contains the port on the target computer """ def __init__(self, protocol, listenaddr, listenport, destaddr, destport, closeoncompletion="false", name="", srcport=None, srcportlist=None, srcportrange=None, *trashargs, **trashkargs): self.protocol = protocol # XXX - The redirection section really shouldn't have XPath in it. self.listenaddr = strip_xpath(listenaddr) self.listenport = strip_xpath(listenport) self.destaddr = strip_xpath(destaddr) self.destport = strip_xpath(destport) self.closeoncompletion = str2bool(closeoncompletion) self.name = name self.srcport = strip_xpath(srcport) self.srcportlist = srcportlist self.srcportrange = srcportrange def __repr__(self): return str(self.__dict__) class RemoteRedirection(object): def __init__(self, protocol, listenaddr, destport, closeoncompletion="false", name="", listenport=None, listenportlist=None, listenportrange=None, listenportcount=None, destaddr="0.0.0.0", *trashargs, **trashkargs): self.protocol = protocol self.listenaddr = strip_xpath(listenaddr) self.listenport = strip_xpath(listenport) self.destaddr = strip_xpath(destaddr) self.destport = strip_xpath(destport) self.closeoncompletion = str2bool(closeoncompletion) self.name = name # Need conversion? self.listenportlist = listenportlist self.listenportrange = listenportrange self.listenportcount = listenportcount def __repr__(self): return str(self.__dict__) class RedirectionManager: """This is something of a misnomer. This is really a redirection manager rather than a redirection object. This is responsible for taking the defined tunnels in the plug-in's XML and 'swapping out' the parameters as they pertain to redirection. A sample redirection section appears as follows: <redirection> <!-- (1) The "throwing" tunnel --> <local name="Launch" protocol="TCP" listenaddr="TargetIp" # IP of redirector listenport="TargetPort" # Port of redirector destaddr="TargetIp" # IP of target computer destport="TargetPort" # Port of target computer closeoncompletion="true"/> <!-- (2) The "Callin" tunnel --> <local name="Callin" protocol="TCP" listenaddr="TargetIp" # IP on redirector listenport="CallinPort" # Port on redirector destaddr="TargetIp" # IP of target callin destport="ListenPort" # Port of target callin closeoncompletion="false"/> <!-- (3) The "callback" tunnel --> <remote name="Callback" protocol="TCP" listenaddr="CallbackIp" # IP opened by egg (last redirector) listenport="CallbackPort" # Port opened by egg (last redirector) destport="CallbackLocalPort" # Port for throwing side to listen closeoncompletion="false"/> </redirection> For the "throwing" (launch) tunnel, we: 1: Ask for/retrieve the "Destination IP" and "Destination Port", which default to the "TargetIp" and "TargetPort" parameters 2: Ask for the "Listen IP" (listenaddr) and "Listen Port" (listenport) and then swap them in "TargetIp" and "TargetPort" 3: After execution, restore the proper session parameters * (listenaddr, listenport) = l(destaddr, destport) For the "callin" tunnel, we: 1: Ask for/retrieve the "Destination IP" and Destination Port", which default to the "TargetIp" and the "ListenPort" parameters 2: Ask for the "Listen IP" (listenaddr) and "Listen Port" (listenport) and then swap them into "TargetIp" and "CallinPort" parameters 3: After execution, restore the proper session parameters * (listenaddr, listenport) = l(destaddr, destport) For the "callback" tunnel, we: 1: Ask for the Listen IP and Listen Port for which the payload will callback. This is most likely the last hop redirector IP and a port on it 2: Ask for the Destination IP and Destination Port, which will likely be the operator workstation. Store the Destination port as "CallbackLocalPort", basically ignoring the DestinationIp 3: After execution, restore the proper session parameters * (destaddr, destport) = l(listenaddr, listenport) """ def __init__(self, io): self.io = io self.active = False # A place to store parameters for the session. We push the info, run the plug-in # (with redirection), and then pop the info to restore it self.session_cache = {} def on(self): self.active = True def off(self): self.active = False def is_active(self): return self.active def get_status(self): if self.active: return "ON" else: return "OFF" def get_session(self, id): return self.session_cache.get(id) def pre_exec(self, plugin): if not plugin.canRedirect(): return 0 if self.is_active(): self.io.print_msg("Redirection ON") return self.config_redirect(plugin, True) else: self.io.print_msg("Redirection OFF") return self.config_redirect(plugin, False) def post_exec(self, plugin, id): if id == 0: return # if plugin doesn't do redir, return try: stored_session_data = self.session_cache.pop(id) except KeyError: return # Restore the old information to the session for key,val in stored_session_data['params'].items(): plugin.set(key, val) def print_session(self, id): try: session = self.session_cache[id] except KeyError: return self.io.print_global_redir(session) """ Pre plugin execution """ def conv_param(self, val, params, session_data={}): """Resolve a value from one of session, params, or the hard value""" try: # First try to find the session parameter if val in session_data: return session_data[val] # Then try to find the context-specific parameter if is_identifier(val): return params[val] except: return None # If it is neither a session or context parameter, return the value as is return val def prompt_redir_fake(self, msg, default): done = None while not done: try: line = self.io.prompt_user(msg, default) except exception.PromptHelp, err: self.io.print_warning('No help available') except exception.PromptErr, err: raise except exception.CmdErr, err: self.io.print_error(err.getErr()) if line: return line def prompt_redir(self, plugin, var, msg, default): """Prompt for a redirect value and set it in Truantchild""" done = None while not done: try: line = self.io.prompt_user(msg, default) plugin.set(var, line) done = plugin.hasValidValue(var) except exception.PromptHelp, err: self.io.print_warning('No help available') except exception.PromptErr, err: raise except exception.CmdErr, err: self.io.print_error(err.getErr()) return plugin.get(var) def straight_remote(self, r, plugin): params = iDict(plugin.getParameters()) lport = self.conv_param(r.listenport, params) dport = self.conv_param(r.destport, params) laddr = self.conv_param(r.listenaddr, params) if None in (lport, dport, laddr): return # Do we need to choose a random local port? # XXX - This won't happen unless lport is 0 if not lport or lport == "0": lport = rand_port() # Store off the old values so that we can restore them after the # plug-in executes cache = {r.listenaddr : plugin.get(r.listenaddr), r.listenport : plugin.get(r.listenport), r.destport : plugin.get(r.destport)} self.io.print_success("Remote Tunnel - %s" % r.name) try: # Modify the plugin and report success callbackip = self.prompt_redir(plugin, r.listenaddr, 'Listen IP', laddr) callbackport = self.prompt_redir(plugin, r.listenport, 'Listen Port', lport) plugin.set(r.destport, callbackport) self.io.print_success("(%s) Remote %s:%s" % (r.protocol, callbackip, callbackport)) except exception.PromptErr: self.io.print_error("Aborted by user") for (var,val) in cache.items(): try: plugin.set(var, val) except: self.io.print_error("Error setting '%s' - May be in an inconsistent state" % var) raise def straight_local(self, l, plugin): """Effectively just print the straight path to the target""" params = iDict(plugin.getParameters()) laddr = self.conv_param(l.listenaddr, params) lport = self.conv_param(l.listenport, params) if not laddr or not lport: return # HACK HACK # The logic here was previously wrong, which meant that people didn't have to be careful # about their redirection sections. Until we get them fixed, we need a hack that will # allow these invalid redirection sections if we try it the valid way and fail enable_hack = False try: cache = {l.destaddr : plugin.get(l.destaddr), l.destport : plugin.get(l.destport)} laddr = self.conv_param(l.destaddr, params) lport = self.conv_param(l.destport, params) except exception.CmdErr: enable_hack = True cache = {l.destaddr : plugin.get(l.listenaddr), l.destport : plugin.get(l.listenport)} self.io.print_success("Local Tunnel - %s" % l.name) try: if not enable_hack: targetip = self.prompt_redir(plugin, l.destaddr, 'Destination IP', laddr) targetport = self.prompt_redir(plugin, l.destport, 'Destination Port', lport) self.io.print_success("(%s) Local %s:%s" % (l.protocol, targetip, targetport)) else: targetip = self.prompt_redir(plugin, l.listenaddr, 'Destination IP', laddr) targetport = self.prompt_redir(plugin, l.listenport, 'Destination Port', lport) self.io.print_success("(%s) Local %s:%s" % (l.protocol, targetip, targetport)) except exception.PromptErr: self.io.print_error("Aborted by user") for (var,val) in cache.items(): try: plugin.set(var, val) except: self.io.print_error("Error setting '%s' - May be in an inconsistent state" % var) raise except Exception as e: self.io.print_error("Error: {0}".format(str(type(e)))) def redirect_remote(self, r, plugin, session_data): """(destaddr, destport) = r-xform(listenaddr, listenport) * Each of the identifiers above specifies a variable for the plug-in (1) Prompt for Listen IP - Likely the ultimate redirector's IP (2) Prompt for Listen Port - Likely the ultimate redirector's port (3) Prompt for Destination - Likely 0.0.0.0 (4) Prompt for Destination Port - Likely a local port Lookup the variables specified by listenaddr and listenport, transform them with a given transform function, and substitute the resulting values into the variables specified by destaddr and destport. The plug-in will then have to open a port to listen on using the variables specified by the destnation IP and destination port """ params = iDict(plugin.getParameters()) lport = self.conv_param(r.listenport, params, session_data['params']) dport = self.conv_param(r.destport, params, session_data['params']) laddr = self.conv_param(r.listenaddr, params, session_data['params']) daddr = self.conv_param(r.destaddr, params, session_data['params']) if None in (lport, dport, laddr, daddr): for p,n in (laddr, r.listenaddr), (lport, r.listenport), (daddr, r.destaddr), (dport, r.destport): if p == None: self.io.print_warning("Parameter %s referenced by tunnel %s not found. This tunnel will " "be ignored" % (n, r.name)) return if not lport or lport == "0": lport = rand_port() self.io.print_success("Remote Tunnel - %s" % r.name) # # Prompt the user for the listenaddr and listenport # callbackip = self.prompt_redir(plugin, r.listenaddr, 'Listen IP', laddr) callbackport = self.prompt_redir(plugin, r.listenport, 'Listen Port', lport) # # Do the substitution # session_data['params'][r.listenaddr] = callbackip session_data['params'][r.listenport] = callbackport # Get the other end of the tunnel, where the connection will eventually be made. # This will likely be, but does not have to be, the local workstation callbacklocalip = self.prompt_redir_fake('Destination IP', daddr) if not dport: dport = callbackport callbacklocalport = self.prompt_redir(plugin, r.destport, 'Destination Port', dport) session_data['params'][r.destport] = callbacklocalport session_data['remote'].append(RemoteRedirection(r.protocol, callbackip, callbacklocalport, listenport=callbackport, destaddr=callbacklocalip, name=r.name)) self.io.print_success("(%s) Remote %s:%s -> %s:%s" % (r.protocol, callbackip, callbackport, callbacklocalip, callbacklocalport)) def redirect_local(self, l, plugin, session_data): """ targetip = Destination IP (on the target) targetport = Destination Port (on the target) redirip = IP of the LP redirport = Port on the LP """ # listenaddr - name of variable containing the LP IP # listenport - name of variable containing the LP Port # destaddr - name of variable containing the Target IP # destport - name of variable containing the Target Port # targetip - IP of the target # targetport - Port of the target # redirip - IP of the LP # redirport - Port of the LP params = iDict(plugin.getParameters()) # Get the defaults for the user prompt laddr = self.conv_param(l.listenaddr, params, session_data['params']) lport = self.conv_param(l.listenport, params, session_data['params']) daddr = self.conv_param(l.destaddr, params, session_data['params']) dport = self.conv_param(l.destport, params, session_data['params']) if None in (laddr, lport, daddr, dport): for p,n in (laddr, l.listenaddr), (lport, l.listenport), (daddr, l.destaddr), (dport, l.destport): if p == None: self.io.print_warning("Parameter %s referenced by tunnel %s not found. This tunnel will " "be ignored" % (n, l.name)) return self.io.print_success("Local Tunnel - %s" % l.name) # # Get the destination IP and port for the target # targetip = self.prompt_redir_fake('Destination IP', daddr) targetport = self.prompt_redir_fake('Destination Port', dport) # # Get the redirection addresses # redirip = self.prompt_redir(plugin, l.listenaddr, 'Listen IP', '127.0.0.1') if not dport: dport = targetport redirport = self.prompt_redir(plugin, l.listenport, 'Listen Port', lport) # # # session_data['params'][l.listenaddr] = targetip session_data['params'][l.listenport] = targetport # # Record the redirection tunnel # session_data['local'].append(LocalRedirection(l.protocol, redirip, redirport, targetip, targetport, name=l.name)) self.io.print_success("(%s) Local %s:%s -> %s:%s" % (l.protocol, redirip, redirport, targetip, targetport)) def config_redirect(self, plugin, do_redir): """Configure whether the plug-in should perform redirection plugin - An instance of a plugin do_redir - Should we do redirection? (True or False)""" redir = plugin.getRedirection() # Make a new session dictionary here session_data = { 'params' : {}, # 'remote' : [], # 'local' : [] # } if do_redir: id = uuid.uuid4() else: id = 0 try: self.io.newline() self.io.print_success("Configure Plugin Local Tunnels") for l in redir['local']: if do_redir: self.redirect_local(l, plugin, session_data) else: self.straight_local(l, plugin) self.io.newline() self.io.print_success("Configure Plugin Remote Tunnels") for r in redir['remote']: if do_redir: self.redirect_remote(r, plugin, session_data) else: self.straight_remote(r, plugin) except exception.PromptErr: for key,val in session_data['params'].items(): plugin.set(key, val) raise self.io.newline() # Store info into the cache so that we can restore it in post_exec if id: self.session_cache[id] = session_data return id
DarthMaulware/EquationGroupLeaks
Leak #5 - Lost In Translation/windows/fuzzbunch/redirection.py
Python
unlicense
20,247
#!/usr/bin/env python # -*- coding: utf-8 -*- """Mendel's First Law Usage: IPRB.py <input> IPRB.py (--help | --version) Options: -h --help show this help message and exit -v --version show version and exit """ problem_description = """Mendel's First Law Problem Probability is the mathematical study of randomly occurring phenomena. We will model such a phenomenon with a random variable, which is simply a variable that can take a number of different distinct outcomes depending on the result of an underlying random process. For example, say that we have a bag containing 3 red balls and 2 blue balls. If we let X represent the random variable corresponding to the color of a drawn ball, then the probability of each of the two outcomes is given by Pr(X=red)=35 and Pr(X=blue)=25. Random variables can be combined to yield new random variables. Returning to the ball example, let Y model the color of a second ball drawn from the bag (without replacing the first ball). The probability of Y being red depends on whether the first ball was red or blue. To represent all outcomes of X and Y, we therefore use a probability tree diagram. This branching diagram represents all possible individual probabilities for X and Y, with outcomes at the endpoints ("leaves") of the tree. The probability of any outcome is given by the product of probabilities along the path from the beginning of the tree; see Figure 2 for an illustrative example. An event is simply a collection of outcomes. Because outcomes are distinct, the probability of an event can be written as the sum of the probabilities of its constituent outcomes. For our colored ball example, let A be the event "Y is blue." Pr(A) is equal to the sum of the probabilities of two different outcomes: Pr(X=blue and Y=blue)+Pr(X=red and Y=blue), or 310+110=25 (see Figure 2 above). Given: Three positive integers k, m, and n, representing a population containing k+m+n organisms: k individuals are homozygous dominant for a factor, m are heterozygous, and n are homozygous recessive. Return: The probability that two randomly selected mating organisms will produce an individual possessing a dominant allele (and thus displaying the dominant phenotype). Assume that any two organisms can mate. Sample Dataset 2 2 2 Sample Output 0.78333 """ from docopt import docopt def get_k_m_n(inp_file): with open(inp_file, 'r') as inp: k, m, n = inp.readline().strip().split(' ') return float(k), float(m), float(n) #TODO: Write elegant, general solution to "marbles-in-jar problem" def calculate(k, m, n): first_pop = k + m + n second_pop = first_pop - 1 kk = k / first_pop * (k - 1) / second_pop km = k / first_pop * (m) / second_pop + m / first_pop * (k) / second_pop kn = k / first_pop * (n) / second_pop + n / first_pop * (k) / second_pop mm = m / first_pop * (m - 1) / second_pop mn = m / first_pop * (n) / second_pop + n / first_pop * (m) / second_pop nn = n / first_pop * (n - 1) / second_pop return kk, km, kn, mm, mn, nn def main(): k, m, n = get_k_m_n(arguments['<input>']) #k is homozygous dominant, m heterozygous, and n is homozygous recessive #There are 6 possible combinations of parentage, though some may not be #possible if there are only 1 individuals of a type kk, km, kn, mm, mn, nn = calculate(k, m, n) certain = kk + km + kn three_quarter = 0.75 * mm half = 0.5 * mn print(certain + three_quarter + half) if __name__ == '__main__': arguments = docopt(__doc__, version='0.0.1') main()
SavinaRoja/challenges
Rosalind/Heredity/IPRB.py
Python
unlicense
3,585
<!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" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Email Helper : CodeIgniter User Guide</title> <style type='text/css' media='all'>@import url('../userguide.css');</style> <link rel='stylesheet' type='text/css' media='all' href='../userguide.css' /> <script type="text/javascript" src="../nav/nav.js"></script> <script type="text/javascript" src="../nav/prototype.lite.js"></script> <script type="text/javascript" src="../nav/moo.fx.js"></script> <script type="text/javascript" src="../nav/user_guide_menu.js"></script> <meta http-equiv='expires' content='-1' /> <meta http-equiv= 'pragma' content='no-cache' /> <meta name='robots' content='all' /> <meta name='author' content='ExpressionEngine Dev Team' /> <meta name='description' content='CodeIgniter User Guide' /> </head> <body> <!-- START NAVIGATION --> <div id="nav"><div id="nav_inner"><script type="text/javascript">create_menu('../');</script></div></div> <div id="nav2"><a name="top"></a><a href="javascript:void(0);" onclick="myHeight.toggle();"><img src="../images/nav_toggle_darker.jpg" width="154" height="43" border="0" title="Toggle Table of Contents" alt="Toggle Table of Contents" /></a></div> <div id="masthead"> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td><h1>CodeIgniter User Guide Version 2.1.3</h1></td> <td id="breadcrumb_right"><a href="../toc.html">Table of Contents Page</a></td> </tr> </table> </div> <!-- END NAVIGATION --> <!-- START BREADCRUMB --> <table cellpadding="0" cellspacing="0" border="0" style="width:100%"> <tr> <td id="breadcrumb"> <a href="http://codeigniter.com/">CodeIgniter Home</a> &nbsp;&#8250;&nbsp; <a href="../index.html">User Guide Home</a> &nbsp;&#8250;&nbsp; Email Helper </td> <td id="searchbox"><form method="get" action="http://www.google.com/search"><input type="hidden" name="as_sitesearch" id="as_sitesearch" value="codeigniter.com/user_guide/" />Search User Guide&nbsp; <input type="text" class="input" style="width:200px;" name="q" id="q" size="31" maxlength="255" value="" />&nbsp;<input type="submit" class="submit" name="sa" value="Go" /></form></td> </tr> </table> <!-- END BREADCRUMB --> <br clear="all" /> <!-- START CONTENT --> <div id="content"> <h1>Email Helper</h1> <p>The Email Helper provides some assistive functions for working with Email. For a more robust email solution, see CodeIgniter's <a href="../libraries/email.html">Email Class</a>.</p> <h2>Loading this Helper</h2> <p>This helper is loaded using the following code:</p> <p><code>$this->load->helper('email');</code></p> <p>The following functions are available:</p> <h2>valid_email('<var>email</var>')</h2> <p>Checks if an email is a correctly formatted email. Note that is doesn't actually prove the email will recieve mail, simply that it is a validly formed address.</p> <p>It returns TRUE/FALSE</p> <code> $this-&gt;load-&gt;helper('email');<br /> <br /> if (valid_email('email@somesite.com'))<br /> {<br /> &nbsp;&nbsp;&nbsp;&nbsp;echo 'email is valid';<br /> }<br /> else<br /> {<br /> &nbsp;&nbsp;&nbsp;&nbsp;echo 'email is not valid';<br /> }</code> <h2>send_email('<var>recipient</var>', '<var>subject</var>', '<var>message</var>')</h2> <p>Sends an email using PHP's native <a href="http://www.php.net/function.mail">mail()</a> function. For a more robust email solution, see CodeIgniter's <a href="../libraries/email.html">Email Class</a>.</p> </div> <!-- END CONTENT --> <div id="footer"> <p> Previous Topic:&nbsp;&nbsp;<a href="download_helper.html">Download Helper</a> &nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="#top">Top of Page</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; <a href="../index.html">User Guide Home</a>&nbsp;&nbsp;&nbsp;&middot;&nbsp;&nbsp; Next Topic:&nbsp;&nbsp;<a href="file_helper.html">File Helper</a></p> <p><a href="http://codeigniter.com">CodeIgniter</a> &nbsp;&middot;&nbsp; Copyright &#169; 2006 - 2012 &nbsp;&middot;&nbsp; <a href="http://ellislab.com/">EllisLab, Inc.</a></p> </div> </body> </html>
rtyJay14/crowd-farm
web/apps/user_guide/helpers/email_helper.html
HTML
unlicense
4,313
#include "TextHandler.h" TextHandler::TextHandler(const char* filename) : filename(filename) { characters = new std::set<char>(); charactersStatistics = new std::map<char, int>(); numbers = new std::set<char>(); numbersStatistics = new std::map<char, int>(); specialSymbols = new std::set<char>(); specialSymbolsStatistics = new std::map<char, int>(); words = new std::set<std::string>(); wordsStatistics = new std::map<std::string, int>(); quantity = 0; } TextHandler::~TextHandler() { delete characters; delete charactersStatistics; delete numbers; delete numbersStatistics; delete specialSymbols; delete specialSymbolsStatistics; delete words; delete wordsStatistics; } const std::set<char>& TextHandler::getCharacters() const { return *characters; } const std::map<char, int>& TextHandler::getCharactersStatistics() const { return *charactersStatistics; } const std::set<char>& TextHandler::getNumbers() const { return *numbers; } const std::map<char, int>& TextHandler::getNumbersStatistics() const { return *numbersStatistics; } const std::set<char>& TextHandler::getSpecialSymbols() const { return *specialSymbols; } const std::map<char, int>& TextHandler::getSpecialSymbolsStatistics() const { return *specialSymbolsStatistics; } const std::set<std::string>& TextHandler::getWords() const { return *words; } const std::map<std::string, int>& TextHandler::getWordsStatistics() const { return *wordsStatistics; } long long TextHandler::getQuantity() const { return quantity; } void TextHandler::insert(char symbol, std::set<char>* lst) { lst->insert(symbol); } void TextHandler::insert(std::string word, std::set<std::string>* lst) { lst->insert(word); } void TextHandler::insert(char symbol, std::map<char, int>* lst) { if ( lst->find(symbol) == lst->end() ) { lst->insert(std::pair<char, int>(symbol, 0)); } lst->at(symbol) += 1; } void TextHandler::insert(std::string word, std::map<std::string, int>* lst) { if ( lst->find(word) == lst->end() ) { lst->insert(std::pair<std::string, int>(word, 0)); } lst->at(word) += 1; } bool TextHandler::isLetter(char symbol) { return ( symbol >= 'A' && symbol <= 'Z' ) || ( symbol >= 'a' && symbol <= 'z' ); } bool TextHandler::isNumber(char symbol) { return symbol >= '0' && symbol <= '9'; } bool TextHandler::isSpecial(char symbol) { bool special = false; if ( ( symbol > ' ' && symbol < '0' ) || ( symbol > '9' && symbol < 'A' ) ) { special = true; } if ( ( symbol > 'Z' && symbol < 'a' ) || ( symbol > 'z' && symbol <= '~' ) ) { special = true; } return special; } void TextHandler::parseText() { std::ifstream file(filename); int diff = 'a' - 'A'; char symbol; std::string word; for ( ; file.get(symbol) ; ) { if ( isLetter(symbol) ) { if ( symbol < 'a' ) { symbol += diff; } insert(symbol, characters); insert(symbol, charactersStatistics); quantity += 1; } if ( isNumber(symbol) ) { insert(symbol, numbers); insert(symbol, numbersStatistics); quantity += 1; } if ( isSpecial(symbol) ) { insert(symbol, specialSymbols); insert(symbol, specialSymbolsStatistics); quantity += 1; } if ( isLetter(symbol) ) { word += symbol; } else { if (symbol == ' ') { insert(word, words); insert(word, wordsStatistics); word.clear(); } } } file.close(); } std::ostream& operator<<(std::ostream& out, const TextHandler& handler) { out << "Symbols found: " << handler.getQuantity() << std::endl; out << "Letters statistic:" << std::endl; out << "Unique: " << handler.getCharacters() << std::endl; out << "Matches in text: " << std::endl; out << handler.getCharactersStatistics() << std::endl; out << "Numbers statistic:" << std::endl; out << "Unique: " << handler.getNumbers() << std::endl; out << "Matches in text: " << std::endl; out << handler.getNumbersStatistics() << std::endl; out << "Special symbols statistic:" << std::endl; out << "Unique: " << handler.getSpecialSymbols() << std::endl; out << "Matches in text: " << std::endl; out << handler.getSpecialSymbolsStatistics() << std::endl; out << "Words statistic:" << std::endl; out << "Unique: " << handler.getWords() << std::endl; out << "Matches in text: " << std::endl; out << handler.getWordsStatistics() << std::endl; return out; }
KozyrOK/Study
5week/statistic/TextHandler.cpp
C++
unlicense
4,781
-- http://stackoverflow.com/questions/20849893/how-to-plot-a-graph-using-haskell-graphviz {-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE OverloadedStrings #-} {- Created : 2014 Feb 26 (Wed) 18:54:30 by Harold Carr. Last Modified : 2014 Feb 28 (Fri) 17:10:45 by Harold Carr. This prints the dot versions for the examples in Data.Graph.Inductive.Example. -} module E1 where import Control.Monad (forM_) import Data.Graph.Inductive.Example import Data.Graph.Inductive.Graph (Graph (..)) import Data.GraphViz (graphToDot, nonClusteredParams, toDot) import Data.GraphViz.Printing (renderDot) import Data.Text.Lazy (unpack) showDot :: (Show (gr l el), Graph gr) => (String, gr l el) -> IO () showDot (s,g) = do putStrLn "--------------------------------------------------" putStrLn s putStrLn $ show g putStrLn "" putStrLn $ unpack $ renderDot $ toDot $ graphToDot nonClusteredParams g mapShowDot :: (Show (gr l el), Graph gr) => [(String, gr l el)] -> IO () mapShowDot xs = forM_ xs showDot main :: IO () main = do mapShowDot [("a",a),("b",b),("c",c),("e",e),("loop",loop),("ab",ab),("abb",abb),("dag3",dag3)] mapShowDot [("e3",e3)] mapShowDot [("cyc3",cyc3),("g3",g3),("g3b",g3b)] mapShowDot [("dag4",dag4)] mapShowDot [("d1",d1),("d3",d3)] mapShowDot [("clr479",clr479),("clr489",clr489)] mapShowDot [("clr486",clr486)] mapShowDot [("clr508",clr508),("clr528",clr528)] mapShowDot [("clr595",clr595),("gr1",gr1)] mapShowDot [("kin248",kin248)] mapShowDot [("vor",vor)] -- End of file.
haroldcarr/learn-haskell-coq-ml-etc
haskell/paper/haroldcarr/2014-02-28-using-graphviz-via-haskell/e1.hs
Haskell
unlicense
1,767
module WinCommon module Errors module HRESULT # Defined in winerror.h S_OK = 0x00000000 S_FALSE = 0x00000001 E_PENDING = 0x8000000A E_BOUNDS = 0x8000000B E_CHANGED_STATE = 0x8000000C E_ILLEGAL_STATE_CHANGE = 0x8000000D E_ILLEGAL_METHOD_CALL = 0x8000000E RO_E_METADATA_NAME_NOT_FOUND = 0x8000000F RO_E_METADATA_NAME_IS_NAMESPACE = 0x80000010 RO_E_METADATA_INVALID_TYPE_FORMAT = 0x80000011 RO_E_INVALID_METADATA_FILE = 0x80000012 RO_E_CLOSED = 0x80000013 RO_E_EXCLUSIVE_WRITE = 0x80000014 RO_E_CHANGE_NOTIFICATION_IN_PROGRESS = 0x80000015 RO_E_ERROR_STRING_NOT_FOUND = 0x80000016 E_STRING_NOT_NULL_TERMINATED = 0x80000017 E_ILLEGAL_DELEGATE_ASSIGNMENT = 0x80000018 E_ASYNC_OPERATION_NOT_STARTED = 0x80000019 E_APPLICATION_EXITING = 0x8000001A E_APPLICATION_VIEW_EXITING = 0x8000001B RO_E_MUST_BE_AGILE = 0x8000001C RO_E_UNSUPPORTED_FROM_MTA = 0x8000001D RO_E_COMMITTED = 0x8000001E RO_E_BLOCKED_CROSS_ASTA_CALL = 0x8000001F E_NOTIMPL = 0x80004001 E_NOINTERFACE = 0x80004002 E_POINTER = 0x80004003 E_ABORT = 0x80004004 E_FAIL = 0x80004005 E_UNEXPECTED = 0x8000FFFF E_PATH_NOT_FOUND = 0x80070003 E_ACCESSDENIED = 0x80070005 E_HANDLE = 0x80070006 E_INVALID_DATA = 0x8007000D E_OUTOFMEMORY = 0x8007000E E_INVALIDARG = 0x80070057 module SEVERITY SUCCESS = 0 ERROR = 1 end def self.toUnsigned(hresult) hresult += 0x1_0000_0000 if (hresult < 0) hresult end def self.Compare(error, code) error = toUnsigned(error) error <=> code end def self.Equal?(error, codes) [*codes].include?(toUnsigned(error)) end def self.ErrorIfEqual(error, code) raise HRESULTError.new(error) if Equal?(error, code) end def self.GetSeverity(hresult) (toUnsigned(hresult) >> 31) & 0x01 end def self.GetFacility(hresult) (toUnsigned(hresult) >> 16) & 0x1FFF end def self.GetCode(hresult) toUnsigned(hresult) & 0x0000FFFF end def self.IsSuccess?(hresult) GetSeverity(hresult) == SEVERITY::SUCCESS end def self.IsError?(hresult) GetSeverity(hresult) == SEVERITY::ERROR end def self.GetName(hresult) hresult = toUnsigned(hresult) constants(true).each do |name| if const_get(name) == hresult return name.to_s end end if IsSuccess?(hresult) 'UKNOWN_SUCCESS' else 'UKNOWN_ERROR' end end def self.GetNameCode(hresult) code = HRESULT.toUnsigned(hresult) HRESULT.GetName(code) + " [0x%08X]" % code end end class HRESULTError < WinCommonError attr_reader :code def initialize(hr) @code = HRESULT.toUnsigned(hr) super(HRESULT.GetNameCode(@code)) end end end end
davispuh/WinCommon
lib/win_common/errors/hresult.rb
Ruby
unlicense
4,356
INF PINF BADR BASEADDR HURP ZURP 0x12 EPINF EINF ; This program reads in integers and adds them together ; until a negative number is read in. Then it outputs ; the sum (not including the last number). ;Start: read ; read n -> acc ; jmpn Done ; jump to Done if n < 0. ; add sum ; add sum to the acc ; store sum ; store the new sum ; jump Start ; go back & read in next number ;Done: load sum ; load the final sum ; write ; write the final sum ; stop ; stop ; ;sum: .data 2 0 ; 2-byte location where sum is stored ;; START NIbble-Knowledge code ;; ;; Instruction Section ;; Start: LOD n15 ADD n2 NND n15 NOP CXA JMP Jump STR sum Jump: HLT ;; Data Section ;; n0: .data 1 0 ; b0000 n1: .data 1 1 ; b0001 n2: .data 1 2 ; b0010 n3: .data 1 3 ; b0011 n4: .data 1 4 ; b0100 n5: .data 1 5 ; b0101 n6: .data 1 6 ; b0110 n7: .data 1 7 ; b0111 n8: .data 1 8 ; b1000 n9: .data 1 9 ; b1001 n10: .data 1 10 ; b1010 n11: .data 1 11 ; b1011 n12: .data 1 12 ; b1100 n13: .data 1 13 ; b1101 n14: .data 1 14 ; b1110 n15: .data 1 15 ; b1111 derp: .data 6 0x454534 derp3: .ascii "hey there" derp4: .ascii "hey\" there\n" derp5: .asciiz "hey there" derp6: .asciiz "hey\" there\n" long: .asciiz "This is a very long string with a \"few\" escape characters\nI hope it \"works\"" sum: .data 1 0
Nibble-Knowledge/label-replacer
examples/asm/derp.asm
Assembly
unlicense
1,336
package org.dwquerybuilder.builders.query.helpers; import org.apache.commons.lang.NotImplementedException; import org.dwquerybuilder.data.ComputedColumn; import org.dwquerybuilder.data.ComputedColumnOperation; import org.dwquerybuilder.data.SelectColumn; import org.dwquerybuilder.data.DwQuery; import org.dwquerybuilder.exceptions.QueryBuilderRuntimeException; import org.jooq.AggregateFunction; import org.jooq.Field; import org.jooq.SelectSelectStep; import static org.jooq.impl.DSL.avg; import static org.jooq.impl.DSL.count; import static org.jooq.impl.DSL.field; import static org.jooq.impl.DSL.fieldByName; import static org.jooq.impl.DSL.max; import static org.jooq.impl.DSL.min; import static org.jooq.impl.DSL.sum; @SuppressWarnings("unchecked") public final class SelectColumnHelper { private static final String WILDCARD = "*"; private SelectColumnHelper() { } public static SelectSelectStep buildSelectColumns(String schemaName, SelectSelectStep selectSelectStep, DwQuery dwQuery) { SelectSelectStep step = selectSelectStep; for (SelectColumn selectColumn : dwQuery.getSelectColumns()) { step = step.select(resolveSelectColumn(schemaName, selectColumn, true, true)); } return selectSelectStep; } public static Field resolveSelectColumn(String schemaName, SelectColumn selectColumn, Boolean useSchemaName, Boolean useAlias) { Field field; if (selectColumn.getComputedColumn().hasOperations() && selectColumn.getComputedColumn().getFieldName().equals(WILDCARD)) { selectColumn.getComputedColumn().getOperations().clear(); } if (selectColumn.getFunction() != null) { field = resolveAggregateFunction(schemaName, selectColumn, useSchemaName); } else { if (WILDCARD.equals(selectColumn.getComputedColumn().getFieldName())) { field = resolveWildcard(schemaName, selectColumn.getComputedColumn(), useSchemaName); } else { field = resolveComputedColumn(schemaName, selectColumn.getComputedColumn(), useSchemaName); } if (selectColumn.hasNullValue()) { field = field.nvl(selectColumn.getNullValue()); } } if (useAlias && selectColumn.hasAlias()) { field = field.as(selectColumn.getAlias()); } return field; } public static Field resolveWildcard(String schemaName, ComputedColumn computedColumn, Boolean useSchemaName) { if (computedColumn.getTableName() == null && computedColumn.getFieldName().equals(WILDCARD)) { return field(WILDCARD); } else if (computedColumn.getFieldName().equals(WILDCARD)) { if (useSchemaName) { return field("\"" + schemaName + "\".\"" + computedColumn.getTableName() + "\"." + WILDCARD); } else { return field("\"" + computedColumn.getTableName() + "\"." + WILDCARD); } } return null; } public static AggregateFunction resolveAggregateFunction(String schemaName, SelectColumn selectColumn, Boolean useSchemaName) { AggregateFunction aggregateFunction; if (selectColumn.getComputedColumn().getFieldName().equals(WILDCARD)) { aggregateFunction = buildSelectColumnFunctionForWildcard(schemaName, selectColumn, useSchemaName); } else { aggregateFunction = buildSelectColumnFunction(schemaName, selectColumn, useSchemaName); } return aggregateFunction; } public static Field resolveComputedColumn(String schemaName, ComputedColumn computedColumn, Boolean useSchemaName) { Field field; if (useSchemaName) { field = fieldByName(schemaName, computedColumn.getTableName(), computedColumn.getFieldName()); } else { field = fieldByName(computedColumn.getTableName(), computedColumn.getFieldName()); } if (computedColumn.hasOperations()) { for (ComputedColumnOperation operation : computedColumn.getOperations()) { Field field2 = resolveComputedColumn(schemaName, operation.getComputedColumn(), useSchemaName); switch (operation.getOperatorType()) { case Add: field = field.add(field2); break; case Divide: field = field.divide(field2); break; case Multiply: field = field.multiply(field2); break; case Subtract: field = field.subtract(field2); break; default: break; } } } return field; } public static AggregateFunction buildSelectColumnFunction(String schemaName, SelectColumn selectColumn, Boolean useSchemaName) { try { Field field = resolveComputedColumn(schemaName, selectColumn.getComputedColumn(), useSchemaName); if (selectColumn.hasNullValue()) { field = field.nvl(selectColumn.getNullValue()); } switch (selectColumn.getFunction()) { case Average: return avg(field); case Count: return count(field); case Max: return max(field); case Min: return min(field); case Sum: return sum(field); default: throw new NotImplementedException(); } } catch (Exception e) { throw new QueryBuilderRuntimeException(e); } } public static AggregateFunction buildSelectColumnFunctionForWildcard(String schemaName, SelectColumn selectColumn, Boolean useSchemaName) { try { switch (selectColumn.getFunction()) { case Count: return count(resolveWildcard(schemaName, selectColumn.getComputedColumn(), useSchemaName)); default: throw new NotImplementedException(); } } catch (Exception e) { throw new QueryBuilderRuntimeException(e); } } }
lrozanski/dwquerybuilder
src/main/java/org/dwquerybuilder/builders/query/helpers/SelectColumnHelper.java
Java
unlicense
7,087
package bronz.accounting.bunk.ui.product.model; import java.math.BigDecimal; import java.math.RoundingMode; import java.util.List; import bronz.accounting.bunk.products.model.ProductClosingBalance; import bronz.utilities.custom.CustomDecimal; import bronz.utilities.swing.table.DataTable; import bronz.utilities.swing.table.DataTableField; @DataTable( fixNoOfRows=true, uniqueIdCol=true ) public class FuelSalesProdDetailBean { @DataTableField( columnName="PRODUCT", preferedWidth=28, allowNull=false, columnNum=0, isEditable=false) private ProductClosingBalance product; //@DataTableField( columnName="RATE", preferedWidth=10, allowNull=false, columnNum=1, isEditable=false) private BigDecimal rate = new CustomDecimal( 0 ); @DataTableField( columnName="TOTAL", preferedWidth=10, allowNull=false, columnNum=1, isEditable=false) private BigDecimal totalSaleAmt = new CustomDecimal( 0 ); @DataTableField( columnName="TOTAL CASH", preferedWidth=14, allowNull=false, columnNum=2, isEditable=false) private BigDecimal totalSaleCash = new CustomDecimal( 0 ); @DataTableField( columnName="SALE", preferedWidth=10, allowNull=false, columnNum=3, isEditable=false) private BigDecimal saleAmt = new CustomDecimal( 0 ); @DataTableField( columnName="SALE CASH", preferedWidth=14, allowNull=false, columnNum=4, isEditable=false) private BigDecimal saleCash = new CustomDecimal( 0 ); @DataTableField( columnName="TEST", preferedWidth=10, allowNull=false, columnNum=5, isEditable=false) private BigDecimal testAmt = new CustomDecimal( 0 ); @DataTableField( columnName="TEST CASH", preferedWidth=14, allowNull=false, columnNum=6, isEditable=false) private BigDecimal testCash = new CustomDecimal( 0 ); private final List<TankSaleDetailBean> tankList; public FuelSalesProdDetailBean( final ProductClosingBalance product, final List<TankSaleDetailBean> tankList ) { super(); this.tankList = tankList; this.setProduct( product ); } public ProductClosingBalance getProduct() { return product; } public void setProduct( final ProductClosingBalance product ) { this.product = product; if ( null != product ) { this.rate = product.getUnitSellingPrice().setScale( 2, RoundingMode.HALF_UP ); } } /** * @return the rate */ public BigDecimal getRate() { return rate; } /** * @param rate the rate to set */ public void setRate( BigDecimal rate ) { this.rate = rate.setScale( 2, RoundingMode.HALF_UP ); } /** * @return the saleAmt */ public BigDecimal getSaleAmt() { return saleAmt; } /** * @param saleAmt the saleAmt to set */ public void setSaleAmt( BigDecimal saleAmt ) { this.saleAmt = saleAmt.setScale( 3, RoundingMode.HALF_UP ); } /** * @return the saleCash */ public BigDecimal getSaleCash() { return saleCash; } /** * @param saleCash the saleCash to set */ public void setSaleCash( BigDecimal saleCash ) { this.saleCash = saleCash.setScale( 2, RoundingMode.HALF_UP ); } /** * @return the testAmt */ public BigDecimal getTestAmt() { return testAmt; } /** * @param testAmt the testAmt to set */ public void setTestAmt( BigDecimal testAmt ) { this.testAmt = testAmt.setScale( 3, RoundingMode.HALF_UP ); } /** * @return the testCash */ public BigDecimal getTestCash() { return testCash; } /** * @param testCash the testCash to set */ public void setTestCash( BigDecimal testCash ) { this.testCash = testCash.setScale( 2, RoundingMode.HALF_UP ); } /** * @return the tankList */ public List<TankSaleDetailBean> getTankList() { return tankList; } /** * @return the totalSaleAmt */ public BigDecimal getTotalSaleAmt() { if ( null != this.tankList ) { BigDecimal sale = new BigDecimal( 0 ); BigDecimal test = new BigDecimal( 0 ); BigDecimal total = new BigDecimal( 0 ); for ( TankSaleDetailBean bean : this.tankList ) { sale = sale.add( bean.getSaleAmt() ); test = test.add( bean.getTest() ); total = total.add( bean.getTotalSale() ); } this.saleAmt = sale.setScale( 3, RoundingMode.HALF_UP ); this.saleCash = sale.multiply( this.rate ).setScale( 2, RoundingMode.HALF_UP ); this.testAmt = test.setScale( 3, RoundingMode.HALF_UP ); this.testCash = test.multiply( this.rate ).setScale( 2, RoundingMode.HALF_UP ); this.totalSaleAmt = total.setScale( 3, RoundingMode.HALF_UP ); this.totalSaleCash = total.multiply( this.rate ).setScale( 2, RoundingMode.HALF_UP ); } return totalSaleAmt.setScale( 3, RoundingMode.HALF_UP ); } /** * @param totalSaleAmt the totalSaleAmt to set */ public void setTotalSaleAmt( BigDecimal totalSaleAmt ) { this.totalSaleAmt = totalSaleAmt.setScale( 3, RoundingMode.HALF_UP ); } /** * @return the totalSaleCash */ public BigDecimal getTotalSaleCash() { return totalSaleCash; } /** * @param totalSaleCash the totalSaleCash to set */ public void setTotalSaleCash( BigDecimal totalSaleCash ) { this.totalSaleCash = totalSaleCash.setScale( 2, RoundingMode.HALF_UP ); } }
robbinmathew/centbunk
java/BunkAccountingApplication/BunkAccountingSwingApp/src/main/java/bronz/accounting/bunk/ui/product/model/FuelSalesProdDetailBean.java
Java
unlicense
5,710
# Shortcodes A Python library for parsing customizable WordPress-style shortcodes. * [Documentation](http://www.dmulholl.com/dev/shortcodes.html)
dmulholland/shortcodes
readme.md
Markdown
unlicense
148
using Pms.Business.Contracts; using Pms.Model; namespace Pms.Business.Models { public class PmsWorkbench { public PmsWorkbench(IProvideTable tableProvider) { TableProvider = tableProvider; } public IProvideTable TableProvider { get; set; } public Waiter Waiter { get; set; } } }
Slesa/Poseidon
old/src/2nd/Pms.Business/Models/PmsWorkbench.cs
C#
unlicense
348
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html lang="pt" xml:lang="pt" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <head> <META http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Task: Criar os Casos de Teste</title> <meta name="uma.type" content="Task"> <meta name="uma.name" content="create_test_cases"> <meta name="uma.presentationName" content="Criar os Casos de Teste"> <meta name="uma.category" content="Discipline:test:Teste"> <meta name="element_type" content="activity"> <meta name="filetype" content="description"> <meta name="role" content="Testador"> <link rel="StyleSheet" href="./../../css/default.css" type="text/css"> <script src="./../../scripts/ContentPageResource.js" type="text/javascript" language="JavaScript"></script><script src="./../../scripts/ContentPageSection.js" type="text/javascript" language="JavaScript"></script><script src="./../../scripts/ContentPageSubSection.js" type="text/javascript" language="JavaScript"></script><script src="./../../scripts/ContentPageToolbar.js" type="text/javascript" language="JavaScript"></script><script src="./../../scripts/contentPage.js" type="text/javascript" language="JavaScript"></script><script type="text/javascript" language="JavaScript"> var backPath = './../../'; var imgPath = './../../images/'; var nodeInfo=null; contentPage.preload(imgPath, backPath, nodeInfo, '', true, false, false); </script> </head> <body> <div id="breadcrumbs"></div> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td valign="top"> <div id="page-guid" value="_0iwc0clgEdmt3adZL5Dmdw"></div> <table border="0" cellspacing="0" cellpadding="0" width="100%"> <tr> <td class="pageTitle" nowrap="true">Task: Criar os Casos de Teste</td><td width="100%"> <div align="right" id="contentPageToolbar"></div> </td><td width="100%" class="expandCollapseLink" align="right"><a name="mainIndex" href="./../../index.htm"></a><script language="JavaScript" type="text/javascript" src="./../../scripts/treebrowser.js"></script></td> </tr> </table> <table width="100%" border="0" cellpadding="0" cellspacing="0"> <tr> <td class="pageTitleSeparator"><img src="./../../images/shim.gif" alt="" title="" height="1"></td> </tr> </table> <div class="overview"> <table width="97%" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="50"><img src="./../../images/task.gif" alt="" title=""></td><td> <table class="overviewTable" border="0" cellspacing="0" cellpadding="0"> <tr> <td valign="top">Desenvolver os casos de teste e os dados de teste para os requisitos a serem testados.</td> </tr> <tr> <td>Disciplines: <a href="./../../openup/disciplines/test_FB85069.html" guid="_0TkKQMlgEdmt3adZL5Dmdw">Teste</a></td> </tr> </table> </td> </tr> </table> </div> <div class="sectionHeading">Purpose</div> <div class="sectionContent"> <table class="sectionTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td class="sectionTableSingleCell"><p>Para alcançar um entendimento comum das condições específicas que a solução deve satisfazer.</p></td> </tr> </table> </div> <div class="sectionHeading">Relationships</div> <div class="sectionContent"> <table class="sectionTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <th class="sectionTableHeading" scope="row">Roles</th><td class="sectionTableCell" width="42%"><span class="sectionTableCellHeading">Primary Performer: </span> <ul> <li> <a href="./../../openup/roles/tester_9859B590.html" guid="_0ZM4MclgEdmt3adZL5Dmdw">Testador</a> </li> </ul> </td><td class="sectionTableCell"><span class="sectionTableCellHeading">Additional Performers: </span> <ul> <li> <a href="./../../openup/roles/analyst_39D7C49B.html" guid="_0VxJsMlgEdmt3adZL5Dmdw">Analista</a> </li> <li> <a href="./../../openup/roles/developer_C633AB7.html" guid="_0YDosMlgEdmt3adZL5Dmdw">Desenvolvedor</a> </li> <li> <a href="./../../openup/roles/stakeholder_9FFD4106.html" guid="_dTa6gMAYEdqX-s4mWhkyqQ">Stakeholder</a> </li> </ul> </td> </tr> <tr valign="top"> <th class="sectionTableHeading" scope="row">Inputs</th><td class="sectionTableCell" width="42%"><span class="sectionTableCellHeading">Mandatory: </span> <ul> <li> <a href="./../../openup/workproducts/use_case_22BE66E2.html" guid="_0VGbUMlgEdmt3adZL5Dmdw">Caso de Uso</a> </li> </ul> <ul></ul> </td><td class="sectionTableCell"><span class="sectionTableCellHeading">Optional: </span> <ul> <li> <a href="./../../openup/workproducts/test_case_335C5DEA.html" guid="_0ZS-0MlgEdmt3adZL5Dmdw">Caso de Teste</a> </li> <li> <a href="./../../openup/workproducts/supporting_requirements_spec_7D9DD47C.html" guid="_BVh9cL-CEdqb7N6KIeDL8Q">Especifica&ccedil;&atilde;o de Requisitos Suplementares</a> </li> </ul> <ul></ul> </td> </tr> <tr valign="top"> <th class="sectionTableHeading" scope="row">Outputs</th><td class="sectionTableCell" colspan="2"> <ul> <li> <a href="./../../openup/workproducts/test_case_335C5DEA.html" guid="_0ZS-0MlgEdmt3adZL5Dmdw">Caso de Teste</a> </li> </ul> <ul></ul> </td> </tr> </table> </div> <div class="sectionHeading">Steps</div> <div class="sectionContent"> <table class="sectionTable" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="sectionTableSingleCell"> <div class="stepHeading">Revise os requisitos a serem testados</div> <div class="stepContent"> <table class="stepTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td><p>Trabalhe com o <a class="elementLink" href="./../../openup/roles/analyst_39D7C49B.html" guid="_0VxJsMlgEdmt3adZL5Dmdw">Analista</a> e o <a class="elementLink" href="./../../openup/roles/developer_C633AB7.html" guid="_0YDosMlgEdmt3adZL5Dmdw">Desenvolvedor</a> para identificar quais cenários necessitam de novos ou adicionais casos de teste. Revise o <a class="elementLink" href="./../../openup/workproducts/iteration_plan_B46FED39.html" guid="_0aQBEslgEdmt3adZL5Dmdw">Plano de Iteração</a> para assegurar que você entendeu o escopo de desenvolvimento para a iteração corrente.<br /> </p></td> </tr> </table> </div> <div class="stepHeading">Identifique Casos de Teste relevantes</div> <div class="stepContent"> <table class="stepTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td><p>Identifique os caminhos nos cenários como condições únicas de teste. Considere os caminhos alternativos ou de exceções com perspectivas positivas e negativas.</p> <p>Discuta o requisito com o <a class="elementLink" href="./../../openup/roles/stakeholder_9FFD4106.html" guid="_dTa6gMAYEdqX-s4mWhkyqQ">Stakeholder</a> para identificar outras condições de satisfação para os requisitos.</p> <p>Relacione cada caso de teste com um nome único que identifique a condição que ele avalia ou o resultado esperado.</p></td> </tr> </table> </div> <div class="stepHeading">Descreva os Casos de Teste</div> <div class="stepContent"> <table class="stepTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td><p>Para cada caso de teste, escreva uma descrição resumida com um resultado esperado. Assegure-se que um leitor casual possa entender claramente a diferença entre os casos de teste. Anote as precondições e pós-condições lógicas que se aplicam a cada caso de teste. Opcionalmente, descreva os passos para o caso de teste.</p> <p>Verifique que os casos de teste satisfaçam as diretrizes da <a class="elementLinkWithType" href="./../../openup/guidances/checklists/test_case_9D3F2E96.html" guid="_0Zxf8MlgEdmt3adZL5Dmdw">Checklist: Caso de Teste</a>.</p> <p>Para mais informações sobre casos de teste, veja <a class="elementLinkWithType" href="./../../openup/guidances/templates/test_case_A18913A5.html" guid="_0dT8IMlgEdmt3adZL5Dmdw">Template: Caso de Teste</a>.</p></td> </tr> </table> </div> <div class="stepHeading">Identifique os dados de teste necess&aacute;rios</div> <div class="stepContent"> <table class="stepTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td><p>Revise cada caso de teste e anote onde os dados de entrada ou saída possam ser necessários. Identifique o tipo, quantidade e singularidade do dado necessário e adicione essas observações no caso de teste. Concentre-se na articulação dos dados necessários e não na criação de dados específicos.</p> <p>Para mais informações sobre a seleção de dados de teste, veja <a class="elementLinkWithType" href="./../../openup/guidances/checklists/test_case_9D3F2E96.html" guid="_0Zxf8MlgEdmt3adZL5Dmdw">Checklist: Caso de Teste</a>.</p></td> </tr> </table> </div> <div class="stepHeading">Compartilhe e avalie os Casos de Teste</div> <div class="stepContent"> <table class="stepTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td><p>Percorra os casos de teste com o <a class="elementLink" href="./../../openup/roles/analyst_39D7C49B.html" guid="_0VxJsMlgEdmt3adZL5Dmdw">Analista</a> e o <a class="elementLink" href="./../../openup/roles/developer_C633AB7.html" guid="_0YDosMlgEdmt3adZL5Dmdw">Desenvolvedor</a> responsáveis pelo cenário relacionado. Se for possível, o <a class="elementLink" href="./../../openup/roles/stakeholder_9FFD4106.html" guid="_dTa6gMAYEdqX-s4mWhkyqQ">Stakeholder</a> também deve participar.</p> <p>Pergunte aos participantes se eles concordam que <em>se os casos teste passarem</em>, eles considerarão os requisitos implementados. Elicite idéias de teste adicionais do <a class="elementLinkWithType" href="./../../openup/roles/analyst_39D7C49B.html" guid="_0VxJsMlgEdmt3adZL5Dmdw">Role: Analista</a> e do <a class="elementLink" href="./../../openup/roles/stakeholder_9FFD4106.html" guid="_dTa6gMAYEdqX-s4mWhkyqQ">Stakeholder</a> para assegurar que você entendeu o comportamento esperado do cenário.</p> <p>Durante a revisão, assegure-se que:</p> <ul> <li>Os <a class="elementLink" href="./../../openup/workproducts/use_case_22BE66E2.html" guid="_0VGbUMlgEdmt3adZL5Dmdw">Caso de Uso</a> e a <a class="elementLink" href="./../../openup/workproducts/supporting_requirements_spec_7D9DD47C.html" guid="_BVh9cL-CEdqb7N6KIeDL8Q">Especificação de Requisitos Suplementares</a>, planejados para a iteração corrente, tenham casos de teste associados.</li> <li>Todos os participantes devem concordar com os resultados esperados dos casos de teste.</li> <li>Não existem <em>outras</em> condições de satisfação para o requisito a ser testado, o que indica uma falta de um caso de teste ou um requisito ausente.</li> </ul></td> </tr> </table> </div> </td> </tr> </table> </div> <div class="sectionHeading">Key Considerations</div> <div class="sectionContent"> <table class="sectionTable" border="0" cellspacing="0" cellpadding="0"> <tr valign="top"> <td class="sectionTableSingleCell"><p>Desenvolva os casos de teste paralelamente aos requisitos de forma que o <a class="elementLinkWithType" href="./../../openup/roles/analyst_39D7C49B.html" guid="_0VxJsMlgEdmt3adZL5Dmdw">Role: Analista</a> e o <a class="elementLinkWithType" href="./../../openup/roles/stakeholder_9FFD4106.html" guid="_dTa6gMAYEdqX-s4mWhkyqQ">Role: Stakeholder</a> possam concordar com as condições específicas de satisfação para cada requisito. Os casos de teste agem como critérios de aceitação, expandindo sobre a intenção do sistema através de cenários reais de utilização. Isto permite aos membros da equipe medir o progresso em termos de casos de teste executados com sucesso.</p></td> </tr> </table> </div> <table class="copyright" border="0" cellspacing="0" cellpadding="0"> <tr> <td class="copyright"><p>Este programa e o material que o acompanha são disponibilizados sob a<br /> <a href="http://www.eclipse.org/org/documents/epl-v10.php" target="_blank">Eclipse Public License v1.0</a> que acompanha esta distribuição.</p><p/><p> <a class="elementLink" href="./../../openup/guidances/supportingmaterials/openup_copyright_C3031062.html" guid="_UaGfECcTEduSX6N2jUafGA">Direitos Autorais do OpenUP</a>.</p></td> </tr> </table> </td> </tr> </table> </body> <script type="text/javascript" language="JavaScript"> contentPage.onload(); </script> </html>
Themakew/Grupo8
EPF/Publicacao/openup/tasks/create_test_cases_D39E98A1.html
HTML
unlicense
12,186
vimstuff ======== Collection of my vim related things
IkeShoeman/vimstuff
README.md
Markdown
unlicense
55
<?php $item_menu[0] = 3; $item_menu[1] = 2 ; $title = 'M&oacute;dulos'; include('header.php'); if (!isset($_SESSION["admin"])) {redirect("login.php"); exit(); } $accion = request('accion',''); $id = request('id',0); if ($accion == 'guardar') { $titulo = request('titulo',''); $bloque_menu = request('bloque_menu',0); // $script = request('script',''); $script = addslashes($_POST['script']); $descripcion = addslashes(request('descripcion','')); $ubicacion = request('ubicacion',''); $categorias = request('categorias',''); $listar_categoria = request('listar_categoria',''); $cantidad_publicaciones = request('cantidad_publicaciones',5); $cantidad_caracteres = request('cantidad_caracteres',0); $muestra_miniatura = request('muestra_miniatura',0); $nombre_div = request('nombre_div',''); $mostrar_en_sitemap = request('mostrar_en_sitemap',0); $mostrar_en_contacto = request('mostrar_en_contacto',0); $mostrar_en_home = request('mostrar_en_home',0); $mostrar_en_listado = request('mostrar_en_listado',0); $mostrar_destacados = request('mostrar_destacados',0); $muestra_titulo = request('muestra_titulo',0); $cantidad_destacados = request('cantidad_destacados',0); $slide = request('slide',0); $listar_familia = request('listar_familia',''); $cantidad_productos = request('cantidad_productos',5); $idioma_id = request('idioma_id',0); $consulta_rapida = request('consulta_rapida',0); if ($id!=0) { $sql = "update modulos set bloque_menu = '$bloque_menu', descripcion = '$descripcion', script = '$script', ubicacion = '$ubicacion', titulo = '$titulo', categorias = '$categorias', listar_categoria = '$listar_categoria', cantidad_publicaciones = '$cantidad_publicaciones', cantidad_caracteres = '$cantidad_caracteres', muestra_miniatura = '$muestra_miniatura', nombre_div = '$nombre_div', mostrar_en_sitemap = '$mostrar_en_sitemap', mostrar_en_contacto = '$mostrar_en_contacto', mostrar_en_home = '$mostrar_en_home', mostrar_en_listado = '$mostrar_en_listado', mostrar_destacados = '$mostrar_destacados', cantidad_destacados = '$cantidad_destacados', muestra_titulo = '$muestra_titulo', listar_familia = '$listar_familia', cantidad_productos = '$cantidad_productos', idioma_id = '$idioma_id', consulta_rapida = '$consulta_rapida', slide = '$slide' where id = '$id'"; } else { $sql = "insert into modulos (bloque_menu, descripcion, script, ubicacion, titulo, categorias, listar_categoria, cantidad_publicaciones, nombre_div, mostrar_en_sitemap, mostrar_en_contacto, mostrar_en_home, mostrar_en_listado, slide, cantidad_caracteres, muestra_miniatura, mostrar_destacados, cantidad_destacados, muestra_titulo, listar_familia, cantidad_productos, idioma_id, consulta_rapida ) values ('$bloque_menu', '$descripcion', '$script', '$ubicacion', '$titulo', '$categorias', '$listar_categoria', '$cantidad_publicaciones', '$nombre_div', '$mostrar_en_sitemap', '$mostrar_en_contacto', '$mostrar_en_home','$mostrar_en_listado','$slide', '$cantidad_caracteres', '$muestra_miniatura', '$mostrar_destacados', '$cantidad_destacados', '$muestra_titulo','$listar_familia', '$cantidad_productos','$idioma_id', '$consulta_rapida' )"; } /* echo $sql; die(); */ $ok = $db->Execute( $sql ); if ($ok) { $_SESSION['Msg'] = "Cambios guardados correctamente!"; redirect('modulos_contenido.php'); exit(); } else { $_SESSION['Msg'] = "ERROR!, no se pudieron guardar los cambios"; $Mod['titulo'] = $titulo; $Mod['script'] = $script; $Mod['categorias'] = $categorias; $Mod['descripcion'] = $descripcion; $Mod['ubicacion'] = $ubicacion; $Mod['bloque_menu'] = $bloque_menu; $Mod['listar_categoria'] = $listar_categoria; $Mod['cantidad_publicaciones'] = $cantidad_publicaciones; $Mod['nombre_div'] = $nombre_div; $Mod['mostrar_en_sitemap'] = $mostrar_en_sitemap; $Mod['mostrar_en_contacto'] = $mostrar_en_contacto; $Mod['mostrar_en_home'] = $mostrar_en_home; $Mod['mostrar_en_listado'] = $mostrar_en_listado; $Mod['mostrar_destacados'] = $mostrar_destacados; $Mod['cantidad_destacados'] = $cantidad_destacados; $Mod['muestra_titulo'] = $muestra_titulo; $Mod['slide'] = $slide; $Mod['listar_familia'] = $listar_familia; $Mod['cantidad_productos'] = $cantidad_productos; $Mod['idioma_id'] = $idioma_id; $Mod['consulta_rapida'] = $consulta_rapida; // pr($sql); } } else { $sql = "select * from modulos where id='$id'"; $rs = $db->SelectLimit($sql,1); $Mod = $rs->FetchRow(); $Mod['script'] = stripslashes($Mod['script']); $Mod['descripcion'] = stripslashes($Mod['descripcion']); $idioma_id = $Mod['idioma_id']; } // Select Idiomas $rs = $db->Execute("select name,id from idiomas where activo=1"); $select_idioma = $rs->GetMenu2('idioma_id',$idioma_id,true,false); $sql = "select * from bloque_menu where activo=1 order by nombre ASC"; $rs = $db->Execute($sql); $BloquesMenues = $rs->GetRows(); $sql = "select * from categorias where activo=1 order by titulo1 ASC"; $rs = $db->Execute($sql); $Categorias = $rs->GetRows(); // -ARMA LOS SELECT DE LAS FAMILIAS $Familias = crearArbol(0); $parent_id = 0; $familia_id = '<select name="listar_familia">'; $familia_id.= "<option value='0' >Seleccione una Familia de Productos</option>"; foreach($Familias as $dd){ if ($Mod['listar_familia'] == $dd['id']) { $sel = "selected='selected'"; } else {$sel='';} $separador = ""; if ($dd['nivel'] == 2 ) { $separador = "------"; } elseif ($dd['nivel'] == 3 ) { $separador = "------------"; } elseif ($dd['nivel'] == 4 ) { $separador = "------------------"; } $familia_id.= "<option value='{$dd['id']}' $sel >$separador {$dd['nombre1']}</option>"; } $familia_id.= "</select>"; $sql = "select * from slides where activo=1 order by nombre ASC"; $rs = $db->Execute($sql); $Slides = $rs->GetRows(); if(!empty($_SESSION['Msg'])) { echo mensaje_ok($_SESSION['Msg']); $_SESSION['Msg']=''; } ?> <link href="<?=RUTA;?>/css/texto.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="<?php echo INST_DIR;?>/admin/js/ckeditor/ckeditor.js"></script> <script type="text/javascript" src="<?php echo INST_DIR;?>/admin/js/ckfinder/ckfinder.js"></script> <form action="modulos_contenido_edicion.php" method="post"> <table width='1000' cellpadding='3' cellspacing='3' style="border-width:1px; border-style:solid; border-color:#000000"> <tr><td colspan="2" class="th">Edición de Contenido de Módulo</td></tr> <tr> <td align="right" width="10%" class="th"><b>Título</b><span class="tchico">&nbsp;(requerido)</span></td> <td align="left"><input name="titulo" value="<?=$Mod['titulo'];?>" size="60" type="text" /> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Muestra el Titulo: </strong> <select name="muestra_titulo"> <option value='0' <?php if($Mod['muestra_titulo'] == 0){ echo "selected='selected'";} ?> >No</option> <option value='1' <?php if($Mod['muestra_titulo'] == 1){ echo "selected='selected'";} ?> >Si</option> </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <strong>Mostrar en Idioma:</strong> <?php echo $select_idioma;?> </td> </tr> <tr><td colspan="2"><hr /><h2>DONDE PUBLICAR</h2></td></tr> <tr> <td align="right" width="150" class="th"><b>Ubicación:</b></td> <td align="left" width="25%" valign="middle"> <select name="ubicacion"> <option value="1" <?php if($Mod['ubicacion']=='1') { echo 'selected="selected"';}?> >B1</option> <option value="2" <?php if($Mod['ubicacion']=='2') { echo 'selected="selected"';}?> >B2</option> <option value="3" <?php if($Mod['ubicacion']=='3') { echo 'selected="selected"';}?> >B3</option> <option value="4" <?php if($Mod['ubicacion']=='4') { echo 'selected="selected"';}?> >B4</option> <option value="5" <?php if($Mod['ubicacion']=='5') { echo 'selected="selected"';}?> >B5</option> <option value="6" <?php if($Mod['ubicacion']=='6') { echo 'selected="selected"';}?> >B6</option> <option value="7" <?php if($Mod['ubicacion']=='7') { echo 'selected="selected"';}?> >B7</option> <option value="8" <?php if($Mod['ubicacion']=='8') { echo 'selected="selected"';}?> >B8</option> <option value="9" <?php if($Mod['ubicacion']=='9') { echo 'selected="selected"';}?> >B9</option> <?php /* <option value="10" <?php if($Mod['ubicacion']=='10') { echo 'selected="selected"';}?> >B10</option> <option value="11" <?php if($Mod['ubicacion']=='11') { echo 'selected="selected"';}?> >B11</option> <option value="12" <?php if($Mod['ubicacion']=='12') { echo 'selected="selected"';}?> >B12</option> <option value="13" <?php if($Mod['ubicacion']=='13') { echo 'selected="selected"';}?> >B13</option> <option value="14" <?php if($Mod['ubicacion']=='14') { echo 'selected="selected"';}?> >B14</option> <option value="15" <?php if($Mod['ubicacion']=='15') { echo 'selected="selected"';}?> >B15</option> */ ?> </select> </td> </tr> <tr> <td align="right" width="150" class="th"><b>Nombre del DIV:</b></td> <td align="left" width="25%" valign="middle"> <input type="text" name="nombre_div" value='<?php echo $Mod['nombre_div'];?>' /> </td> </tr> <tr><td colspan="2"><hr /><h2>QUE PUBLICAR</h2>Estas opciones son excluyentes [contenido html] o [script] o [Bloque de Menú]</td></tr> <tr> <td class="th"><b>Imagen <br /> Flash <br /> HTML <br /> Video:</td> <td align="left"> <textarea name="descripcion" cols="100" rows="20" class="ckeditor" ><?=$Mod['descripcion'];?></textarea> <script type="text/javascript"> var editor = CKEDITOR.replace( 'descripcion' ); CKFinder.setupCKEditor( editor, '<?=URL;?>/admin/js/ckfinder/' ) ; </script> </td> </tr> <tr> <td class="th"><b>Script</b> <small>Ej: Los script de facebook, twitter, etc</small>:</td> <td align="left"> <textarea name="script" cols="150" rows="10" ><?=$Mod['script'];?></textarea> </td> </tr> <tr> <td class="th"><br /><b>Formulario de Consulta Rapida</b>:<br /><br /></td> <td align="left"> <select name="consulta_rapida"> <option value='0' <?php if($Mod['consulta_rapida'] == 0){ echo "selected='selected'";} ?> >No</option> <option value='1' <?php if($Mod['consulta_rapida'] == 1){ echo "selected='selected'";} ?> >Si</option> </select> </td> </tr> <tr> <td class="th"><br /><b>Bloque de Menú</b>:<br /><br /></td> <td align="left"> <select name="bloque_menu"> <option value='0' <?php if($Mod['bloque_menu']==0){ echo "selected='selected'";} ?> >Seleccione un bloque de menu</option> <?php foreach($BloquesMenues as $bm){ ?> <option value='<?=$bm['id'];?>' <?php if($Mod['bloque_menu']==$bm['id']){ echo "selected='selected'";} ?> ><?=$bm['nombre'];?></option> <?php }?> </select> </td> </tr> <tr> <td class="th"><br/><b>Listar Ultimas Publicaciones de una categoria:</b><br /><br /></td> <td align="left"> <select name="listar_categoria"> <option value='0' <?php if($Mod['listar_categoria']==0){ echo "selected='selected'";} ?> >Seleccione una Categoria</option> <?php foreach($Categorias as $bm){ ?> <option value='<?=$bm['id'];?>' <?php if($Mod['listar_categoria']==$bm['id']){ echo "selected='selected'";} ?> ><?=$bm['titulo1'];?></option> <?php }?> </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cantidad de Publicaciones a mostrar: <input type="text" name="cantidad_publicaciones" value='<?php echo $Mod['cantidad_publicaciones'];?>' size='2'/> <br /> Cantidad de Caracteres a mostrar: <input type="text" name="cantidad_caracteres" value='<?php echo $Mod['cantidad_caracteres'];?>' size='2'/> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Muestra Miniatura: <select name="muestra_miniatura"> <option value='0' <?php if($Mod['muestra_miniatura'] == 0){ echo "selected='selected'";} ?> >No</option> <option value='1' <?php if($Mod['muestra_miniatura'] == 1){ echo "selected='selected'";} ?> >Si</option> </select> </td> </tr> <tr> <td class="th"><br/><b>Listar Productos de una Familia:</b><br /><br /></td> <td align="left"> <?php echo $familia_id;?> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cantidad de Productos a mostrar: <input type="text" name="cantidad_productos" value='<?php echo $Mod['cantidad_productos'];?>' size='2'/> </td> </tr> <tr> <td class="th"><br/><b>SLIDE:</b><br /><br /></td> <td align="left"> <select name="slide"> <option value='0' <?php if($Mod['slide']==0){ echo "selected='selected'";} ?> >Seleccione un Banner</option> <?php foreach($Slides as $bm){ ?> <option value='<?=$bm['id'];?>' <?php if($Mod['slide']==$bm['id']){ echo "selected='selected'";} ?> ><?=$bm['nombre'];?></option> <?php }?> </select> </td> </tr> <tr> <td class="th"><br/><b>Destacados:</b><br /><br /></td> <td align="left"> Mostrar publicaciones destacadas: <select name="mostrar_destacados"> <option value="0" <?php if($Mod['mostrar_destacados']=='0') { echo 'selected="selected"';}?> >No</option> <option value="1" <?php if($Mod['mostrar_destacados']=='1') { echo 'selected="selected"';}?> >Si</option> </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Cantidad de Destacados a mostrar: <input type="text" name="cantidad_destacados" value='<?php echo $Mod['cantidad_destacados'];?>' size='2'/> </td> </tr> <tr><td colspan="2"><hr /><h2>CUANDO PUBLICAR</h2></td></tr> <tr> <td align="right" width="150" class="th"><b>Cuando se va a Mostrar:</b></td> <td align="left" valign="middle"> En las publicaciones de la siguiente categoria: <select name="categorias"> <option value='0' <?php if($Mod['categorias'] == 0){ echo "selected='selected'";} ?> >En Todas las categorias</option> <option value='-1' <?php if($Mod['categorias'] == -1){ echo "selected='selected'";} ?> >Solo en las siguentes opciones</option> <?php foreach($Categorias as $cate){ ?> <option value='<?=$cate['id'];?>' <?php if($Mod['categorias']==$cate['id']){ echo "selected='selected'";} ?> ><?=$cate['titulo1'];?></option> <?php }?> </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Mostrar tambien en el listado de esa categoria?: <select name="mostrar_en_listado"> <option value="0" <?php if($Mod['mostrar_en_listado']=='0') { echo 'selected="selected"';}?> >No</option> <option value="1" <?php if($Mod['mostrar_en_listado']=='1') { echo 'selected="selected"';}?> >Si</option> </select> <br /><br /> Mostrar en la Home?: <select name="mostrar_en_home"> <option value="0" <?php if($Mod['mostrar_en_home']=='0') { echo 'selected="selected"';}?> >No</option> <option value="1" <?php if($Mod['mostrar_en_home']=='1') { echo 'selected="selected"';}?> >Si</option> </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Mostrar en Formulario de Contacto?: <select name="mostrar_en_contacto"> <option value="0" <?php if($Mod['mostrar_en_contacto']=='0') { echo 'selected="selected"';}?> >No</option> <option value="1" <?php if($Mod['mostrar_en_contacto']=='1') { echo 'selected="selected"';}?> >Si</option> </select> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Mostrar en Mapa Web?: <select name="mostrar_en_sitemap"> <option value="0" <?php if($Mod['mostrar_en_sitemap']=='0') { echo 'selected="selected"';}?> >No</option> <option value="1" <?php if($Mod['mostrar_en_sitemap']=='1') { echo 'selected="selected"';}?> >Si</option> </select> <br /> </td> </tr> <tr> <td colspan="2" align="center"> <input name="id" value="<?=$Mod['id'];?>" type="hidden" /> <input name="accion" value="guardar" type="hidden" /> <input name="submit" value="Guardar los Cambios" type="submit" /> </td> </tr> </table> </form>
fdolci/cj-ztYt7MVxgtFy5vL3
admin/modulos_contenido_edicion.php
PHP
unlicense
19,219
# TowerOfHanoi OpenGL simulation of the solution to the Tower of Hanoi problem.
rohitjha/TowerOfHanoi
README.md
Markdown
unlicense
80
package deterno.fight.tgm.damage.grave.event; import deterno.fight.tgm.damage.tracker.Lifetime; import lombok.ToString; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.inventory.ItemStack; import org.joda.time.Instant; import java.util.List; @ToString(callSuper = true) public class EntityDeathByPlayerEvent extends EntityDeathByEntityEvent<Player> { public EntityDeathByPlayerEvent(Entity entity, Location location, Lifetime lifetime, Instant time, List<ItemStack> drops, int droppedExp, Player cause) { super(entity, location, lifetime, time, drops, droppedExp, cause); } public static HandlerList getHandlerList() { return handlers; } public HandlerList getHandlers() { return handlers; } }
FightMC/Fight
TGM/src/main/java/network/fight/tgm/damage/grave/event/EntityDeathByPlayerEvent.java
Java
unlicense
848
--- layout: post title: Low Cost Server Hosting for Low Traffic date: 2016-07-18 --- It is always a good idea to host a personal website. However hosting just several simple pages on a dedicated server is an over-kill (and costly) option. Here I list some web services which are incredibly cheap and reliable. I may make some guidelines later on how to use them. It costs me around HKD700 (USD 90) annually to host everything. Or if you have any alternative choices, please give me feedback too. ;-) # Some example of what you can make... 1. URL redirect - http://stackoverflow.billy.hk - http://linkedin.billy.hk - http://facebook.billy.hk 2. Your own email server - jobs@billy.hk # Service List ## Domain - http://www.gandi.net - I find it inexpensive to register a .hk domain with 3-year contract. I will switch to this provider once my current contract ends. ## Static Page - https://aws.amazon.com/tw/s3/ - Amazon S3, highly available and secure. Several MB pages cost only several cents monthly. ## Dynamic Page - https://www.digitalocean.com - Digital Ocean, costs only $5 for a full functioning UNIX machine. Extremely stable. - This screenshot can show you the definition of a stable machine. - ![Digital Ocean Uptime]({{ site.image_base }}/2016/07/18/DigitalOceanUpTime.png) ## Email - Google Apps for Work - There was a loophole and it allowed a free account for one user in the domain. I am uncertain if the loophole was fixed. If not, this is the cheapest mail server option.
hktonylee/hktonylee.github.io
_posts/2016-10-28-low-cost-server-hosting-for-low-traffic.md
Markdown
unlicense
1,546
#include <iostream> #include <map> #include <utility> using namespace std; map<pair<int, int>, int> cache; // Pascal's triangle int combination(int n, int k) { if (n == k || k == 0) return 1; pair<int, int> entry(n, k); if (cache.count(entry) > 0) return cache[entry]; int result = combination(n - 1, k - 1) + combination(n - 1, k); cache[entry] = result; return result; } int main() { int n, m; while(cin >> n >> m && n > 0 && m > 0) { cout << n << " things taken " << m << " at a time is " << combination(n, m) << " exactly.\n"; } return 0; }
0xDCA/competitive_programming
UVa/UVa 369 - Combinations.cpp
C++
unlicense
612
package ru.kontur; import java.util.*; /** * @author Dmitry * @since 01.08.2015 */ public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int wordNumber = in.nextInt();//количество слов в найденных текстах IWordSearcher wordSearcher = new WordSearcherPrefixTree(); while (wordNumber > 0) { String word = in.next(); Integer frequency = in.nextInt(); wordSearcher.add(word, frequency); wordNumber--; } wordNumber = in.nextInt();//количество слов для поиска List<String> searchedWordsList = new ArrayList<>(wordNumber);//Список слов для поиска while (wordNumber > 0) { searchedWordsList.add(in.next()); wordNumber--; } in.close(); for (String searchedWord : searchedWordsList) { wordSearcher.getMostFrequentlyUsedWords(searchedWord).forEach(System.out::println); System.out.println(); } } }
mylog00/kontur
src/main/java/ru/kontur/Main.java
Java
unlicense
1,113
#include <stdio.h> #include <string.h> #include <errno.h> #include "parse.h" #include "common.h" #include "colormap.h" int *load_array (char *list); /* Load configuration */ void load_config (FILE * infile) { if (infile == NULL) { fprintf (stderr, "%s: failed to read config file - %s\n", progname, strerror (errno)); exit (EXIT_FAILURE); } int comment = 0; int lineno = 1; /* Prepare buffer */ char *buffer, *ptr; size_t buffer_len = 128; buffer = ptr = xmalloc (buffer_len); *buffer = 0; while (!feof (infile)) { char c = getc (infile); /* End of line */ if (c == 10 || c == 13) { *ptr = 0; int result = process_line (buffer); if (result != 0) { fprintf (stderr, "%s:%d: config parse error\n", progname, lineno); exit (EXIT_FAILURE); } *buffer = 0; ptr = buffer; lineno++; comment = 0; continue; } if (comment) continue; if (c == '#') { comment = 1; continue; } *ptr = c; ptr++; if (ptr - buffer > (int) buffer_len - 4) { size_t off = ptr - buffer; buffer_len *= 2; buffer = realloc (buffer, buffer_len); if (buffer == NULL) { fprintf (stderr, "%s: realloc failed\n", progname); exit (EXIT_FAILURE); } ptr = buffer + off; } } } /* Parse a single line */ int process_line (char *line) { char *base = line; /* trim whitespace */ while (*base == ' ') base++; if (*base == 0) return 0; char *ptr = base; while (*ptr != '=' && *ptr != ' ' && *ptr != 0) ptr++; if (*ptr == 0) return 1; *ptr = 0; /* Now find value */ ptr++; while (*ptr == '=' || *ptr == ' ') ptr++; if (*ptr == 0) return 1; char *val = ptr; /* Match keyword */ if (strcmp (base, "xmin") == 0) xmin = strtod (val, NULL); else if (strcmp (base, "xmax") == 0) xmax = strtod (val, NULL); else if (strcmp (base, "ymin") == 0) ymin = strtod (val, NULL); else if (strcmp (base, "ymax") == 0) ymax = strtod (val, NULL); else if (strcmp (base, "zoomx") == 0) zoomx = strtod (val, NULL); else if (strcmp (base, "zoomy") == 0) zoomy = strtod (val, NULL); else if (strcmp (base, "iterations") == 0) it = atoi (val); else if (strcmp (base, "image_width") == 0) width = atoi (val); else if (strcmp (base, "image_height") == 0) height = atoi (val); else if (strcmp (base, "image_jobs") == 0) jobs = atoi (val); else if (strcmp (base, "zoom_jobs") == 0) zoom_jobs = atoi (val); else if (strcmp (base, "zoom_frames") == 0) zoom_it = atoi (val); else if (strcmp (base, "zoom_rate") == 0) zoom_rate = strtod (val, NULL); else if (strcmp (base, "color_width") == 0) cwidth = atoi (val); else if (strcmp (base, "red") == 0) { red = load_array (val); if (red == NULL) return 1; } else if (strcmp (base, "green") == 0) { green = load_array (val); if (green == NULL) return 1; } else if (strcmp (base, "blue") == 0) { blue = load_array (val); if (blue == NULL) return 1; } else return 1; return 0; } /* Load an array for a colormap */ int *load_array (char *list) { int *c = xmalloc (cmap_len * sizeof (int)); int ci = 0; char *ptr = list; while (*ptr != '{' && *ptr != 0) ptr++; if (*ptr == 0) return NULL; ptr++; while (*ptr != 0) { if (*ptr == '}') break; c[ci] = atoi (ptr); ci++; if (ci > cmap_len) { /* Badly formed colormap */ if (cmap_edit) return NULL; cmap_len *= 2; c = realloc (c, cmap_len); if (c == NULL) { fprintf (stderr, "%s: cmap realloc failed - %s\n", progname, strerror (errno)); exit (EXIT_FAILURE); } } while (*ptr != ',' && *ptr != 0) ptr++; ptr++; } /* Make sure we read in enough values. */ if (cmap_edit && cmap_len != ci) return NULL; cmap_len = ci; cmap_edit = 1; return c; }
skeeto/mandelbrot
parse.c
C
unlicense
4,031
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MegatubeV2 { public class CsvVideo : IReferenceable { public string VideoId { get; set; } public string ChannelID { get; set; } public string Uploader { get; set; } public decimal PartnerRevenue { get; set; } public string ContentType { get; set; } public string AssetChannelId { get; set; } public string ChannelDisplayName { get; set; } public CsvVideo() { } public string GetOwnerReference() => string.IsNullOrEmpty(AssetChannelId) ? AssetChannelId : ChannelID; } }
Alx666/MegatubeV2
MegatubeV2/CsvVideo.cs
C#
unlicense
750
# GL_Vehicles OpenGL simulation of wheeled vehicles
OllieReynolds/GL_VEHICLES
README.md
Markdown
unlicense
52
pub mod bfs_dfs; pub mod dijkstra;
alekseysidorov/playground
training/graphs/src/lib.rs
Rust
unlicense
35
package me.pagar.model; import com.google.gson.JsonArray; import com.google.gson.JsonObject; import java.util.ArrayList; import java.util.Collection; import me.pagar.util.JSONUtils; public class PagarMeException extends Exception { private int returnCode; private String url; private String method; Collection<PagarMeError> errors = new ArrayList<PagarMeError>(); public static PagarMeException buildWithError(final Exception error) { return new PagarMeException(error.getMessage(), null); } public static PagarMeException buildWithError(final PagarMeResponse response) { if (null == response) { return null; } final JsonObject responseError = JSONUtils.getInterpreter().fromJson(response.getBody(), JsonObject.class); final JsonArray errors = responseError.getAsJsonArray("errors"); final StringBuilder joinedMessages = new StringBuilder(); int i; for (i = 0; i < errors.size(); i++) { final JsonObject error = errors.get(i).getAsJsonObject(); joinedMessages .append(error.get("message").getAsString()) .append("\n"); } final PagarMeException exception = new PagarMeException(joinedMessages.toString(), responseError); exception.returnCode = response.getCode(); return exception; } public PagarMeException(int returnCode, String url, String method, String message) { super(message); this.returnCode = returnCode; this.url = url; this.method = method; } public PagarMeException(final String message) { this(message, null); } public PagarMeException(final String message, final JsonObject responseError) { super(message); if (null != responseError) { this.url = responseError.get("url").getAsString(); this.method = responseError.get("method").getAsString(); if (responseError.has("errors")) { final JsonArray errors = responseError.get("errors").getAsJsonArray(); int i; for (i = 0; i < errors.size(); i++) { final JsonObject error = errors.get(i).getAsJsonObject(); this.errors.add(new PagarMeError(error)); } } } } public Collection<PagarMeError> getErrors() { return errors; } public String getUrl() { return url; } public String getMethod() { return method; } public int getReturnCode() { return returnCode; } }
pagarme/pagarme-java
src/main/java/me/pagar/model/PagarMeException.java
Java
unlicense
2,653
/** * Copyright (c) 2009 - 2010 Chris Leonello * jqPlot is currently available for use in all personal or commercial projects * under both the MIT and GPL version 2.0 licenses. This means that you can * choose the license that best suits your project and use it accordingly. * * The author would appreciate an email letting him know of any substantial * use of jqPlot. You can reach the author at: chris at jqplot dot com * or see http://www.jqplot.com/info.php . This is, of course, * not required. * * If you are feeling kind and generous, consider supporting the project by * making a donation at: http://www.jqplot.com/donate.php . * * Thanks for using jqPlot! * */ (function($) { /** * Class: $.jqplot.ciParser * Data Renderer function which converts a custom JSON data object into jqPlot data format. * Set this as a callable on the jqplot dataRenderer plot option: * * > plot = $.jqplot('mychart', [data], { dataRenderer: $.jqplot.ciParser, ... }); * * Where data is an object in JSON format or a JSON encoded string conforming to the * City Index API spec. * * Note that calling the renderer function is handled internally by jqPlot. The * user does not have to call the function. The parameters described below will * automatically be passed to the ciParser function. * * Parameters: * data - JSON encoded string or object. * plot - reference to jqPlot Plot object. * * Returns: * data array in jqPlot format. * */ $.jqplot.ciParser = function (data, plot) { var ret = [], line, i, j, k, kk; if (typeof(data) == "string") { data = $.jqplot.JSON.parse(data, handleStrings); } else if (typeof(data) == "object") { for (k in data) { for (i=0; i<data[k].length; i++) { for (kk in data[k][i]) { data[k][i][kk] = handleStrings(kk, data[k][i][kk]); } } } } else return null; // function handleStrings // Checks any JSON encoded strings to see if they are // encoded dates. If so, pull out the timestamp. // Expects dates to be represented by js timestamps. function handleStrings(key, value) { var a; if (value != null) { if (value.toString().indexOf('Date') >= 0) { //here we will try to extract the ticks from the Date string in the "value" fields of JSON returned data a = /^\/Date\((-?[0-9]+)\)\/$/.exec(value); if (a) { return parseInt(a[1], 10); } } return value; } } for (var prop in data) { line = []; temp = data[prop]; switch (prop) { case "PriceTicks": for (i=0; i<temp.length; i++) { line.push([temp[i]['TickDate'], temp[i]['Price']]); } break; case "PriceBars": for (i=0; i<temp.length; i++) { line.push([temp[i]['BarDate'], temp[i]['Open'], temp[i]['High'], temp[i]['Low'], temp[i]['Close']]); } break; } ret.push(line); } return ret; }; })(jQuery);
ninetwentyfour/Homkora
app/webroot/js/jqplot/src/plugins/jqplot.ciParser.js
JavaScript
unlicense
3,574
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_07) on Wed Feb 08 19:32:56 CST 2012 --> <TITLE> org.hibernate.cache.infinispan.query (Hibernate JavaDocs) </TITLE> <META NAME="date" CONTENT="2012-02-08"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style"> </HEAD> <BODY BGCOLOR="white"> <FONT size="+1" CLASS="FrameTitleFont"> <A HREF="../../../../../org/hibernate/cache/infinispan/query/package-summary.html" target="classFrame">org.hibernate.cache.infinispan.query</A></FONT> <TABLE BORDER="0" WIDTH="100%" SUMMARY=""> <TR> <TD NOWRAP><FONT size="+1" CLASS="FrameHeadingFont"> Classes</FONT>&nbsp; <FONT CLASS="FrameItemFont"> <BR> <A HREF="QueryResultsRegionImpl.html" title="class in org.hibernate.cache.infinispan.query" target="classFrame">QueryResultsRegionImpl</A></FONT></TD> </TR> </TABLE> </BODY> </HTML>
codeApeFromChina/resource
frame_packages/java_libs/hibernate-distribution-3.6.10.Final/documentation/javadocs/org/hibernate/cache/infinispan/query/package-frame.html
HTML
unlicense
985
/** * Karp Server. * * @author James Koval & Friends <https://github.com/jakl/karp> * @license MIT? * @version 2 * * :shipit: */ "use strict"; // Pollyfil object.values because heroku is running old node.js var reduce = Function.bind.call(Function.call, Array.prototype.reduce); var isEnumerable = Function.bind.call(Function.call, Object.prototype.propertyIsEnumerable); var concat = Function.bind.call(Function.call, Array.prototype.concat); var keys = Reflect.ownKeys; if (!Object.values) { Object.values = function values(O) { return reduce(keys(O), (v, k) => concat(v, typeof k === 'string' && isEnumerable(O, k) ? [O[k]] : []), []); }; } const express = require('express') const app = express(); const http = require('http').Server(app); const io = require('socket.io')(http); const names = {} app.set('port', (process.env.PORT || 5000)); app.use(express.static(__dirname + '/')); app.get('/', function(req, res){ res.sendFile(__dirname + '/index.html'); }); io.on('connection', function(socket){ names[socket.id] = 'unnamed' console.log(`user ${socket.id} connected`); players[socket.id] = random_player_fish(socket.id) keyboards[socket.id] = empty_keyboard() socket.emit('config', config) socket.on('disconnect', function(){ delete players[socket.id] delete keyboards[socket.id] console.log(`user ${socket.id} disconnected`); }); socket.on('name', name => { console.log(`user ${socket.id} is now know as: '${name}'`) names[socket.id] = name; }) socket.on('keyboard', function(client_keyboard){ keyboards[socket.id] = client_keyboard }); socket.on('reset', function(){ if(!game_over) return; // only allow on game over. reset() }); }); http.listen(app.get('port'), function(){ console.log(`listening on ${app.get('port')}`); }); //================================ // Declare all game constiables (imaginary buckets that hold game information/values) // Note: // [] means an array (an auto-numbered list of values, index starts at 0) // {} means an object (a named list of values, also known as a hash or map) //================================ const config = require("./config.json") let game_over = false // If this is set to true, the game over screen is displayed let game_over_auto_reset = null let winner = null let ai_quantity = config.start_with let fishes = [] const players = {} /** * Return all the fishes on the server? * @return {Array} Array of fishes. */ const all_fishes = () => { return fishes.concat(Object.values(players)) } // === constiables for the keyboard keys that we track for player movement === const keyboards = {} /** * Reset the player to a new location. * @param {String} id Player id. * @returns {Object} Player Object. */ const reset_player = id => { players[id] = random_player_fish(id) return players[id] } //================================ // Reset all the fish back to start //================================ const reset = () => { fishes = [] Object.keys(players).forEach(reset_player) game_over = false ai_quantity = config.start_with clearTimeout(game_over_auto_reset) game_over_auto_reset = null io.emit('game_over', { game_over: false, winner: false }) } reset() //================================ // Code for moving each fish individually //================================ const move_fish = fish => { // === move the fish position by an amount that is its speed === fish.x += fish.dx fish.y += fish.dy if(fish.id) fish.name = names[fish.id] if(!fish.name) { const names = ['glub...', '*splash*', '???'] fish.name = names[Math.floor(Math.random() * names.length)]; } const fish_alive = Date.now() - fish.created_at; if(fish.type === 'gold' && fish_alive > config.special_fish_timeout) { let original_fish = fish; fish = random_ai_fish() fish.r = original_fish.r fish.x = original_fish.x fish.y = original_fish.y } if(fish.type === 'negative' && fish_alive > config.special_fish_timeout) { fish = random_ai_fish(); } /* === if the fish goes off an edge, wrap it around === */ if (fish.x > config.x_scale) { fish.x = 0 } if (fish.x < 0) { fish.x = config.x_scale } if (fish.y > config.y_scale) { fish.y = 0 } if (fish.y < 0) { fish.y = config.y_scale } } //================================ // Set the speeds for fishes controlled by players, based on keys pressed //================================ const move_with_keyboard = id => { if (!keyboards[id] || !players[id]) { return } // === keyboard controls for players === if (keyboards[id].left) { players[id].dx = -config.player_speed } else if (keyboards[id].right) { players[id].dx = config.player_speed } else { players[id].dx = 0 } if (keyboards[id].up) { players[id].dy = -config.player_speed } else if (keyboards[id].down) { players[id].dy = config.player_speed } else { players[id].dy = 0 } } //================================ // Code to add AI fish to the pond if there are too few //================================ const add_ai_fish = () => { if(fishes.length > config.max_ai_fish) return; // max if (fishes.length < ai_quantity){ fishes.push(random_ai_fish()) } } // Every 10s add an AI fish setInterval(() => { ai_quantity++ }, config.ai_reproduction_rate) //================================ // Generate a randomized fish javascript object //================================ const random_ai_fish = () => { let type = 'positive' let color = 'blue'; // decide which type this fish is let negFishChance = Math.floor(Math.random() * (config.negChance - 0)); let goldFishChance = Math.floor(Math.random() * (config.goldChance - 0)); // make a neg? if(negFishChance === config.negChance-1) { type = 'negative' color = 'green' } // game winner. if(goldFishChance === config.goldChance - 1) { type = 'gold' color = 'gold' } return { x: Math.random() * config.x_scale, y: Math.random() * config.y_scale, dx: Math.random() * config.ai_speed * 2 - config.ai_speed, dy: Math.random() * config.ai_speed * 2 - config.ai_speed, r: Math.random() * config.max_ai_size + 1, type: type, created_at: Date.now(), color: color, } } //================================ // Generate a randomized player fish javascript object //================================ const random_player_fish = id => { return { id: id, x: Math.random() * config.x_scale, y: Math.random() * config.y_scale, dx: 0, dy: 0, type: 'player', r: config.player_start_size, color: "#FF0000", } } const empty_keyboard = () => { return { up: false, down: false, left: false, right: false, } } //================================ // Code to check if any fish bumps into any other fish //================================ const bump_fish = () => { all_fishes().forEach(function(fish, fish_index){ all_fishes().forEach(function(another_fish, another_fish_index){ if (another_fish_index == fish_index) { // don't check the same fish against itself return } // Distance formula: √[(x1-x2)²+(y1-y2)²] const distance = Math.sqrt( Math.pow(fish.x - another_fish.x, 2) + Math.pow(fish.y - another_fish.y, 2) ) // if the fish are closer than their radiuses, then they are touching if (distance < fish.r + another_fish.r) { // avoid any issues. fish.index = fish_index; another_fish.index = another_fish_index /** * Find a fish by type. * * @param {String} type Type name. * @param {Object:Fish} one_fish Fish to check. * @param {Object:Fish} two_fish Fish to check. * @return {Object} Matching fish or undefined. */ const find_fish = (type, one_fish, two_fish) => { return (one_fish.type === type) ? one_fish : (two_fish.type === type) ? two_fish : undefined } const negative_fish = find_fish('negative', fish, another_fish) const player_fish = find_fish('player', fish, another_fish) const positive_fish = find_fish('positive', fish, another_fish) const gold_fish = find_fish('gold', fish, another_fish) // negative fish if((player_fish || positive_fish) && negative_fish) { const subject_fish = player_fish !== undefined ? player_fish : positive_fish subject_fish.r = subject_fish.r / config.neg_reduction fishes.splice(negative_fish.index, 1, random_ai_fish()) return; } // gold fish if(player_fish && gold_fish) { player_fish.r = config.x_scale return; } // check which fish is bigger - the bigger one eats the little one if (fish.r > another_fish.r) { eat_fish(another_fish_index, fish_index) } else { eat_fish(fish_index, another_fish_index) } } }) }) } //================================ // Code for when fish touch, the smaller fish is eaten, the bigger fish grows larger //================================ const eat_fish = (small_fish_index, big_fish_index) => { const big_fish = all_fishes()[big_fish_index] const small_fish = all_fishes()[small_fish_index] // expand big fish to be BIGGER. big_fish.r += small_fish.r / big_fish.r if (small_fish.id) { // This is a player reset_player(small_fish.id) } else { fishes.splice(small_fish_index, 1, random_ai_fish()) } if (big_fish.r > config.x_scale) { if(big_fish.id) { winner = names[big_fish.id]; } else { winner = 'AI' } end_game(winner) } } const end_game = (winner) => { game_over = true io.emit('game_over', { game_over: game_over, winner: winner }) io.emit('fishes', []) game_over_auto_reset = setTimeout(() => { reset(); }, config.restart_game_timer) } //================================ // Code that will periodically send game information out to any browsers connected //================================ const update_clients = () => { io.emit('fishes', all_fishes().concat(Object.values(players))) } //================================ // This is the code that runs over and over again to keep the game moving //================================ const heartbeat = () => { if(game_over) { return; } Object.keys(players).forEach(move_with_keyboard) all_fishes().forEach(move_fish) add_ai_fish() bump_fish() update_clients() }; //================================ // This starts the infinite looping heartbeat of the game logic, every 60 milliseconds //================================ setInterval(heartbeat, 60) /* This debug function can display game information in the console */ const debug = () => { console.log("fishes:", fishes, "players:", players, "keyboards:", keyboards, "game_over:", game_over) } if(process.env.DEBUG) setInterval(debug, 5000)/* Uncomment this line of code to see debug info */
jakl/karp
index.js
JavaScript
unlicense
11,128
#include <C_Scheme.hpp> #include <iostream> namespace C { Scheme::Vivifian::Vivifian(int) { std::clog << "Vivifian(int)" << std::endl; } }
OragonEfreet/Sandbox
test_archi/C/C_Scheme.cpp
C++
unlicense
152
class SchoolsController < ApplicationController def index renter = Renter.find( params[:renter_id]) if renter @schools = renter.schools end render json: @schools end def get_school_cycles school = School.find( params[:id]) if school render json:school.cycles end end end
ofoso/ofo_t
app/controllers/schools_controller.rb
Ruby
unlicense
315
#!/bin/bash sed s/\;.*// $1 | xclip -selection clipboard
CompSciCabal/SMRTYPRTY
paip/jim/attolisp/uncomment.sh
Shell
unlicense
58
package br.com.fiap.filter; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import br.com.fiap.bean.UsuarioSessaoBean; @WebFilter("/*") public class PopulaUsuarioFilter implements Filter { SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss.S"); public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; HttpSession sessao = httpRequest.getSession(true); UsuarioSessaoBean usuario = (UsuarioSessaoBean) sessao.getAttribute("usuario"); if (usuario == null) { usuario = new UsuarioSessaoBean(); usuario.setPrimeiroAcesso(sdf.format(new Date())); } usuario.setUltimoAcesso(sdf.format(new Date())); sessao.setAttribute("usuario", usuario); chain.doFilter(request, response); } }
pedrohnog/Atividades_Extras-FIAP
Fiap-Aula2_Ex3_JavaNaWeb/src/br/com/fiap/filter/PopulaUsuarioFilter.java
Java
unlicense
1,216
package be.kifaru.examples; import javax.xml.bind.DatatypeConverter; import static java.nio.charset.StandardCharsets.UTF_8; /** * @author Devid Verfaillie * @since 2015-09-07 */ public enum Base64 { /** * Singleton instance of this class. * <p/> * See Effective Java 2nd Edition, items 3 (Enforce the singleton property with a private constructor or an enum * type) & 77 (For instance control, prefer enum types to readResolve). */ INSTANCE; public byte[] decodeToByteArray(String base64StringToDecode) { // use the following class and method instead of org.apache.commons.codec.binary.Base64 for example // there is no need for wrapping really return DatatypeConverter.parseBase64Binary(base64StringToDecode); } public String decodeToString(String base64StringToDecode) { return new String(decodeToByteArray(base64StringToDecode), UTF_8); } public String encodeFromByteArray(byte[] byteArrayToEncode) { // use the following class and method instead of org.apache.commons.codec.binary.Base64 for example // there is no need for wrapping really return DatatypeConverter.printBase64Binary(byteArrayToEncode); } public String encodeFromString(String stringToEncode) { return encodeFromByteArray(stringToEncode.getBytes(UTF_8)); } }
verfade/examples
examples/src/main/java/be/kifaru/examples/Base64.java
Java
unlicense
1,369
<table> <tr> <th>Name</th> <th>Password</th> <th>Type</th> </tr> <tr> <?php foreach ($name as $data): ?> <td> <?php echo $data; ?></td> <?php endforeach; ?> </tr> </table>
johnotaalo/NQCL_LIMS
application/views.bak/me_v.php
PHP
unlicense
240
# JessacaSummers.github.io
JessacaSummers/JessacaSummers.github.io
README.md
Markdown
unlicense
26
#ifndef __SIZE_T_H #define __SIZE_T_H //**************************************************************************** //** //** size_t.h //** - Standard C and C++ size_t type //** //**************************************************************************** //============================================================================ // INTERFACE REQUIRED HEADERS //============================================================================ //============================================================================ // INTERFACE DEFINITIONS / ENUMERATIONS / SIMPLE TYPEDEFS //============================================================================ #ifdef __cplusplus extern "C" { #endif /* standard size_t type */ typedef unsigned size_t; #ifdef __cplusplus } #endif //============================================================================ // INTERFACE CLASS PROTOTYPES / EXTERNAL CLASS REFERENCES //============================================================================ //============================================================================ // INTERFACE STRUCTURES / UTILITY CLASSES //============================================================================ //============================================================================ // INTERFACE DATA DECLARATIONS //============================================================================ //============================================================================ // INTERFACE FUNCTION PROTOTYPES //============================================================================ //============================================================================ // INTERFACE OBJECT CLASS DEFINITIONS //============================================================================ //============================================================================ // INTERFACE TRAILING HEADERS //============================================================================ //**************************************************************************** //** //** END size_t.h //** //**************************************************************************** #endif
mooseman/plan_42
attic/p42/SysCore/Include/size_t.h
C
unlicense
2,246
var Db = require('../lib/mongodb').Db, Connection = require('../lib/mongodb').Connection, Server = require('../lib/mongodb').Server; var host = process.env['MONGO_NODE_DRIVER_HOST'] != null ? process.env['MONGO_NODE_DRIVER_HOST'] : 'localhost'; var port = process.env['MONGO_NODE_DRIVER_PORT'] != null ? process.env['MONGO_NODE_DRIVER_PORT'] : Connection.DEFAULT_PORT; console.log("Connecting to " + host + ":" + port); var db = new Db('node-mongo-examples', new Server(host, port, {}), {native_parser:true}); db.open(function(err, db) { db.dropDatabase(function() { // Fetch the collection test db.collection('test', function(err, collection) { // Remove all records in collection if any collection.remove(function(err, result) { // Insert three records collection.insert([{'a':1}, {'a':2}, {'b':3}], function(docs) { // Count the number of records collection.count(function(err, count) { console.log("There are " + count + " records."); }); // Find all records. find() returns a cursor collection.find(function(err, cursor) { // Print each row, each document has an _id field added on insert // to override the basic behaviour implement a primary key factory // that provides a 12 byte value console.log("Printing docs from Cursor Each") cursor.each(function(err, doc) { if(doc != null) console.log("Doc from Each "); console.dir(doc); }) }); // Cursor has an to array method that reads in all the records to memory collection.find(function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Printing docs from Array") docs.forEach(function(doc) { console.log("Doc from Array "); console.dir(doc); }); }); }); // Different methods to access records (no printing of the results) // Locate specific document by key collection.find({'a':1}, function(err, cursor) { cursor.nextObject(function(err, doc) { console.log("Returned #1 documents"); }); }); // Find records sort by 'a', skip 1, limit 2 records // Sort can be a single name, array, associate array or ordered hash collection.find({}, {'skip':1, 'limit':1, 'sort':'a'}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }) }); // Find all records with 'a' > 1, you can also use $lt, $gte or $lte collection.find({'a':{'$gt':1}}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); collection.find({'a':{'$gt':1, '$lte':3}}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); // Find all records with 'a' in a set of values collection.find({'a':{'$in':[1,2]}}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); // Find by regexp collection.find({'a':/[1|2]/}, function(err, cursor) { cursor.toArray(function(err, docs) { console.log("Returned #" + docs.length + " documents"); }); }); // Print Query explanation collection.find({'a':/[1|2]/}, function(err, cursor) { cursor.explain(function(err, doc) { console.log("-------------------------- Explanation"); console.dir(doc); }) }); // Use a hint with a query, hint's can also be store in the collection // and will be applied to each query done through the collection. // Hint's can also be specified by query which will override the // hint's associated with the collection collection.createIndex('a', function(err, indexName) { collection.hint = 'a'; // You will see a different explanation now that the hint was set collection.find({'a':/[1|2]/}, function(err, cursor) { cursor.explain(function(err, doc) { console.log("-------------------------- Explanation"); console.dir(doc); }) }); collection.find({'a':/[1|2]/}, {'hint':'a'}, function(err, cursor) { cursor.explain(function(err, doc) { console.log("-------------------------- Explanation"); console.dir(doc); db.close(); }) }); }); }); }); }); }); });
luizesramos/learning
web-auth/node_modules/mongodb/examples/queries.js
JavaScript
unlicense
5,240
/**************************************************************************** ** Meta object code from reading C++ file 'canvaspicker.h' ** ** Created: Wed 23. Nov 03:06:34 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.4) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "WidgetData/CanvasPicker.hpp" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'canvaspicker.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.4. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_CanvasPicker[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_CanvasPicker[] = { "CanvasPicker\0" }; const QMetaObject CanvasPicker::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_CanvasPicker, qt_meta_data_CanvasPicker, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &CanvasPicker::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *CanvasPicker::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *CanvasPicker::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_CanvasPicker)) return static_cast<void*>(const_cast< CanvasPicker*>(this)); return QObject::qt_metacast(_clname); } int CanvasPicker::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
KonstantinStepanovich/SIM
src/Tools/MathModelTuner/Source/moc/moc_CanvasPicker.cpp
C++
unlicense
2,168
import { IResource, SimpleCallback, ReturnCallback, ResourceType } from '../IResource' import { Readable, Writable } from 'stream' import { StandardResource } from '../std/StandardResource' import { ResourceChildren } from '../std/ResourceChildren' import { VirtualResource } from './VirtualResource' import { FSManager } from '../../../manager/v1/FSManager' import { Errors } from '../../../Errors' export class VirtualFolder extends VirtualResource { children : ResourceChildren constructor(name : string, parent ?: IResource, fsManager ?: FSManager) { super(name, parent, fsManager); this.children = new ResourceChildren(); } // ****************************** Std meta-data ****************************** // type(callback : ReturnCallback<ResourceType>) { callback(null, ResourceType.Directory) } // ****************************** Content ****************************** // write(targetSource : boolean, callback : ReturnCallback<Writable>) { callback(Errors.InvalidOperation, null); } read(targetSource : boolean, callback : ReturnCallback<Readable>) { callback(Errors.InvalidOperation, null); } mimeType(targetSource : boolean, callback : ReturnCallback<string>) { callback(Errors.NoMimeTypeForAFolder, null); } size(targetSource : boolean, callback : ReturnCallback<number>) { callback(Errors.NoSizeForAFolder, null); } // ****************************** Children ****************************** // addChild(resource : IResource, callback : SimpleCallback) { this.children.add(resource, (e) => { if(!e) resource.parent = this; callback(e); }); } removeChild(resource : IResource, callback : SimpleCallback) { this.children.remove(resource, (e) => { if(!e) resource.parent = null; callback(e); }); } getChildren(callback : ReturnCallback<IResource[]>) { callback(null, this.children.children); } }
OpenMarshal/npm-WebDAV-Server
src/resource/v1/virtual/VirtualFolder.ts
TypeScript
unlicense
2,110
package io.github.picodotdev.blogbitix.dddhexagonal.catalog.application.commandbus; public class Command { }
picodotdev/blog-ejemplos
DomainDrivenDesignHexagonalArchitecture/src/main/java/io/github/picodotdev/blogbitix/dddhexagonal/catalog/application/commandbus/Command.java
Java
unlicense
109
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>SemVerInfo - FAKE - F# Make</title> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content="Steffen Forkmann, Mauricio Scheffer, Colin Bull"> <script src="https://code.jquery.com/jquery-1.8.0.js"></script> <script src="https://code.jquery.com/ui/1.8.23/jquery-ui.js"></script> <script src="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/js/bootstrap.min.js"></script> <script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.2.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link type="text/css" rel="stylesheet" href="http://fsharp.github.io/FAKE/content/style.css" /> <script type="text/javascript" src="http://fsharp.github.io/FAKE/content/tips.js"></script> <!-- HTML5 shim, for IE6-8 support of HTML5 elements --> <!--[if lt IE 9]> <script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <div class="container"> <div class="masthead"> <ul class="nav nav-pills pull-right"> <li><a href="http://fsharp.org">fsharp.org</a></li> <li><a href="http://github.com/fsharp/fake">github page</a></li> </ul> <h3 class="muted"><a href="http://fsharp.github.io/FAKE/index.html">FAKE - F# Make</a></h3> </div> <hr /> <div class="row"> <div class="span9" id="main"> <h1>SemVerInfo</h1> <div class="xmldoc"> <p>Contains the version information.</p> </div> <h3>Record Fields</h3> <table class="table table-bordered member-list"> <thead> <tr><td>Record Field</td><td>Description</td></tr> </thead> <tbody> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1662', 1662)" onmouseover="showTip(event, '1662', 1662)"> Build </code> <div class="tip" id="1662"> <strong>Signature:</strong> string<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/SemVerHelper.fs#L43-43" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>The optional build no.</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1663', 1663)" onmouseover="showTip(event, '1663', 1663)"> Major </code> <div class="tip" id="1663"> <strong>Signature:</strong> int<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/SemVerHelper.fs#L35-35" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>MAJOR version when you make incompatible API changes.</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1664', 1664)" onmouseover="showTip(event, '1664', 1664)"> Minor </code> <div class="tip" id="1664"> <strong>Signature:</strong> int<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/SemVerHelper.fs#L37-37" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>MINOR version when you add functionality in a backwards-compatible manner.</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1665', 1665)" onmouseover="showTip(event, '1665', 1665)"> Patch </code> <div class="tip" id="1665"> <strong>Signature:</strong> int<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/SemVerHelper.fs#L39-39" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>PATCH version when you make backwards-compatible bug fixes.</p> </td> </tr> <tr> <td class="member-name"> <code onmouseout="hideTip(event, '1666', 1666)" onmouseover="showTip(event, '1666', 1666)"> PreRelease </code> <div class="tip" id="1666"> <strong>Signature:</strong> PreRelease option<br /> </div> </td> <td class="xmldoc"> <a href="https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/SemVerHelper.fs#L41-41" class="github-link"> <img src="../content/img/github.png" class="normal" /> <img src="../content/img/github-blue.png" class="hover" /> </a> <p>The optional PreRelease version</p> </td> </tr> </tbody> </table> </div> <div class="span3"> <a href="http://fsharp.github.io/FAKE/index.html"> <img src="http://fsharp.github.io/FAKE/pics/logo.png" style="width:140px;height:140px;margin:10px 0px 0px 35px;border-style:none;" /> </a> <ul class="nav nav-list" id="menu"> <li class="nav-header">FAKE - F# Make</li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/index.html">Home page</a></li> <li class="divider"></li> <li><a href="https://www.nuget.org/packages/FAKE">Get FAKE - F# Make via NuGet</a></li> <li><a href="http://github.com/fsharp/fake">Source Code on GitHub</a></li> <li><a href="http://github.com/fsharp/fake/blob/master/License.txt">License (Apache 2)</a></li> <li><a href="http://fsharp.github.io/FAKE/RELEASE_NOTES.html">Release Notes</a></li> <li><a href="http://fsharp.github.io/FAKE//contributing.html">Contributing to FAKE - F# Make</a></li> <li><a href="http://fsharp.github.io/FAKE/users.html">Who is using FAKE?</a></li> <li><a href="http://stackoverflow.com/questions/tagged/f%23-fake">Ask a question</a></li> <li class="nav-header">Tutorials</li> <li><a href="http://fsharp.github.io/FAKE/gettingstarted.html">Getting started</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/nuget.html">NuGet package restore</a></li> <li><a href="http://fsharp.github.io/FAKE/fxcop.html">Using FxCop in a build</a></li> <li><a href="http://fsharp.github.io/FAKE/assemblyinfo.html">Generating AssemblyInfo</a></li> <li><a href="http://fsharp.github.io/FAKE/create-nuget-package.html">Create NuGet packages</a></li> <li><a href="http://fsharp.github.io/FAKE/specifictargets.html">Running specific targets</a></li> <li><a href="http://fsharp.github.io/FAKE/commandline.html">Running FAKE from command line</a></li> <li><a href="http://fsharp.github.io/FAKE/parallel-build.html">Running targets in parallel</a></li> <li><a href="http://fsharp.github.io/FAKE/fsc.html">Using the F# compiler from FAKE</a></li> <li><a href="http://fsharp.github.io/FAKE/customtasks.html">Creating custom tasks</a></li> <li><a href="http://fsharp.github.io/FAKE/teamcity.html">TeamCity integration</a></li> <li><a href="http://fsharp.github.io/FAKE/canopy.html">Running canopy tests</a></li> <li><a href="http://fsharp.github.io/FAKE/octopusdeploy.html">Octopus Deploy</a></li> <li><a href="http://fsharp.github.io/FAKE/typescript.html">TypeScript support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurewebjobs.html">Azure WebJobs support</a></li> <li><a href="http://fsharp.github.io/FAKE/azurecloudservices.html">Azure Cloud Services support</a></li> <li><a href="http://fsharp.github.io/FAKE/androidpublisher.html">Android publisher</a></li> <li><a href="http://fsharp.github.io/FAKE/watch.html">File Watcher</a></li> <li class="divider"></li> <li><a href="http://fsharp.github.io/FAKE/deploy.html">Fake.Deploy</a></li> <li class="nav-header">Reference</li> <li><a href="http://fsharp.github.io/FAKE/apidocs/index.html">API Reference</a></li> </ul> </div> </div> </div> <a href="http://github.com/fsharp/fake"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a> </body> </html>
Slesa/Poseidon
src/packages/FAKE/docs/apidocs/fake-semverhelper-semverinfo.html
HTML
unlicense
9,309
'use strict'; var module = angular.module('librarium'); module.controller('GamesList', function ($scope, $resource, GamesRESTService) { $scope.breadcrumb = [ { url: 'games', name: 'Games' } ]; $scope.myData = GamesRESTService.getAllGames().query(); $scope.gridOptions = { data: 'myData' }; });
Normegil/Librarium-AngularJS
app/scripts/controllers/GamesList.js
JavaScript
unlicense
355
/* * 2007-2013 PrestaShop * * NOTICE OF LICENSE * * This source file is subject to the Academic Free License (AFL 3.0) * that is bundled with this package in the file LICENSE.txt. * It is also available through the world-wide-web at this URL: * http://opensource.org/licenses/afl-3.0.php * If you did not receive a copy of the license and are unable to * obtain it through the world-wide-web, please send an email * to license@prestashop.com so we can send you a copy immediately. * * DISCLAIMER * * Do not edit or add to this file if you wish to upgrade PrestaShop to newer * versions in the future. If you wish to customize PrestaShop for your * needs please refer to http://www.prestashop.com for more information. * * @author PrestaShop SA <contact@prestashop.com> * @copyright 2007-2013 PrestaShop SA * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0) * International Registered Trademark & Property of PrestaShop SA */ $(document).ready(function() { $('.cart_quantity_up').unbind('click').live('click', function(){upQuantity($(this).attr('id').replace('cart_quantity_up_', '')); return false;}); $('.cart_quantity_down').unbind('click').live('click', function(){downQuantity($(this).attr('id').replace('cart_quantity_down_', '')); return false;}); $('.cart_quantity_delete' ).unbind('click').live('click', function(){deleteProductFromSummary($(this).attr('id')); return false;}); $('.cart_quantity_input').typeWatch({highlight: true, wait: 600, captureLength: 0, callback: function(val) { updateQty(val, true, this.el);}}); $('.cart_address_delivery').live('change', function(){changeAddressDelivery($(this));}); cleanSelectAddressDelivery(); }); function cleanSelectAddressDelivery() { if (window.ajaxCart !== undefined) { //Removing "Ship to an other address" from the address delivery select option if there is not enought address $.each($('.cart_address_delivery'), function(it, item) { var options = $(item).find('option'); var address_count = 0; var ids = $(item).attr('id').split('_'); var id_product = ids[3]; var id_product_attribute = ids[4]; var id_address_delivery = ids[5]; $.each(options, function(i) { if ($(options[i]).val() > 0 && ($('#product_' + id_product + '_' + id_product_attribute + '_0_' + $(options[i]).val()).length == 0 // Check the address is not already used for a similare products || id_address_delivery == $(options[i]).val() ) ) address_count++; }); // Need at least two address to allow skipping products to multiple address if (address_count < 2) $($(item).find('option[value=-2]')).remove(); else if($($(item).find('option[value=-2]')).length == 0) $(item).append($('<option value="-2">' + ShipToAnOtherAddress + '</option>')); }); } } function changeAddressDelivery(obj) { var ids = obj.attr('id').split('_'); var id_product = ids[3]; var id_product_attribute = ids[4]; var old_id_address_delivery = ids[5]; var new_id_address_delivery = obj.val(); if (new_id_address_delivery == old_id_address_delivery) return; if (new_id_address_delivery > 0) // Change the delivery address { $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: 'json', data: 'controller=cart&ajax=true&changeAddressDelivery=1&summary=1&id_product=' + id_product + '&id_product_attribute='+id_product_attribute + '&old_id_address_delivery='+old_id_address_delivery + '&new_id_address_delivery='+new_id_address_delivery + '&token='+static_token + '&allow_refresh=1', success: function(jsonData) { if (typeof(jsonData.hasErrors) != 'undefined' && jsonData.hasErrors) { alert(jsonData.error); // Reset the old address $('#select_address_delivery_' + id_product + '_' + id_product_attribute + '_' + old_id_address_delivery).val(old_id_address_delivery); } else { // The product exist if ($('#product_' + id_product + '_' + id_product_attribute + '_0_' + new_id_address_delivery).length) { updateCartSummary(jsonData.summary); if (window.ajaxCart != undefined) ajaxCart.updateCart(jsonData); updateCustomizedDatas(jsonData.customizedDatas); updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); // @todo reverse the remove order // This effect remove the current line, but it's better to remove the other one, and refresshing this one $('#product_' + id_product + '_' + id_product_attribute + '_0_' + old_id_address_delivery).remove(); // @todo improve customization upgrading $('.product_' + id_product + '_' + id_product_attribute + '_0_' + old_id_address_delivery).remove(); } if (window.ajaxCart != undefined) ajaxCart.updateCart(jsonData); updateAddressId(id_product, id_product_attribute, old_id_address_delivery, new_id_address_delivery); cleanSelectAddressDelivery(); } } }); } else if (new_id_address_delivery == -1) // Adding a new address window.location = $($('.address_add a')[0]).attr('href'); else if (new_id_address_delivery == -2) // Add a new line for this product { // This test is will not usefull in the future if (old_id_address_delivery == 0) { alert(txtSelectAnAddressFirst); return false; } // Get new address to deliver var id_address_delivery = 0; var options = $('#select_address_delivery_' + id_product + '_' + id_product_attribute + '_' + old_id_address_delivery + ' option'); $.each(options, function(i) { // Check the address is not already used for a similare products if ($(options[i]).val() > 0 && $(options[i]).val() !== old_id_address_delivery && $('#product_' + id_product + '_' + id_product_attribute + '_0_' + $(options[i]).val()).length == 0) { id_address_delivery = $(options[i]).val(); return false; } }); $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: 'json', context: obj, data: 'controller=cart' + '&ajax=true&duplicate=true&summary=true' + '&id_product='+id_product + '&id_product_attribute='+id_product_attribute + '&id_address_delivery='+old_id_address_delivery + '&new_id_address_delivery='+id_address_delivery + '&token='+static_token + '&allow_refresh=1', success: function(jsonData) { if (jsonData.error) { alert(jsonData.reason); return; } var line = $('#product_' + id_product + '_' + id_product_attribute + '_0_' + old_id_address_delivery); var new_line = line.clone(); updateAddressId(id_product, id_product_attribute, old_id_address_delivery, id_address_delivery, new_line); line.after(new_line); new_line.find('input[name=quantity_' + id_product + '_' + id_product_attribute + '_0_' + old_id_address_delivery + '_hidden]') .val(1); new_line.find('.cart_quantity_input') .val(1); $('#select_address_delivery_' + id_product + '_' + id_product_attribute + '_' + old_id_address_delivery).val(old_id_address_delivery); $('#select_address_delivery_' + id_product + '_' + id_product_attribute + '_' + id_address_delivery).val(id_address_delivery); cleanSelectAddressDelivery(); updateCartSummary(jsonData.summary); if (window.ajaxCart !== undefined) ajaxCart.updateCart(jsonData); } }); } return true; } function updateAddressId(id_product, id_product_attribute, old_id_address_delivery, id_address_delivery, line) { if (typeof(line) == 'undefined' || line.length == 0) line = $('#cart_summary tr[id^=product_' + id_product + '_' + id_product_attribute + '_0_], #cart_summary tr[id^=product_' + id_product + '_' + id_product_attribute + '_nocustom_]'); $('.product_customization_for_' + id_product + '_' + id_product_attribute + '_' + old_id_address_delivery).each(function(){ $(this).attr('id', $(this).attr('id').replace(/_\d+$/, '_' + id_address_delivery)).removeClass('product_customization_for_' + id_product + '_' + id_product_attribute + '_' + old_id_address_delivery + ' address_' + old_id_address_delivery).addClass('product_customization_for_' + id_product + '_' + id_product_attribute + '_' + id_address_delivery + ' address_' + id_address_delivery); $(this).find('input[name^=quantity_]').each(function(){ if (typeof($(this).attr('name')) != 'undefined') $(this).attr('name', $(this).attr('name').replace(/_\d+(_hidden|)$/, '_' + id_address_delivery)); }); $(this).find('a').each(function(){ if (typeof($(this).attr('href')) != 'undefined') $(this).attr('href', $(this).attr('href').replace(/id_address_delivery=\d+/, 'id_address_delivery=' + id_address_delivery)); }); }); line.attr('id', line.attr('id').replace(/_\d+$/, '_' + id_address_delivery)).removeClass('address_' + old_id_address_delivery).addClass('address_' + id_address_delivery).find('span[id^=cart_quantity_custom_], span[id^=total_product_price_], input[name^=quantity_], .cart_quantity_down, .cart_quantity_up, .cart_quantity_delete').each(function(){ if (typeof($(this).attr('name')) != 'undefined') $(this).attr('name', $(this).attr('name').replace(/_\d+(_hidden|)$/, '_' + id_address_delivery)); if (typeof($(this).attr('id')) != 'undefined') $(this).attr('id', $(this).attr('id').replace(/_\d+$/, '_' + id_address_delivery)); if (typeof($(this).attr('href')) != 'undefined') $(this).attr('href', $(this).attr('href').replace(/id_address_delivery=\d+/, 'id_address_delivery=' + id_address_delivery)); }); line.find('#select_address_delivery_' + id_product + '_' + id_product_attribute + '_' + old_id_address_delivery).attr('id', 'select_address_delivery_' + id_product + '_' + id_product_attribute + '_' + id_address_delivery); if (window.ajaxCart !== undefined) { $('#cart_block_list dd, #cart_block_list dt').each(function(){ if (typeof($(this).attr('id')) != 'undefined') $(this).attr('id', $(this).attr('id').replace(/_\d+$/, '_' + id_address_delivery)); }); } } function updateQty(val, cart, el) { var prefix = ""; if (typeof(cart) == 'undefined' || cart) prefix = '#order-detail-content '; else prefix = '#fancybox-content '; var id = $(el).attr('name'); var exp = new RegExp("^[0-9]+$"); if (exp.test(val) == true) { var hidden = $(prefix + 'input[name=' + id + '_hidden]').val(); var input = $(prefix + 'input[name=' + id + ']').val(); var QtyToUp = parseInt(input) - parseInt(hidden); if (parseInt(QtyToUp) > 0) upQuantity(id.replace('quantity_', ''), QtyToUp); else if(parseInt(QtyToUp) < 0) downQuantity(id.replace('quantity_', ''), QtyToUp); } else $(prefix + 'input[name=' + id + ']').val($(prefix + 'input[name=' + id + '_hidden]').val()); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); } function deleteProductFromSummary(id) { var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = 0; ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined' && ids[2] !== 'nocustom') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: 'json', data: 'controller=cart' + '&ajax=true&delete=true&summary=true' + '&id_product='+productId + '&ipa='+productAttributeId + '&id_address_delivery='+id_address_delivery + ((customizationId !== 0) ? '&id_customization=' + customizationId : '') + '&token=' + static_token + '&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if (error !== 'indexOf') errors += jsonData.errors[error] + "\n"; } else { if (jsonData.refresh) location.reload(); if (parseInt(jsonData.summary.products.length) == 0) { if (typeof(orderProcess) == 'undefined' || orderProcess !== 'order-opc') document.location.href = document.location.href; // redirection else { $('#center_column').children().each(function() { if ($(this).attr('id') !== 'emptyCartWarning' && $(this).attr('class') !== 'breadcrumb' && $(this).attr('id') !== 'cart_title') { $(this).fadeOut('slow', function () { $(this).remove(); }); } }); $('#summary_products_label').remove(); $('#emptyCartWarning').fadeIn('slow'); } } else { $('#product_' + id).fadeOut('slow', function() { $(this).remove(); cleanSelectAddressDelivery(); if (!customizationId) refreshOddRow(); }); var exist = false; for (i=0;i<jsonData.summary.products.length;i++) { if (jsonData.summary.products[i].id_product == productId && jsonData.summary.products[i].id_product_attribute == productAttributeId && jsonData.summary.products[i].id_address_delivery == id_address_delivery && (parseInt(jsonData.summary.products[i].customization_quantity) > 0)) exist = true; } // if all customization removed => delete product line if (!exist && customizationId) $('#product_' + productId + '_' + productAttributeId + '_0_' + id_address_delivery).fadeOut('slow', function() { $(this).remove(); var line = $('#product_' + productId + '_' + productAttributeId + '_nocustom_' + id_address_delivery); if (line.length > 0) { line.find('input[name^=quantity_], .cart_quantity_down, .cart_quantity_up, .cart_quantity_delete').each(function(){ if (typeof($(this).attr('name')) != 'undefined') $(this).attr('name', $(this).attr('name').replace(/nocustom/, '0')); if (typeof($(this).attr('id')) != 'undefined') $(this).attr('id', $(this).attr('id').replace(/nocustom/, '0')); }); line.find('span[id^=total_product_price_]').each(function(){ $(this).attr('id', $(this).attr('id').replace(/_nocustom/, '')); }); line.attr('id', line.attr('id').replace(/nocustom/, '0')); } refreshOddRow(); }); } updateCartSummary(jsonData.summary); if (window.ajaxCart != undefined) ajaxCart.updateCart(jsonData); updateCustomizedDatas(jsonData.customizedDatas); updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (typeof(getCarrierListAndUpdate) !== 'undefined' && jsonData.summary.products.length > 0) getCarrierListAndUpdate(); if (typeof(updatePaymentMethodsDisplay) !== 'undefined') updatePaymentMethodsDisplay(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); } function refreshOddRow() { var odd_class = 'odd'; var even_class = 'even'; $.each($('.cart_item'), function(i, it) { if (i == 0) // First item { if ($(this).hasClass('even')) { odd_class = 'even'; even_class = 'odd'; } $(this).addClass('first_item'); } if(i % 2) $(this).removeClass(odd_class).addClass(even_class); else $(this).removeClass(even_class).addClass(odd_class); }); $('.cart_item:last-child, .customization:last-child').addClass('last_item'); } function upQuantity(id, qty) { if (typeof(qty) == 'undefined' || !qty) qty = 1; var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = 0; ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined' && ids[2] !== 'nocustom') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: 'json', data: 'controller=cart' + '&ajax=true' + '&add=true' + '&getproductprice=true' + '&summary=true' + '&id_product=' + productId + '&ipa=' + productAttributeId + '&id_address_delivery=' + id_address_delivery + ((customizationId !== 0) ? '&id_customization=' + customizationId : '') + '&qty=' + qty + '&token=' + static_token + '&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if(error !== 'indexOf') errors += $('<div />').html(jsonData.errors[error]).text() + "\n"; alert(errors); $('input[name=quantity_'+ id +']').val($('input[name=quantity_'+ id +'_hidden]').val()); } else { if (jsonData.refresh) location.reload(); updateCartSummary(jsonData.summary); if (window.ajaxCart != undefined) ajaxCart.updateCart(jsonData); if (customizationId !== 0) updateCustomizedDatas(jsonData.customizedDatas); updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); if (typeof(updatePaymentMethodsDisplay) !== 'undefined') updatePaymentMethodsDisplay(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); } function downQuantity(id, qty) { var val = $('input[name=quantity_' + id + ']').val(); var newVal = val; if(typeof(qty) == 'undefined' || !qty) { qty = 1; newVal = val - 1; } else if (qty < 0) qty = -qty; var customizationId = 0; var productId = 0; var productAttributeId = 0; var id_address_delivery = 0; var ids = 0; ids = id.split('_'); productId = parseInt(ids[0]); if (typeof(ids[1]) !== 'undefined') productAttributeId = parseInt(ids[1]); if (typeof(ids[2]) !== 'undefined' && ids[2] !== 'nocustom') customizationId = parseInt(ids[2]); if (typeof(ids[3]) !== 'undefined') id_address_delivery = parseInt(ids[3]); if (newVal > 0 || $('#product_' + id + '_gift').length) { $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, dataType: 'json', data: 'controller=cart' + '&ajax=true' + '&add=true' + '&getproductprice=true' + '&summary=true' + '&id_product='+productId + '&ipa='+productAttributeId + '&id_address_delivery='+id_address_delivery + '&op=down' + ((customizationId !== 0) ? '&id_customization='+customizationId : '') + '&qty='+qty + '&token='+static_token + '&allow_refresh=1', success: function(jsonData) { if (jsonData.hasError) { var errors = ''; for(var error in jsonData.errors) //IE6 bug fix if(error !== 'indexOf') errors += $('<div />').html(jsonData.errors[error]).text() + "\n"; alert(errors); $('input[name=quantity_' + id + ']').val($('input[name=quantity_' + id + '_hidden]').val()); } else { if (jsonData.refresh) location.reload(); updateCartSummary(jsonData.summary); if (window.ajaxCart !== undefined) ajaxCart.updateCart(jsonData); if (customizationId !== 0) updateCustomizedDatas(jsonData.customizedDatas); updateHookShoppingCart(jsonData.HOOK_SHOPPING_CART); updateHookShoppingCartExtra(jsonData.HOOK_SHOPPING_CART_EXTRA); if (newVal == 0) $('#product_' + id).hide(); if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); if (typeof(updatePaymentMethodsDisplay) !== 'undefined') updatePaymentMethodsDisplay(); } }, error: function(XMLHttpRequest, textStatus, errorThrown) { if (textStatus !== 'abort') alert("TECHNICAL ERROR: unable to save update quantity \n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus); } }); } else { deleteProductFromSummary(id); } } function updateCartSummary(json) { var i; var nbrProducts = 0; var product_list = new Array(); if (typeof json == 'undefined') return; $('div.error').fadeOut(); for (i=0;i<json.products.length;i++) product_list[json.products[i].id_product + '_' + json.products[i].id_product_attribute + '_' + json.products[i].id_address_delivery] = json.products[i]; if (!$('.multishipping-cart:visible').length) { for (i=0;i<json.gift_products.length;i++) if (typeof(product_list[json.gift_products[i].id_product + '_' + json.gift_products[i].id_product_attribute + '_' + json.gift_products[i].id_address_delivery]) !== 'undefined') product_list[json.gift_products[i].id_product + '_' + json.gift_products[i].id_product_attribute + '_' + json.gift_products[i].id_address_delivery].quantity -= json.gift_products[i].cart_quantity; } else for (i=0;i<json.gift_products.length;i++) if (typeof(product_list[json.gift_products[i].id_product + '_' + json.gift_products[i].id_product_attribute + '_' + json.gift_products[i].id_address_delivery]) == 'undefined') product_list[json.gift_products[i].id_product + '_' + json.gift_products[i].id_product_attribute + '_' + json.gift_products[i].id_address_delivery] = json.gift_products[i]; for (i in product_list) { // if reduction, we need to show it in the cart by showing the initial price above the current one var reduction = product_list[i].reduction_applies; var initial_price_text = ''; initial_price = ''; if (typeof(product_list[i].price_without_quantity_discount) !== 'undefined') initial_price = formatCurrency(product_list[i].price_without_quantity_discount, currencyFormat, currencySign, currencyBlank); var current_price = ''; if (priceDisplayMethod !== 0) current_price = formatCurrency(product_list[i].price, currencyFormat, currencySign, currencyBlank); else current_price = formatCurrency(product_list[i].price_wt, currencyFormat, currencySign, currencyBlank); if (reduction && typeof(initial_price) !== 'undefined') if (initial_price !== '' && product_list[i].price_without_quantity_discount > product_list[i].price) initial_price_text = '<span style="text-decoration:line-through;">' + initial_price + '</span><br />'; var key_for_blockcart = product_list[i].id_product + '_' + product_list[i].id_product_attribute + '_' + product_list[i].id_address_delivery; var key_for_blockcart_nocustom = product_list[i].id_product + '_' + product_list[i].id_product_attribute + '_' + ((product_list[i].id_customization && product_list[i].quantity_without_customization != product_list[i].quantity)? 'nocustom' : '0') + '_' + product_list[i].id_address_delivery; if (priceDisplayMethod !== 0) { $('#product_price_' + key_for_blockcart).html(initial_price_text + current_price); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_list[i].total_customization, currencyFormat, currencySign, currencyBlank)); else $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_list[i].total, currencyFormat, currencySign, currencyBlank)); if (product_list[i].quantity_without_customization != product_list[i].quantity) $('#total_product_price_' + key_for_blockcart_nocustom).html(formatCurrency(product_list[i].total, currencyFormat, currencySign, currencyBlank)); } else { $('#product_price_' + key_for_blockcart).html(initial_price_text + current_price); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_list[i].total_customization_wt, currencyFormat, currencySign, currencyBlank)); else $('#total_product_price_' + key_for_blockcart).html(formatCurrency(product_list[i].total_wt, currencyFormat, currencySign, currencyBlank)); if (product_list[i].quantity_without_customization != product_list[i].quantity) $('#total_product_price_' + key_for_blockcart_nocustom).html(formatCurrency(product_list[i].total_wt, currencyFormat, currencySign, currencyBlank)); } $('input[name=quantity_' + key_for_blockcart_nocustom + ']').val(product_list[i].id_customization? product_list[i].quantity_without_customization : product_list[i].cart_quantity); $('input[name=quantity_' + key_for_blockcart_nocustom + '_hidden]').val(product_list[i].id_customization? product_list[i].quantity_without_customization : product_list[i].cart_quantity); if (typeof(product_list[i].customizationQuantityTotal) !== 'undefined' && product_list[i].customizationQuantityTotal > 0) $('#cart_quantity_custom_' + key_for_blockcart).html(product_list[i].customizationQuantityTotal); nbrProducts += parseInt(product_list[i].quantity); } // Update discounts if (json.discounts.length == 0) { $('.cart_discount').each(function(){$(this).remove();}); $('.cart_total_voucher').remove(); } else { if ($('.cart_discount').length == 0) location.reload(); if (priceDisplayMethod !== 0) $('#total_discount').html('-' + formatCurrency(json.total_discounts_tax_exc, currencyFormat, currencySign, currencyBlank)); else $('#total_discount').html('-' + formatCurrency(json.total_discounts, currencyFormat, currencySign, currencyBlank)); $('.cart_discount').each(function(){ var idElmt = $(this).attr('id').replace('cart_discount_',''); var toDelete = true; for (i=0;i<json.discounts.length;i++) if (json.discounts[i].id_discount == idElmt) { if (json.discounts[i].value_real !== '!') { if (priceDisplayMethod !== 0) $('#cart_discount_' + idElmt + ' td.cart_discount_price span.price-discount').html(formatCurrency(json.discounts[i].value_tax_exc * -1, currencyFormat, currencySign, currencyBlank)); else $('#cart_discount_' + idElmt + ' td.cart_discount_price span.price-discount').html(formatCurrency(json.discounts[i].value_real * -1, currencyFormat, currencySign, currencyBlank)); } toDelete = false; } if (toDelete) $('#cart_discount_' + idElmt + ', #cart_total_voucher').fadeTo('fast', 0, function(){ $(this).remove(); }); }); } // Block cart $('#cart_block_shipping_cost').show(); $('#cart_block_shipping_cost').next().show(); if (json.total_shipping > 0) { if (priceDisplayMethod !== 0) { $('#cart_block_shipping_cost').html(formatCurrency(json.total_shipping_tax_exc, currencyFormat, currencySign, currencyBlank)); $('#cart_block_wrapping_cost').html(formatCurrency(json.total_wrapping_tax_exc, currencyFormat, currencySign, currencyBlank)); $('#cart_block_total').html(formatCurrency(json.total_price_without_tax, currencyFormat, currencySign, currencyBlank)); } else { $('#cart_block_shipping_cost').html(formatCurrency(json.total_shipping, currencyFormat, currencySign, currencyBlank)); $('#cart_block_wrapping_cost').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#cart_block_total').html(formatCurrency(json.total_price, currencyFormat, currencySign, currencyBlank)); } } else { if (json.carrier.id == null) { $('#cart_block_shipping_cost').hide(); $('#cart_block_shipping_cost').next().hide(); } } $('#cart_block_tax_cost').html(formatCurrency(json.total_tax, currencyFormat, currencySign, currencyBlank)); $('.ajax_cart_quantity').html(nbrProducts); // Cart summary $('#summary_products_quantity').html(nbrProducts + ' ' + (nbrProducts > 1 ? txtProducts : txtProduct)); if (priceDisplayMethod !== 0) $('#total_product').html(formatCurrency(json.total_products, currencyFormat, currencySign, currencyBlank)); else $('#total_product').html(formatCurrency(json.total_products_wt, currencyFormat, currencySign, currencyBlank)); $('#total_price').html(formatCurrency(json.total_price, currencyFormat, currencySign, currencyBlank)); $('#total_price_without_tax').html(formatCurrency(json.total_price_without_tax, currencyFormat, currencySign, currencyBlank)); $('#total_tax').html(formatCurrency(json.total_tax, currencyFormat, currencySign, currencyBlank)); $('.cart_total_delivery').show(); if (json.total_shipping > 0) { if (priceDisplayMethod !== 0) $('#total_shipping').html(formatCurrency(json.total_shipping_tax_exc, currencyFormat, currencySign, currencyBlank)); else $('#total_shipping').html(formatCurrency(json.total_shipping, currencyFormat, currencySign, currencyBlank)); } else { if (json.carrier.id != null) $('#total_shipping').html(freeShippingTranslation); else $('.cart_total_delivery').hide(); } if (json.free_ship > 0 && !json.is_virtual_cart) { $('.cart_free_shipping').fadeIn(); $('#free_shipping').html(formatCurrency(json.free_ship, currencyFormat, currencySign, currencyBlank)); } else $('.cart_free_shipping').hide(); if (json.total_wrapping > 0) { $('#total_wrapping').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#total_wrapping').parent().show(); } else { $('#total_wrapping').html(formatCurrency(json.total_wrapping, currencyFormat, currencySign, currencyBlank)); $('#total_wrapping').parent().hide(); } } function updateCustomizedDatas(json) { for(var i in json) for(var j in json[i]) for(var k in json[i][j]) for(var l in json[i][j][k]) { var quantity = json[i][j][k][l]['quantity']; $('input[name=quantity_' + i + '_' + j + '_' + l + '_' + k + '_hidden]').val(quantity); $('input[name=quantity_' + i + '_' + j + '_' + l + '_' + k + ']').val(quantity); } } function updateHookShoppingCart(html) { $('#HOOK_SHOPPING_CART').html(html); } function updateHookShoppingCartExtra(html) { $('#HOOK_SHOPPING_CART_EXTRA').html(html); } function refreshDeliveryOptions() { $.each($('.delivery_option_radio'), function() { if ($(this).prop('checked')) { if ($(this).parent().find('.delivery_option_carrier.not-displayable').length == 0) $(this).parent().find('.delivery_option_carrier').show(); var carrier_id_list = $(this).val().split(','); carrier_id_list.pop(); var it = this; $(carrier_id_list).each(function() { $(it).parent().find('input[value="' + this.toString() + '"]').change(); }); } else $(this).parent().find('.delivery_option_carrier').hide(); }); } $(document).ready(function() { refreshDeliveryOptions(); $('.delivery_option_radio').live('change', function() { refreshDeliveryOptions(); }); $('#allow_seperated_package').live('click', function() { $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: baseUri + '?rand=' + new Date().getTime(), async: true, cache: false, data: 'controller=cart&ajax=true&allowSeperatedPackage=true&value=' + ($(this).prop('checked') ? '1' : '0') + '&token='+static_token + '&allow_refresh=1', success: function(jsonData) { if (typeof(getCarrierListAndUpdate) !== 'undefined') getCarrierListAndUpdate(); } }); }); $('#gift').checkboxChange(function() { $('#gift_div').show('slow'); }, function() { $('#gift_div').hide('slow'); }); $('#enable-multishipping').checkboxChange( function() { $('.standard-checkout').hide(0); $('.multishipping-checkout').show(0); }, function() { $('.standard-checkout').show(0); $('.multishipping-checkout').hide(0); } ); }); function updateExtraCarrier(id_delivery_option, id_address) { var url = ""; if(typeof(orderOpcUrl) !== 'undefined') url = orderOpcUrl; else url = orderUrl; $.ajax({ type: 'POST', headers: { "cache-control": "no-cache" }, url: url + '?rand=' + new Date().getTime(), async: true, cache: false, dataType : "json", data: 'ajax=true' + '&method=updateExtraCarrier' + '&id_address='+id_address + '&id_delivery_option='+id_delivery_option + '&token='+static_token + '&allow_refresh=1', success: function(jsonData) { $('#HOOK_EXTRACARRIER_' + id_address).html(jsonData['content']); } }); }
MrChip/FlowerShop
ShopFlower.Web/App_Themes/themes/FlowerShop/js/cart-summary.js
JavaScript
unlicense
33,008
<!DOCTYPE html> <html> <head> <title>[GopherJS] Animate.css Test Demo</title> <meta charset="utf-8" /> <meta name="viewport" content="initial-scale=1, minimal-ui" /> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css" /> <style>body{ text-align: center; }</style> </head> <body> <header> <div> <h1 id="animationSandbox">Animate.css</h1> </div> </header> <main role="content"> <div> <form> <select id="animate-select"> <optgroup label="Attention Seekers"> <option value="bounce">bounce</option> <option value="flash">flash</option> <option value="pulse">pulse</option> <option value="rubberBand">rubberBand</option> <option value="shake">shake</option> <option value="swing">swing</option> <option value="tada">tada</option> <option value="wobble">wobble</option> <option value="jello">jello</option> </optgroup> <optgroup label="Bouncing Entrances"> <option value="bounceIn">bounceIn</option> <option value="bounceInDown">bounceInDown</option> <option value="bounceInLeft">bounceInLeft</option> <option value="bounceInRight">bounceInRight</option> <option value="bounceInUp">bounceInUp</option> </optgroup> <optgroup label="Bouncing Exits"> <option value="bounceOut">bounceOut</option> <option value="bounceOutDown">bounceOutDown</option> <option value="bounceOutLeft">bounceOutLeft</option> <option value="bounceOutRight">bounceOutRight</option> <option value="bounceOutUp">bounceOutUp</option> </optgroup> <optgroup label="Fading Entrances"> <option value="fadeIn">fadeIn</option> <option value="fadeInDown">fadeInDown</option> <option value="fadeInDownBig">fadeInDownBig</option> <option value="fadeInLeft">fadeInLeft</option> <option value="fadeInLeftBig">fadeInLeftBig</option> <option value="fadeInRight">fadeInRight</option> <option value="fadeInRightBig">fadeInRightBig</option> <option value="fadeInUp">fadeInUp</option> <option value="fadeInUpBig">fadeInUpBig</option> </optgroup> <optgroup label="Fading Exits"> <option value="fadeOut">fadeOut</option> <option value="fadeOutDown">fadeOutDown</option> <option value="fadeOutDownBig">fadeOutDownBig</option> <option value="fadeOutLeft">fadeOutLeft</option> <option value="fadeOutLeftBig">fadeOutLeftBig</option> <option value="fadeOutRight">fadeOutRight</option> <option value="fadeOutRightBig">fadeOutRightBig</option> <option value="fadeOutUp">fadeOutUp</option> <option value="fadeOutUpBig">fadeOutUpBig</option> </optgroup> <optgroup label="Flippers"> <option value="flip">flip</option> <option value="flipInX">flipInX</option> <option value="flipInY">flipInY</option> <option value="flipOutX">flipOutX</option> <option value="flipOutY">flipOutY</option> </optgroup> <optgroup label="Lightspeed"> <option value="lightSpeedIn">lightSpeedIn</option> <option value="lightSpeedOut">lightSpeedOut</option> </optgroup> <optgroup label="Rotating Entrances"> <option value="rotateIn">rotateIn</option> <option value="rotateInDownLeft">rotateInDownLeft</option> <option value="rotateInDownRight">rotateInDownRight</option> <option value="rotateInUpLeft">rotateInUpLeft</option> <option value="rotateInUpRight">rotateInUpRight</option> </optgroup> <optgroup label="Rotating Exits"> <option value="rotateOut">rotateOut</option> <option value="rotateOutDownLeft">rotateOutDownLeft</option> <option value="rotateOutDownRight">rotateOutDownRight</option> <option value="rotateOutUpLeft">rotateOutUpLeft</option> <option value="rotateOutUpRight">rotateOutUpRight</option> </optgroup> <optgroup label="Sliding Entrances"> <option value="slideInUp">slideInUp</option> <option value="slideInDown">slideInDown</option> <option value="slideInLeft">slideInLeft</option> <option value="slideInRight">slideInRight</option> </optgroup> <optgroup label="Sliding Exits"> <option value="slideOutUp">slideOutUp</option> <option value="slideOutDown">slideOutDown</option> <option value="slideOutLeft">slideOutLeft</option> <option value="slideOutRight">slideOutRight</option> </optgroup> <optgroup label="Zoom Entrances"> <option value="zoomIn">zoomIn</option> <option value="zoomInDown">zoomInDown</option> <option value="zoomInLeft">zoomInLeft</option> <option value="zoomInRight">zoomInRight</option> <option value="zoomInUp">zoomInUp</option> </optgroup> <optgroup label="Zoom Exits"> <option value="zoomOut">zoomOut</option> <option value="zoomOutDown">zoomOutDown</option> <option value="zoomOutLeft">zoomOutLeft</option> <option value="zoomOutRight">zoomOutRight</option> <option value="zoomOutUp">zoomOutUp</option> </optgroup> <optgroup label="Specials"> <option value="hinge">hinge</option> <option value="rollIn">rollIn</option> <option value="rollOut">rollOut</option> </optgroup> </select> <button id="animate-btn" type="button">Animate it</button> </form> </div> </main> <script src="app.js"></script> </body> </html>
siongui/userpages
content/code/gopherjs/animate.css-test/index.html
HTML
unlicense
5,854
#include <iostream> #include <sstream> #include <string> #include <vector> #include <deque> #include <queue> #include <set> #include <map> #include <algorithm> #include <functional> #include <utility> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <cstring> #include <stdio.h> #include <tr1/unordered_map> #include <tr1/unordered_set> using namespace std; #define LL long long #define pb push_back #define mp make_pair #define hashmap unordered_map #define hashset unordered_set #define contains(hs, key) ((hs).find((key))!=(hs).end()) #define REP(i,n) for(int (i)=0;(i)<(int)(n);(i)++) #define REP2(i,j,n) for(int (i)=(j);(i)<(int)(n);(i)++) #define REPD(i,j,n) for(int (i)=(j);(i)>=(int)(n);(i)--) #define REPC(i,j,expr) for(int (i)=(j);expr;(i)++) #define foreach(c,itr) for(__typeof((c).begin()) itr=(c).begin();itr!=(c).end();itr++) #define ALL(lst) (lst).begin(), (lst).end() #define inbounds(i,j,a,b) ((i)>=(a)&(i)<=(b)&(j)>=(a)&(j)<=(b)) #define bitcount(n) __builtin_popcount(n) #define DEBUG 1 #define debug(x) { if(DEBUG) cerr << #x << " = " << x << endl; } #define debugv(x) { if (DEBUG) cerr << #x << " = "; foreach((x), it) cerr << *it << ", "; cout << endl; } const double PI = 3.1415926535897932384626433832795; const int MAXN = 200; char aa[] = {'A', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y' }; double mass[] = {71.03711, 103.00919, 115.02694, 129.04259, 147.06841, 57.02146, 137.05891, 113.08406, 128.09496, 113.08406, 131.04049, 114.04293, 97.05276, 128.05858, 156.10111, 87.03203, 101.04768, 99.06841, 186.07931, 163.06333 }; map<double, char> mass_table; int n, target; char graph[MAXN][MAXN]; int p[MAXN]; vector<double> ions; vector<char> ans; bool dfs(int v, vector<char> cur) { if (cur.size() > ans.size()) { ans = cur; } bool ans = false; REP2(to, v + 1, n) if (graph[v][to] != '-') { p[to] = v; vector<char> cur2(ALL(cur)); ans = (ans || dfs(to, cur2)); } return ans; } int main() { #ifndef ONLINE_JUDGE freopen("rosalind_full.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif REP(i, 20) mass_table[floor(mass[i] * 100) / 100] = aa[i]; double total; cin >> total; double ion; while (cin >> ion) ions.push_back(ion); n = ions.size(); target = (ions.size() - 2) / 2; debug(target); fill_n(p, MAXN, -1); REP(i, MAXN) REP(j, MAXN) graph[i][j] = '-'; REP(i, n) REP2(j, i + 1, n) if (contains(mass_table, floor((ions[j] - ions[i]) * 100) / 100)) graph[i][j] = mass_table[floor((ions[j] - ions[i]) * 100) / 100]; vector<char> v; REP(i, n) if (dfs(i, v)) { foreach(ans, itr) cout << *itr; break; } return 0; }
cnt0/rosalind
quick-and-dirty/c++/Rosalind_FULL.cpp
C++
unlicense
3,392
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>vFabric Hyperic 5.7 : Multiprocess Service</title> <link rel="stylesheet" href="styles/site.css" type="text/css" /> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <b><a href="vFabric Hyperic 5.7.html" title="vFabric Hyperic 5.7 Documentation Home">vFabric Hyperic 5.7 Documentation Home (Internal)</a> - <a href="https://www.vmware.com/support/pubs/vfabric-hyperic.html">vFabric Hyperic 5.7 Documentation Home (Online)</a> - <a href="https://www.vmware.com/support/vfabric-hyperic/doc/vfabric-hyperic-rn-5.7.html">Hyperic 5.7 Release Notes</a> </b> <p> <p> <table class="pagecontent" border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="#ffffff"> <tr> <td valign="top" class="pagebody"> <div class="pageheader"> <span class="pagetitle"> vFabric Hyperic 5.7 : Multiprocess Service </span> </div> <div class="pagesubheading"> This page last changed on Jan 04, 2012 by <font color="#0050B2">mmcgarry</font>. </div> <p><font color="gray"><em>Topics marked with</em></font> <font color="red">*</font> <font color="gray"><em>relate to features available only in vFabric Hyperic.</em></font></p> <style type='text/css'>/*<![CDATA[*/ div.rbtoc1325699983989 {margin-left: 1.5em;padding: 0px;} div.rbtoc1325699983989 ul {list-style: disc;margin-left: 0px;padding-left: 20px;} div.rbtoc1325699983989 li {margin-left: 0px;padding-left: 0px;} /*]] >*/</style><div class='rbtoc1325699983989'> <ul> <li><a href='#MultiprocessService-Multiprocess'>Multiprocess</a></li> <li><a href='#MultiprocessService-SpecifyingProcessQueries'>Specifying Process Queries</a></li> <li><a href='#MultiprocessService-CreateMultiprocessServiceinHyperic'>Create Multiprocess Service in Hyperic</a></li> <li><a href='#MultiprocessService-ProcessServiceConfigurationOptions'>Process Service Configuration Options</a></li> <li><a href='#MultiprocessService-ProcessServiceMetrics'>Process Service Metrics</a></li> </ul></div> <h1><a name="MultiprocessService-Multiprocess"></a>Multiprocess</h1> <p>You can configure Hyperic to monitor a set of processs.</p> <h1><a name="MultiprocessService-SpecifyingProcessQueries"></a>Specifying Process Queries</h1> <p>You specify a query statement that identifies the processes you wish to monitor. You specify queries using <em>Process Table Query Language</em> (PTQL), a simple query language for finding processes based based on their attributes.</p> <p>PTQL queries take this form:</p> <p><tt>Class.Attribute.operator=value</tt></p> <p>Where:</p> <ul> <li><tt>Class</tt> &#8212; is the name of the Sigar class minus the Proc prefix.</li> <li><tt>Attribute</tt> &#8212; is an attribute of the given Class, index into an array or key in a Map class.</li> <li><tt>operator</tt> &#8212; is one of the following (for String values): <ul> <li><tt>eq</tt> &#8212; Equal to value</li> <li><tt>ne</tt> &#8212; Not Equal to value</li> <li><tt>ew</tt> &#8212; Ends with value</li> <li><tt>sw</tt> &#8212; Starts with value</li> <li><tt>ct</tt> &#8212; Contains value (substring)</li> <li><tt>re</tt> &#8212; Regular expression value matches</li> </ul> </li> </ul> <p>Delimit queries with a comma.</p> <p>For example, this query statement finds a JBoss instance by looking for a process whose name is "org.jboss.Main":</p> <p><tt>State.Name.eq=java,Args.*.eq=org.jboss.Main</tt></p> <p>this query statement finds the OpenSSH daemon by looking for sshd PID file. </p> <p><tt>Pid.PidFile.eq=/var/run/sshd.pid</tt></p> <p>For more examples, see the <tt>pdk/lib/.sigar_shellrc</tt> file included in the Hyperic Agent distribution and the Sigar PTQL Documentation at <a href="http://support.hyperic.com/display/SIGAR/Home">http://support.hyperic.com/display/SIGAR/Home</a>.</p> <h1><a name="MultiprocessService-CreateMultiprocessServiceinHyperic"></a>Create Multiprocess Service in Hyperic</h1> <p>To create a Multirocess service: </p> <ol> <li>Navigate to the platform where the process runs.</li> <li>Select <b>New Platform Service</b> from the <b>Tools</b> menu.&nbsp;</li> <li>Name the service.</li> <li>Select "Multiprocess" from the <b>Service Type</b> pull-down.</li> <li>Click <b>Edit</b> in the "Configuration Properties" section of the new service's <b>Inventory</b> page.</li> <li>On the <b>Configuration Properties</b> page, supply at least the required properties, described in the table below.</li> </ol> <h1><a name="MultiprocessService-ProcessServiceConfigurationOptions"></a>Process Service Configuration Options </h1> <div class='table-wrap'> <table class='confluenceTable'><tbody> <tr> <th class='confluenceTh'> Name </th> <th class='confluenceTh'> Description </th> <th class='confluenceTh'> Required </th> <th class='confluenceTh'> Example </th> <th class='confluenceTh'> Notes </th> </tr> <tr> <td class='confluenceTd'> process.query </td> <td class='confluenceTd'>A PTQL statement, which contains one or more PTQL queries, that identifies the processrd to monitor. </td> <td class='confluenceTd'> Yes </td> <td class='confluenceTd'>&nbsp;</td> <td class='confluenceTd'>&nbsp;</td> </tr> </tbody></table> </div> <h1><a name="MultiprocessService-ProcessServiceMetrics"></a>Process Service Metrics </h1> <p>Each instance of a <b>Process</b> service provides the following metrics: </p> <div class='table-wrap'> <table class='confluenceTable'><tbody> <tr> <th class='confluenceTh'>Name </th> <th class='confluenceTh'>Alias </th> <th class='confluenceTh'>Units </th> <th class='confluenceTh'>Category </th> <th class='confluenceTh'>Default On </th> <th class='confluenceTh'>Default Interval</th> </tr> <tr> <td class='confluenceTd'>Availability </td> <td class='confluenceTd'>Availability </td> <td class='confluenceTd'>percentage </td> <td class='confluenceTd'>AVAILABILITY </td> <td class='confluenceTd'>true </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Number of Processes </td> <td class='confluenceTd'>NumProcesses </td> <td class='confluenceTd'>none </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>true </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Memory Size </td> <td class='confluenceTd'>MemSize </td> <td class='confluenceTd'>B </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>5 min</td> </tr> <tr> <td class='confluenceTd'>Resident Memory Size </td> <td class='confluenceTd'>ResidentMemSize </td> <td class='confluenceTd'>B </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>true </td> <td class='confluenceTd'>5 min</td> </tr> <tr> <td class='confluenceTd'>Cpu System Time</td> <td class='confluenceTd'>SystemTime </td> <td class='confluenceTd'>ms </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Cpu System Time per Minute </td> <td class='confluenceTd'>SystemTime1m </td> <td class='confluenceTd'>ms </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Cpu User Time </td> <td class='confluenceTd'>UserTime </td> <td class='confluenceTd'>ms </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Cpu User Time per Minute </td> <td class='confluenceTd'>UserTime1m </td> <td class='confluenceTd'>ms </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Cpu Total Time </td> <td class='confluenceTd'>TotalTime </td> <td class='confluenceTd'>ms </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Cpu Total Time per Minute </td> <td class='confluenceTd'>TotalTime1m </td> <td class='confluenceTd'>ms </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>false </td> <td class='confluenceTd'>10 min</td> </tr> <tr> <td class='confluenceTd'>Cpu Usage </td> <td class='confluenceTd'>Usage </td> <td class='confluenceTd'>percentage </td> <td class='confluenceTd'>UTILIZATION </td> <td class='confluenceTd'>true </td> <td class='confluenceTd'>5 min</td> </tr> </tbody></table> </div> </td> </tr> </table> <table border="0" cellpadding="0" cellspacing="0" width="100%"> <tr> <td height="12" background="http://support.hyperic.com/images/border/border_bottom.gif"><img src="images/border/spacer.gif" width="1" height="1" border="0"/></td> </tr> <tr> <td align="center"><font color="grey">Document generated by Confluence on Oct 01, 2012 10:07</font></td> </tr> </table> </body> </html>
cc14514/hq6
hq-web/src/main/webapp/ui_docs/DOC_OLD/Multiprocess Service.html
HTML
unlicense
9,276
import { ChatMessage } from '../../shared/models/chat-message'; import { Component, ChangeDetectionStrategy, OnInit, Input } from '@angular/core'; import { UserService } from '../../shared/services/user.service'; @Component({ selector: 'ddo-message', templateUrl: './message.component.html', styleUrls: ['./message.component.css'], changeDetection: ChangeDetectionStrategy.OnPush }) export class MessageComponent implements OnInit { @Input() message: ChatMessage; constructor(public userService: UserService) { } ngOnInit() { } isMyMessage(): boolean { return this.message.author === this.userService.getUser().pseudo; } }
orange-devrap/devdays-chat
src/app/chat/message/message.component.ts
TypeScript
unlicense
653
<?php header("Cache-Control: max-age=0"); $state = $_GET["state"]." "; echo "set state to $state"; $file = fopen("/home/pi/thermostat/ramdisk/thermostat.ipcfile", "r+"); fseek($file, 60); fwrite($file, substr($state." ",0,20)); fflush($file); fclose($file); echo "file closed"; ?>
baldingwizard/thermostatpi
thermostat/html/write_state.php
PHP
unlicense
329
package de.uni_hamburg.informatik.swt.se2.mediathek.werkzeuge.vormerken; import java.util.ArrayList; import java.util.List; import de.uni_hamburg.informatik.swt.se2.mediathek.materialien.Kunde; import de.uni_hamburg.informatik.swt.se2.mediathek.materialien.medien.Medium; public class VormerkKarte { Medium _medium; List<Kunde> _kunden; public VormerkKarte(Medium m, Kunde k) { _medium = m; _kunden = new ArrayList<Kunde>(); _kunden.add(k); } public Kunde getKunde(int platz) { if(_kunden.size() > platz) { return _kunden.get(platz); } return null; } }
polemonium/SE2Project
src/de/uni_hamburg/informatik/swt/se2/mediathek/werkzeuge/vormerken/VormerkKarte.java
Java
unlicense
602
<?php if (!defined('BASEPATH')) exit('No direct script access allowed'); require dirname(__FILE__) . DIRECTORY_SEPARATOR . 'basecontroller.php'; class Page extends Basecontroller { public function __construct() { parent::__construct(); $this->load->model('Page_model', 'page'); } public function accessRules() { return array( '@' => array('statistics'), // všetci prihlásený používatelia //'1' => array('update', 'delete'), // rola 1 ma pristup k metode update a delete ); } public function index() { $this->load->view('header'); $this->load->view('page/index'); $this->load->view('footer'); } public function contact(){ $this->load->multiview(array('header','page/contact','footer')); } public function statistics(){ $d = new stdClass(); $d->dogs = $this->db->count_all('dog'); $d->kennels = $this->db->count_all('kennel'); $d->kennelsactive = $this->page->getCountActiveKennels(); $d->litters = $this->db->count_all('litter'); $data['d'] = $d; $this->load->multiview(array('header','page/statistics','footer'), $data); } public function newest(){ $d = new stdClass(); $this->load->model('Dog_model', 'dog'); $dogs = $this->dog->getAllDogs(0, 6, 'dog__id', 'DESC'); $data['dogs'] = $dogs; $kennels = $this->page->getKennels(); $data['kennels'] = $kennels; $data['bonitations'] = $this->dog->searchNewestBonitation(6); $this->load->multiview(array('header','page/newest','footer'), $data); } public function search(){ $this->load->multiview(array('header','page/search','footer')); } public function runSearch(){ $this->load->model('Dog_model', 'dog'); $posty = $this->input->post(); echo "<h2>Výsledky vyhľadávania</h2>"; $vysledky = $this->dog->searchDog($posty); if(empty($vysledky)) echo "Nenájdený žiaden jedinec spĺňajúci tieto kritériá!"; else{ echo "<table class='detail-kennel vysledokvyhladavania'><tr><th>Meno</th><th>Registračné číslo</th><th>Narodenie</th><th>Pohlavie</th><th>Plemeno</th><th>Chovnosť</th><th>Matka</th><th>Otec</th></tr>"; foreach($vysledky as $v){ echo "<tr>"; echo "<td>".anchor("dog/show/".$v->dog__id."/".preg_replace('/\s+/','',$v->dog__name), $v->dog__name)."</td>"; echo "<td>".$v->dog__new_regnumber."</td>"; echo "<td>".date('d.m.Y', strtotime($v->dog__birthday))."</td>"; echo "<td>".$v->dog__gender."</td>"; echo "<td class='uzka'>".$v->dog__breed."</td>"; echo "<td>".$v->dog__breeding."</td>"; echo "<td>".anchor("dog/show/".$v->dog__id_mother."/".preg_replace('/\s+/','',$v->m_name),$v->m_name." ")."</td>"; echo "<td>".anchor("dog/show/".$v->dog__id_father."/".preg_replace('/\s+/','',$v->t_name),$v->t_name." ")."</td>"; echo "</tr>"; } echo "</table>"; } } }
Autista/csv
application/controllers/page.php
PHP
unlicense
3,337
pleeease-brunch =============== [Process CSS with ease](https://github.com/iamvdo/pleeease), and [Brunch](https://github.com/brunch/brunch). ##Install `npm install --save pleeease-brunch` ##Add options All options are in `brunch-config` file, in the `plugins.pleeease` section, for example: ```javascript plugins: pleeease: autoprefixer: browsers: ['last 3 versions'] rem: ['20px'] ``` Note that pleeease-brunch is an optimizer, so it runs only when `optimize` is set to `true`. ##Preprocessors Pleeease makes so easy to combine preprocessors and PostCSS. Set which one you want to use from options. For example Stylus and Autoprefixer: ```javascript plugins: pleeease: stylus: true autoprefixer: browsers: ['last 3 versions'] ``` ##Sourcemaps Brunch concatenates files and manages sourcemaps on its own. But, if you `@import` CSS files using Pleeease, you can force sourcemaps generation for these files too. Simply add `plugin.pleeease.sourcemaps: true` option in your `brunch-config` file. ##Options See [Pleeease](http://pleeease.io/docs/#features). ##Changelog 3.0.0 - 03-09-2016 - Update to Pleeease 4 2.0.1 - 08-14-2015 - Fix package creation 2.0.0 - 08-13-2015 - Match Pleeease v3
tiagosatur/guyon
node_modules/pleeease-brunch/README.md
Markdown
unlicense
1,246
all: # do nothing install_dotfiles: ./install.sh
Aluriak/dotfiles
Makefile
Makefile
unlicense
53
use std::cmp::{Ordering, min}; use std::fs::File; use std::io::{BufWriter, Write, Read}; use chrono::{DateTime, NaiveDateTime, Utc}; use serializable::Serializable; use serializable::SerializeError; use byteorder::{ReadBytesExt, WriteBytesExt, BigEndian}; #[derive(Debug, Clone)] pub struct Cliente { pub codigo: u32, pub nome: String, // 50 bytes of utf-8 in the file pub data_nascimento: DateTime<Utc>, } impl PartialEq for Cliente { fn eq(&self, other: &Cliente) -> bool { self.codigo == other.codigo } } impl PartialOrd for Cliente { fn partial_cmp(&self, other: &Cliente) -> Option<Ordering> { Some(self.codigo.cmp(&other.codigo)) } } impl Serializable for Cliente { fn serialize(&self, file: &mut File) -> Result<(), SerializeError> { let mut file = BufWriter::new(file); if self.codigo == 3763629520 { println!("entra aqui arrombado"); } file.write_u32::<BigEndian>(self.codigo)?; let bytes = self.nome.as_bytes(); let boundary = min(50, bytes.len()); let diff = 50 - boundary; file.write_all(&bytes[..boundary])?; for _ in 0..diff { file.write_u8(0)?; } file.write_i64::<BigEndian>(self.data_nascimento.timestamp())?; Ok(()) } fn deserialize(file: &mut File) -> Result<Cliente, SerializeError> { let codigo = file.read_u32::<BigEndian>()?; let mut nome = [0; 50]; file.read_exact(&mut nome)?; let nul_pos = nome.iter().position(|&c| c == b'\0').unwrap_or(nome.len()); let nome = String::from_utf8(nome[..nul_pos].to_vec())?; let data_nascimento = file.read_i64::<BigEndian>()?; let data_nascimento = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(data_nascimento, 0), Utc); Ok(Cliente {codigo, nome, data_nascimento}) } }
vitorhnn/estruturas-de-dados-2
nway-merge/rust/nway_merge/src/cliente.rs
Rust
unlicense
1,912
import scrapy import re from research.items import ResearchItem import sys reload(sys) sys.setdefaultencoding('utf-8') class CaltechSpider(scrapy.Spider): name = "WISC" allowed_domains = ["cs.wisc.edu"] start_urls = ["https://www.cs.wisc.edu/research/groups"] def parse(self, response): item = ResearchItem() for sel in response.xpath('//table[@class="views-table cols-2"]'): item['groupname'] = sel.xpath('caption/text()').extract()[0] item['proflist'] = [] for selp in sel.xpath('.//div[@class="views-field views-field-name-1"]/span/a'): tmpname = selp.xpath('text()').extract() print str(tmpname) item['proflist'].append(tmpname) yield item
doge-search/webdoge
liqian/WISC/research/research/spiders/WISCSpider.py
Python
unlicense
678
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _07.Sum_Seconds { class Program { static void Main(string[] args) { var t1 = int.Parse(Console.ReadLine()); var t2 = int.Parse(Console.ReadLine()); var t3 = int.Parse(Console.ReadLine()); var sum = t1 + t2 + t3; var min = 0; if (sum < 59) { min = 0; } else if (sum > 59 && sum < 120) { min = 1; } else if (sum >= 120 && sum < 179) { min = 2; } var sec = sum - min * 60; Console.Write(min); Console.Write(":"); if (sec < 10) { Console.Write("0"); } Console.WriteLine(sec); } } }
GoldenR1618/SoftUni-Exercises-and-Exams
02.Programming_Basics/03. Simple Conditional Statements/07. Sum Seconds/Program.cs
C#
unlicense
960
# liskak Lisk Army Knife - Forging failover and command line lisk :warning: <br /> After configuration, the following examples perform a donation to the address **8858064098621060602L** (hmachado):<br /> ```./liskak.sh -s 10``` *# sends 10 LSK to 8858064098621060602L*<br /> ```./liskak.sh -t 10 8858064098621060602L``` *# transfers 10 LSK to 8858064098621060602L*<br /> Thank you all and go Lisk go! ![LiskAK proposed setup for monitoring](https://github.com/filipealmeida/liskak/blob/master/docs/liskak_proposed_setup.jpg) # Foreword Last weekend, while educating a couple of individuals on javascript, they started asking a lot of questions on how to achieve many things in nodejs. They wanted to have their lisk delegate nodes monitored, healthy and having at least one forging.<br /> ...And then to check their balance<br /> ...And then to transfer lisks from the command line<br /> ...And then to check sync status<br /> ...And then to list their votes<br /> ...And then to vote for many delegates.<br /> ...And then a lot of other stuff.<br /> <br /> The following script insued. # DISCLAIMER This script is immature and in need of many tests. Nonetheless, since it proved it's worth and is allegedly usefull for the lisk community, here it is. Pay close attention to the USAGE below, there are some flags that are self explanatory but not detailed in this README file. Should you want features: ask! Will add it whenever I can. Do as you will, have a delegation! # Installing Lisk Army Knife You'll need to have node version above v4.0.0 on the path. To install node 4.x on Ubuntu: ``` curl -sL https://deb.nodesource.com/setup_4.x | sudo -E bash - sudo apt-get install -y nodejs ``` Then, download the master from github and: 1. unzip liskak-master.zip 2. # Configure the file liskak.json in the liskak-master/src folder to reflect your account 3. cd liskak-master 4. npm install 5. ./liskak.sh --help ## Windows 1. Use the nodejs installer to install NODE + NPM 2. # Configure the file liskak.json in the liskak-master/src folder to reflect your account 3. npm install 4. liskak.bat --help You can always run issuing "node src/liskak.js ARGS" # Available options: ``` someuser@foo:~/liskak$ ./liskak.sh --help USAGE: node liskak.js [OPTION1] [OPTION2]... arg1 arg2... The following options are supported: -c, --configuration <ARG1> Path to the configuration json file (defaults to ./liskak.json) -i, --info Displays your account info -N, --newAccount Creates a new account -b, --balance <ARG1> Displays an account's balance -d, --getHeight Get block height -L, --logLevel <ARG1> Logging level, one of: error, warn, info verbose, debug, silly ("info" by default) -l, --listVotes <ARG1> Lists your votes -V, --listVoters <ARG1> Lists your voters -U, --shareWithVoters <ARG1> Share ARG1 percent / value of your account funds with your voters. -I, --upvote <ARG1> Vote for delegates in file specified -O, --downvote <ARG1> Remove vote from delegates in file specified -C, --checkVotes Checks current votes, compares with upvote/downvote data in files (flags -I and -O) -r, --replaceVotes Set the upvotes exactly as provided by the upvote list from -I flag -A, --commitVotes Executes your voting orders with upvote/downvote data in files (flags -I and -O); check first with -C flag for action list -v, --voteForIrondizzy Allow a spare voting slot to go to "hmachado" -y, --isForging Test if forging -Y, --enableForging Enable forging -W, --disableForging Disable forging -z, --status Reports on sync status of node -s, --donate <ARG1> Donate LSK to this great cause, default: 5 -t, --transfer <ARG1> <ARG2> Transfer LSK to an address from your configured account: -t LSK ADDRESS -T, --lsktransfer <ARG1> <ARG2> Transfer LSK^-8 to an address from your configured account: -T LSK ADDRESS -m, --multitransfer <ARG1>...<ARGN> Transfer LSK to a list of addresses from your configured account: -t LSK ADDRESS [ADDRESS] ... -M, --multilsktransfer <ARG1>...<ARGN> Transfer LSK^-8 to a list of addresses from your configured account: -t LSK ADDRESS [ADDRESS] ... -f, --failoverMonkey <ARG1>...<ARGN> Provide a list of available nodes for forging failover; stays awake and acts on blockchain and connection failures -Z, --measureOnSyncOnly Takes measures of consensus only while syncing -E, --switchConfirmation <ARG1> Wait for N cycles before switching ("3" by default) -S, --supervise <ARG1> Provide lisk path to manage lisk process locally (handles fork3, etc.) -K, --liskscript <ARG1> Provide absolute path for lisk script: lisk.sh for operations (supervise implied) -J, --logfile <ARG1> Provide absolute path for lisk logfile (supervise implied) -B, --minutesWithoutBlock <ARG1> Minutes without blocks before issuing a rebuild, default is disabled (0) -Q, --consensus <ARG1> <ARG2> Broadhash consensus threshold (%), reload if under value for N consecutive samples ("0,10" by default) -q, --inadequateBroadhash Restart on "Inadequate broadhash consensus" message -R, --reloadSchedule <ARG1> Restart after N minutes if not forging, supervise only, 0 means disabled -P, --pollingInterval <ARG1> Interval between node polling in milliseconds ("10000" by default) -w, --apiRequestTimeout <ARG1> API request timeout, 0 means disabled -F, --maxFailures <ARG1> Maximum failures tolerated when chatting with lisk nodes ("10" by default) -D, --maxBlocksDelayed <ARG1> Maximum number of block difference between nodes before change forging node -X, --testMode Test mode ``` # Usage examples ### Failover forging and node monitoring LiskAK running with the failoverMonkey flag will always try to have forging enabled at the best possible node using always forge tactics with a few tweaks, the tweaks being: * Flag: ```-Q 51 2``` -> don't switch to better consensus if consensus is above 51% * Flag: ```-D 2``` -> don't switch to better height if height of current forging node is under 2 of difference ***NOTE #0:*** Forging failover is under tests due to the poor scoring technique used in the past couple of weeks. If you run into trouble, checkout 82ef27cb3f803693b466938852071dafb117fabc or use the code provided at https://github.com/4miners/always-forge Example: ``` someuser@foo:~/liskak$ ./liskak.sh -c /home/foo/my_forger_configuration.json -f http://172.17.0.2:8000 http://172.17.0.3:8000 http://172.17.0.4:8000 -P 3000 -w 3000 2017-01-02T20:43:34.498Z INFO Initializing 2017-01-02T20:43:34.504Z INFO Failover monkey starting: ["http://172.17.0.2:8000","http://172.17.0.3:8000","http://172.17.0.4:8000"] 2017-01-02T20:43:34.505Z INFO Enabling monitor for node http://172.17.0.2:8000 2017-01-02T20:43:34.506Z INFO Enabling monitor for node http://172.17.0.3:8000 2017-01-02T20:43:34.506Z INFO Enabling monitor for node http://172.17.0.4:8000 2017-01-02T20:43:37.508Z INFO Probe cycle 0 2017-01-02T20:43:37.549Z INFO Evaluation cycle 0 2017-01-02T20:43:37.549Z WARN Server http://172.17.0.3:8000/ removed from forge failover list (syncing or failed) 2017-01-02T20:43:37.550Z WARN Server http://172.17.0.4:8000/ removed from forge failover list (syncing or failed) 2017-01-02T20:43:37.550Z INFO Iteration 1: best server is: http://172.17.0.2:8000/ 2017-01-02T20:43:37.550Z INFO Warming up, no action; Forge failover will be active in 2 cycles 2017-01-02T20:43:37.551Z INFO Forging is ENABLED at http://172.17.0.2:8000/ ...... 2017-01-02T20:44:58.307Z INFO Evaluation cycle 24 2017-01-02T20:44:58.307Z WARN Server http://172.17.0.3:8000/ removed from forge failover list (syncing or failed) 2017-01-02T20:44:58.307Z WARN Server http://172.17.0.4:8000/ removed from forge failover list (syncing or failed) 2017-01-02T20:44:58.307Z INFO Iteration 25: best server is: http://172.17.0.2:8000/ 2017-01-02T20:44:58.307Z INFO Summary: http://172.17.0.4:8000/[-] http://172.17.0.3:8000/[-] http://172.17.0.2:8000/[*] ...... ``` Additional usage of this can be found in the bundled scripts, `monitorMain.sh` and `monitorTest.sh`. These files include everything needed to enable forging monitoring. Each script has an associated config file, `liskak_testnet.json` and `liskak_mainnet.json` in the `src/` folder. Simply add the delegate secret you wish you monitor to that file. Then edit the monitoring script for the network you will be monitoring and include your hosts. Example: ``` HOST1="http://127.0.0.1:8000" HOST2="" HOST3="" HOST4= CONFIG="src/liskak_mainnet.json" LOG_FILE="logs/forgingMain.log" pkill -f $CONFIG -9 nohup bash liskak.sh -c $CONFIG -f $HOST1 $HOST2 $HOST3 $HOST4 > $LOG_FILE 2>&1& ``` Using mainnet as an example, the script using `bash monitorMain.sh`. The logs for this will be found in `logs/`, this can be watched to see the monitoring in action. ### Supervision of node and automatic restarts/reloads 1. Fork 1: issues rebuild but requires work to do this only if you forged the last block (please open an issue with loglines such as this so it can be corrected) 2. Fork 2: issues a lisk restart 3. Fork 3: issues a rebuild 4. If "-B <MINUTES>" flag set, rebuild is issued if no blocks occur in <MINUTES> Please advise for further rules by opening an issue. Example #1: Lisk 0.3.1 and below, assumes app.log and lisk.sh under the folder provided ``` someuser@foo:~/liskak$ ./liskak.sh -S /opt/lisk 2016-06-03T17:09:37.562Z INFO Initializing 2016-06-03T17:09:37.593Z INFO Looking at the lisk log file "/opt/lisk/app.log" 2016-06-03T17:09:37.594Z INFO Lisk shell script found: /opt/lisk/lisk.sh 2016-06-03T17:09:37.631Z INFO Tailing /opt/lisk/app.log 2016-06-03T17:11:45.103Z ERROR Node has forked with cause: 3, issuing rebuild 2016-06-03T17:11:45.109Z WARN Performing "bash lisk.sh rebuild" ``` Example #2: If you have lisk.sh and or app.log on other locations, use the following flavour ``` someuser@foo:~/liskak$ ./liskak.sh -J /path/to/app.log -K /path/to/lisk.sh 2016-06-03T17:09:37.562Z INFO Initializing 2016-06-03T17:09:37.593Z INFO Looking at the lisk log file "/opt/lisk/app.log" 2016-06-03T17:09:37.594Z INFO Lisk shell script found: /opt/lisk/lisk.sh 2016-06-03T17:09:37.631Z INFO Tailing /opt/lisk/app.log 2016-06-03T17:11:45.103Z ERROR Node has forked with cause: 3, issuing rebuild 2016-06-03T17:11:45.109Z WARN Performing "bash lisk.sh rebuild" ``` WARNING: this surelly won't work in windows; please donate to buy a copy :) Example #3: Additional usage of supervise is included in a bundled script `monitorNode.sh`. This script will automatically monitor your node and rebuild after 5 minutes using the default settings for lisk. In order to be used on mainnet the script will need to be modified. Please note that this script assumes lisk installation defaults, if your lisk installation is not default you will also need to modify those parameters. ``` RELEASE="test" <-- This needs to read main instead of test. LISK_LOG="/home/$USER/lisk-$RELEASE/logs/lisk_$RELEASE.app.log" LISK_SH="/home/$USER/lisk-$RELEASE/lisk.sh" LOG_FILE="logs/monitorNode.log" MINUTES="5" CONFIG="src/liskak_testnet.json" <-- This should read mainnet instead of testnet pkill -f $LISK_LOG -9 nohup bash liskak.sh -c $CONFIG -J $LISK_LOG -K $LISK_SH -B $MINUTES > $LOG_FILE 2>&1& ``` ### New account If executed with the -N flag, Lisk Army Knife will produce a new key for you which you can use as an account. Store it or add it to your liskak.json file to keep it. If this flag is set, all other flags will use it. ``` someuser@foo:~/liskak$ ./liskak.sh -N New account passphrase is: "you spike license country refuse barely turkey session online siege page broken" xprivate: "xprv9s21ZrQH143K3zFueQ4cz5FwotnficAWw52YTmDxXTFLvH4aikwuRyAmyrZgrLvvguD3dZLroUBt7AzsM9RdPNftUdTnxgCWD5hjJzZbBdm" ``` ### Balance and information After creating your new account, produce a liskak.json file either on the src dir replacing it's contents or writing to a new file, like ~/liskak_new.json It's contents will be: ``` { "secret": "you spike license country refuse barely turkey session online siege page broken", "host":"localhost", "port":8001, "proto": "https" } ``` Now let's use the new file ``` someuser@foo:~/liskak$ ./liskak.sh -c ~/liskak_new.json -i 2016-05-28T13:40:26.633Z INFO Initializing Lisk account info for /home/someuser/liskak/liskak_new.json address = 1985049510400127319L unconfirmedBalance = 0 balance = 0 publicKey = 6625586ab0aeed824b83e9e1eff64694367eb51f80173852f13a10133c0aa985 unconfirmedSignature = 0 secondSignature = 0 secondPublicKey = null multisignatures = null u_multisignatures = null ``` We're using the default from now on, so keep in mind it's the liskak.json file under the src folder "liskak-master/src/liskak.json" ### Transfering funds If you have balance, you can transfer funds. Transfering 1 LSK to an account, both commands below are the same: ``` someuser@foo:~/liskak$ ./liskak.sh -t 1 18217073061291465384L 2016-05-28T18:25:36.223Z INFO Initializing Transfering 1 LSKs to 18217073061291465384L 2016-05-28T18:25:36.498Z INFO Issuing transfer transactionId = 3519123441717401234 someuser@foo:~/liskak$ ./liskak.sh -T 100000000 18217073061291465384L 2016-05-28T18:25:36.223Z INFO Initializing Transfering 1 LSKs to 18217073061291465384L 2016-05-28T18:25:36.498Z INFO Issuing transfer transactionId = 3519123441717401234 ``` ### Forging Pretty much intuitive: #### Check status ``` someuser@foo:~/liskak$ ./liskak.sh -y 2016-05-28T15:46:43.919Z INFO Initializing Forging ENABLED ``` #### Enable ``` someuser@foo:~/liskak$ ./liskak.sh -W 2016-05-28T15:48:48.650Z INFO Initializing address = 81237192873981739812L ``` #### Disable ``` someuser@foo:~/liskak$ ./liskak.sh -Y 2016-05-28T15:48:52.171Z INFO Initializing address = 81237192873981739812L ``` #### In case of error: You'll see something like this: ``` someuser@foo:~/liskak$ ./liskak.sh -Y 2016-05-28T15:48:45.382Z INFO Initializing 2016-05-28T15:48:45.913Z ERROR Could not get handle the response:{"success":false,"error":"Forging is already enabled"} ``` ### Voting You can compare your votes to your lists #### List your issued votes ``` someuser@foo:~/liskak$ ./liskak.sh -l 2016-05-28T15:05:37.961Z INFO Initializing 2016-05-28T15:05:38.438Z INFO Issuing listDelegates LiskAddress;DelegateName 16979702222780220012L;some 26951091333643074042L;delegate 92873422225441394187L;otehr 75395111111117926082L;hodor ... ``` #### Compare your votes with textfiles with upvotes/downvotes Now you want to add some (upvotes) to your list or remove some (downvotes) Produce a couple of text files (none required, but both possible) 1. One with the usernames or addresses (one per line) of the delegates you want to upvote, let's call it "in.txt". 2. Other with the usernames or addresses (one per line) of the delegates you want to downvote, "out.txt". Now run the command: ``` someuser@foo:~/liskak$ ./liskak.sh -l -C -I in.txt -O out.txt 2016-05-28T15:13:46.118Z INFO Initializing 2016-05-28T15:13:46.598Z INFO Issuing listDelegates 2016-05-28T15:13:47.199Z INFO Loading 565 delegates in memory. 2016-05-28T15:13:47.200Z INFO Issuing listDelegates 2016-05-28T15:13:47.201Z INFO Issuing listDelegates 2016-05-28T15:13:47.202Z INFO Issuing listDelegates 2016-05-28T15:13:47.203Z INFO Issuing listDelegates 2016-05-28T15:13:47.205Z INFO Issuing listDelegates 2016-05-28T15:13:47.207Z INFO Issuing listDelegates some already has your vote. delegate already has your vote. hodor already has your vote. You have voted in 101 of 101 You will downvote 2 You will upvote 0 You may still vote in 2 delegates after this You will have 99 of 101 votes from your account ``` The output is pretty intuitive, it'll list your votes and then report on your files, tell you how many votes you have now, how many, etc. #### Commit your votes with textfiles with upvotes/downvotes Just add the -A flag: ``` someuser@foo:~/liskak$ ./liskak.sh -vl -C -I in.txt -O out.txt -A 2016-05-28T15:17:46.118Z INFO Initializing 2016-05-28T15:17:46.292Z INFO Issuing listDelegates 2016-05-28T15:17:46.344Z INFO Loading 565 delegates in memory. 2016-05-28T15:17:46.398Z INFO Issuing listDelegates 2016-05-28T15:17:47.401Z INFO Issuing listDelegates 2016-05-28T15:17:47.402Z INFO Issuing listDelegates 2016-05-28T15:17:47.403Z INFO Issuing listDelegates 2016-05-28T15:17:47.405Z INFO Issuing listDelegates 2016-05-28T15:17:47.407Z INFO Issuing listDelegates some already has your vote. delegate already has your vote. hodor already has your vote. other will be upvoted. 2016-05-28T15:17:52.125Z WARN 1iiii6979707772780220012L is not a valid delegate ... 2016-05-28T15:17:52.562Z INFO {"success":true,"transaction":{"type":3,"amount":0,"senderPublicKey": .... ``` Please notice, LISK api aparently doesn't support downvoting+upvoting in the same requests. Should the response indicate insucess, first downvote with the "-O FILE -A" flags and then upvote with the "-I FILE -A" flags.
filipealmeida/liskak
README.md
Markdown
unlicense
17,509
djforms =============== Django applications that manage data submitted by the campus community. Logs project requires a logs directory in the djforms directory, writeable by webserver. cd djforms mkdir logs touch logs/debug.log chmod 666 logs/debug.log Required third party packages: See requirements.txt TrustCommerce python library: https://vnvault.trustcommerce.com/downloads/tclink-4.2.0-python.tar.gz _Required but woefully out of date:_ django-profile http://code.google.com/p/django-profile/ Here's a fork of the original on github: https://github.com/tualatrix/django-profile Archived and not updated since 2013: https://github.com/stephrdev/django-userprofiles _Apps list for Migrations_ admin, admindocs, admissions, admitted, auth, bootstrapform, captcha, catering, characterquest, choral, classnotes, committee_letter, contenttypes, copyprint, core, django_countries, djtools, genomics, giving, green, honeypot, humanize, imagekit, languages, lis, memory, metamorphosis, printrequest, processors, proposal, registration, scholars, security, sites, soccer, summer_camp, taggit, userprofile, visitdays, writingcurriculum
carthagecollege/django-djforms
README.md
Markdown
unlicense
1,144
/* A heading with the background reaching the right side of its container, If the container isn't `f-content`, then the heading will *leak* out. <pre> BLOCK f-right-heading </pre> ## Container with padding ``` <div class="kalei-background-white"><!-- only here for the style guide - should not be used on the website --> <div class="f-content"> <!-- this should be used on the website --> <h1 class="f-right-heading">About the FUCK</h1> <!-- this should be used on the website --> </div> <!-- only here for the style guide - should not be used on the website --> </div> ``` ## Leaking out of container ``` <div class="kalei-background-white"><!-- only here for the style guide - should not be used on the website --> <!-- this should be used on the website --> <h1 class="f-right-heading">About the FUCK</h1> <!-- this should be used on the website --> </div><!-- only here for the style guide - should not be used on the website --> ``` */ @import "../variables"; .f-right-heading { margin: 0 -var(--gutter-width) 2.8rem 0; padding: .8rem var(--gutter-width) .8rem 1.93rem; color: var(--color-white); font-size: 2.8rem; background-color: var(--color-black); }
Firefund/styleguide
styles/blocks/f-right-heading.css
CSS
unlicense
1,184
using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Xml.XPath; using FoodServicesMenu.Areas.HelpPage.ModelDescriptions; namespace FoodServicesMenu.Areas.HelpPage { /// <summary> /// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file. /// </summary> public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider { private XPathNavigator _documentNavigator; private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; private const string ParameterExpression = "param[@name='{0}']"; /// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="documentPath">The physical path to XML document.</param> public XmlDocumentationProvider(string documentPath) { if (documentPath == null) { throw new ArgumentNullException("documentPath"); } XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); } public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return GetTagValue(typeNode, "summary"); } public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "summary"); } public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) { ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; if (reflectedParameterDescriptor != null) { XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); if (methodNode != null) { string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); if (parameterNode != null) { return parameterNode.Value.Trim(); } } } return null; } public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "returns"); } public string GetDocumentation(MemberInfo member) { string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); return GetTagValue(propertyNode, "summary"); } public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); } private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) { ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; if (reflectedActionDescriptor != null) { string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); return _documentNavigator.SelectSingleNode(selectExpression); } return null; } private static string GetMemberName(MethodInfo method) { string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0) { string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); } return name; } private static string GetTagValue(XPathNavigator parentNode, string tagName) { if (parentNode != null) { XPathNavigator node = parentNode.SelectSingleNode(tagName); if (node != null) { return node.Value.Trim(); } } return null; } private XPathNavigator GetTypeNode(Type type) { string controllerTypeName = GetTypeName(type); string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); return _documentNavigator.SelectSingleNode(selectExpression); } private static string GetTypeName(Type type) { string name = type.FullName; if (type.IsGenericType) { // Format the generic type name to something like: Generic{System.Int32,System.String} Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); } if (type.IsNested) { // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. name = name.Replace("+", "."); } return name; } } }
hillbillybob/MockWebAPI-FSMenu
FoodServicesMenu/Areas/HelpPage/XmlDocumentationProvider.cs
C#
unlicense
7,036
using System; using System.Collections.Generic; using ModestTree; namespace Zenject { public abstract class StaticMemoryPoolBase<TValue> : IDespawnableMemoryPool<TValue>, IDisposable where TValue : class, new() { readonly Stack<TValue> _stack = new Stack<TValue>(); Action<TValue> _onDespawnedMethod; int _activeCount; public StaticMemoryPoolBase(Action<TValue> onDespawnedMethod) { _onDespawnedMethod = onDespawnedMethod; StaticMemoryPoolRegistry.Add(this); } public Action<TValue> OnDespawnedMethod { set { _onDespawnedMethod = value; } } public int NumTotal { get { return NumInactive + NumActive; } } public int NumActive { get { return _activeCount; } } public int NumInactive { get { return _stack.Count; } } public Type ItemType { get { return typeof(TValue); } } public void Resize(int desiredPoolSize) { Assert.That(desiredPoolSize >= 0, "Attempted to resize the pool to a negative amount"); while (_stack.Count > desiredPoolSize) { _stack.Pop(); } while (desiredPoolSize > _stack.Count) { _stack.Push(Alloc()); } Assert.IsEqual(_stack.Count, desiredPoolSize); } public void Dispose() { StaticMemoryPoolRegistry.Remove(this); } public void ClearActiveCount() { _activeCount = 0; } public void Clear() { Resize(0); } public void ShrinkBy(int numToRemove) { Resize(_stack.Count - numToRemove); } public void ExpandBy(int numToAdd) { Resize(_stack.Count + numToAdd); } TValue Alloc() { return new TValue(); } protected TValue SpawnInternal() { TValue element; if (_stack.Count == 0) { element = Alloc(); } else { element = _stack.Pop(); } _activeCount++; return element; } void IMemoryPool.Despawn(object item) { Despawn((TValue)item); } public void Despawn(TValue element) { if (_onDespawnedMethod != null) { _onDespawnedMethod(element); } if (_stack.Count > 0 && ReferenceEquals(_stack.Peek(), element)) { ModestTree.Log.Error("Despawn error. Trying to destroy object that is already released to pool."); } Assert.That(!_stack.Contains(element), "Attempted to despawn element twice!"); _activeCount--; _stack.Push(element); } } // Zero parameters public class StaticMemoryPool<TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TValue> where TValue : class, new() { Action<TValue> _onSpawnMethod; public StaticMemoryPool( Action<TValue> onSpawnMethod = null, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { _onSpawnMethod = onSpawnMethod; } public Action<TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn() { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(item); } return item; } } // One parameter public class StaticMemoryPool<TParam1, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TValue> where TValue : class, new() { Action<TParam1, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 param) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(param, item); } return item; } } // Two parameter public class StaticMemoryPool<TParam1, TParam2, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TValue> where TValue : class, new() { Action<TParam1, TParam2, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TParam2, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TParam2, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, item); } return item; } } // Three parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TValue> where TValue : class, new() { Action<TParam1, TParam2, TParam3, TValue> _onSpawnMethod; public StaticMemoryPool( Action<TParam1, TParam2, TParam3, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public Action<TParam1, TParam2, TParam3, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, item); } return item; } } // Four parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, item); } return item; } } // Five parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, item); } return item; } } // Six parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, p6, item); } return item; } } // Seven parameters public class StaticMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> : StaticMemoryPoolBase<TValue>, IMemoryPool<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> where TValue : class, new() { #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> _onSpawnMethod; public StaticMemoryPool( #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> onSpawnMethod, Action<TValue> onDespawnedMethod = null) : base(onDespawnedMethod) { // What's the point of having a param otherwise? Assert.IsNotNull(onSpawnMethod); _onSpawnMethod = onSpawnMethod; } public #if !NET_4_6 ModestTree.Util. #endif Action<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TValue> OnSpawnMethod { set { _onSpawnMethod = value; } } public TValue Spawn(TParam1 p1, TParam2 p2, TParam3 p3, TParam4 p4, TParam5 p5, TParam6 p6, TParam7 p7) { var item = SpawnInternal(); if (_onSpawnMethod != null) { _onSpawnMethod(p1, p2, p3, p4, p5, p6, p7, item); } return item; } } }
Zesix/Impulse
Assets/Plugins/Zenject/Source/Factories/Pooling/Static/StaticMemoryPool.cs
C#
unlicense
12,214
from __future__ import division #brings in Python 3.0 mixed type calculation rules import logging import numpy as np import pandas as pd class TerrplantFunctions(object): """ Function class for Stir. """ def __init__(self): """Class representing the functions for Sip""" super(TerrplantFunctions, self).__init__() def run_dry(self): """ EEC for runoff for dry areas """ self.out_run_dry = (self.application_rate / self.incorporation_depth) * self.runoff_fraction return self.out_run_dry def run_semi(self): """ EEC for runoff to semi-aquatic areas """ self.out_run_semi = (self.application_rate / self.incorporation_depth) * self.runoff_fraction * 10 return self.out_run_semi def spray(self): """ EEC for spray drift """ self.out_spray = self.application_rate * self.drift_fraction return self.out_spray def total_dry(self): """ EEC total for dry areas """ self.out_total_dry = self.out_run_dry + self.out_spray return self.out_total_dry def total_semi(self): """ EEC total for semi-aquatic areas """ self.out_total_semi = self.out_run_semi + self.out_spray return self.out_total_semi def nms_rq_dry(self): """ Risk Quotient for NON-LISTED MONOCOT seedlings exposed to Pesticide X in a DRY area """ self.out_nms_rq_dry = self.out_total_dry / self.ec25_nonlisted_seedling_emergence_monocot return self.out_nms_rq_dry def loc_nms_dry(self): """ Level of concern for non-listed monocot seedlings exposed to pesticide X in a dry area """ msg_pass = "The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk." msg_fail = "The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_nms_rq_dry] self.out_nms_loc_dry = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) # exceed_boolean = self.out_nms_rq_dry >= 1.0 # self.out_nms_loc_dry = exceed_boolean.map(lambda x: # 'The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk.' if x == True # else 'The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal.') return self.out_nms_loc_dry def nms_rq_semi(self): """ Risk Quotient for NON-LISTED MONOCOT seedlings exposed to Pesticide X in a SEMI-AQUATIC area """ self.out_nms_rq_semi = self.out_total_semi / self.ec25_nonlisted_seedling_emergence_monocot return self.out_nms_rq_semi def loc_nms_semi(self): """ Level of concern for non-listed monocot seedlings exposed to pesticide X in a semi-aquatic area """ msg_pass = "The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk." msg_fail = "The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_nms_rq_semi] self.out_nms_loc_semi = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_nms_rq_semi >= 1.0 #self.out_nms_loc_semi = exceed_boolean.map(lambda x: # 'The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk.' if x == True # else 'The risk quotient for non-listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal.') return self.out_nms_loc_semi def nms_rq_spray(self): """ Risk Quotient for NON-LISTED MONOCOT seedlings exposed to Pesticide X via SPRAY drift """ self.out_nms_rq_spray = self.out_spray / self.out_min_nms_spray return self.out_nms_rq_spray def loc_nms_spray(self): """ Level of concern for non-listed monocot seedlings exposed to pesticide via spray drift """ msg_pass = "The risk quotient for non-listed monocot seedlings exposed to the pesticide via spray drift indicates a potential risk." msg_fail = "The risk quotient for non-listed monocot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_nms_rq_spray] self.out_nms_loc_spray = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_nms_rq_spray >= 1.0 #self.out_nms_loc_spray = exceed_boolean.map(lambda x: # 'The risk quotient for non-listed monocot seedlings exposed to the pesticide via spray drift indicates a potential risk.' if x == True # else 'The risk quotient for non-listed monocot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal.') return self.out_nms_loc_spray def lms_rq_dry(self): """ Risk Quotient for LISTED MONOCOT seedlings exposed to Pesticide X in a DRY areas """ self.out_lms_rq_dry = self.out_total_dry / self.noaec_listed_seedling_emergence_monocot return self.out_lms_rq_dry def loc_lms_dry(self): """ Level of concern for listed monocot seedlings exposed to pesticide via runoff in a dry area """ msg_pass = "The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk." msg_fail = "The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_lms_rq_dry] self.out_lms_loc_dry = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lms_rq_dry >= 1.0 #self.out_lms_loc_dry = exceed_boolean.map(lambda x: # 'The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk.' if x == True # else 'The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal.') return self.out_lms_loc_dry def lms_rq_semi(self): """ Risk Quotient for LISTED MONOCOT seedlings exposed to Pesticide X in a SEMI-AQUATIC area """ self.out_lms_rq_semi = self.out_total_semi / self.noaec_listed_seedling_emergence_monocot return self.out_lms_rq_semi def loc_lms_semi(self): """ Level of concern for listed monocot seedlings exposed to pesticide X in semi-aquatic areas """ msg_pass = "The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk." msg_fail = "The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_lms_rq_semi] self.out_lms_loc_semi = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lms_rq_semi >= 1.0 #self.out_lms_loc_semi = exceed_boolean.map(lambda x: # 'The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk.' if x == True # else 'The risk quotient for listed monocot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal.') return self.out_lms_loc_semi def lms_rq_spray(self): """ Risk Quotient for LISTED MONOCOT seedlings exposed to Pesticide X via SPRAY drift """ self.out_lms_rq_spray = self.out_spray / self.out_min_lms_spray return self.out_lms_rq_spray def loc_lms_spray(self): """ Level of concern for listed monocot seedlings exposed to pesticide X via spray drift """ msg_pass = "The risk quotient for listed monocot seedlings exposed to the pesticide via spray drift indicates a potential risk." msg_fail = "The risk quotient for listed monocot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_lms_rq_spray] self.out_lms_loc_spray = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lms_rq_spray >= 1.0 #self.out_lms_loc_spray = exceed_boolean.map(lambda x: # 'The risk quotient for listed monocot seedlings exposed to the pesticide via spray drift indicates a potential risk.' if x == True # else 'The risk quotient for listed monocot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal.') return self.out_lms_loc_spray def nds_rq_dry(self): """ Risk Quotient for NON-LISTED DICOT seedlings exposed to Pesticide X in DRY areas """ self.out_nds_rq_dry = self.out_total_dry / self.ec25_nonlisted_seedling_emergence_dicot return self.out_nds_rq_dry def loc_nds_dry(self): """ Level of concern for non-listed dicot seedlings exposed to pesticide X in dry areas """ msg_pass = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk." msg_fail = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_nds_rq_dry] self.out_nds_loc_dry = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_nds_rq_dry >= 1.0 #self.out_nds_loc_dry = exceed_boolean.map(lambda x: # 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk.' if x == True # else 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal.') return self.out_nds_loc_dry def nds_rq_semi(self): """ Risk Quotient for NON-LISTED DICOT seedlings exposed to Pesticide X in SEMI-AQUATIC areas """ self.out_nds_rq_semi = self.out_total_semi / self.ec25_nonlisted_seedling_emergence_dicot return self.out_nds_rq_semi def loc_nds_semi(self): """ Level of concern for non-listed dicot seedlings exposed to pesticide X in semi-aquatic areas """ msg_pass = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk." msg_fail = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_nds_rq_semi] self.out_nds_loc_semi = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_nds_rq_semi >= 1.0 #self.out_nds_loc_semi = exceed_boolean.map(lambda x: #'The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk.' if x == True # else 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal.') return self.out_nds_loc_semi def nds_rq_spray(self): """ # Risk Quotient for NON-LISTED DICOT seedlings exposed to Pesticide X via SPRAY drift """ self.out_nds_rq_spray = self.out_spray / self.out_min_nds_spray return self.out_nds_rq_spray def loc_nds_spray(self): """ Level of concern for non-listed dicot seedlings exposed to pesticide X via spray drift """ msg_pass = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk." msg_fail = "The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_nds_rq_spray] self.out_nds_loc_spray = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_nds_rq_spray >= 1.0 #self.out_nds_loc_spray = exceed_boolean.map(lambda x: # 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk.' if x == True # else 'The risk quotient for non-listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal.') return self.out_nds_loc_spray def lds_rq_dry(self): """ Risk Quotient for LISTED DICOT seedlings exposed to Pesticide X in DRY areas """ self.out_lds_rq_dry = self.out_total_dry / self.noaec_listed_seedling_emergence_dicot return self.out_lds_rq_dry def loc_lds_dry(self): """ Level of concern for listed dicot seedlings exposed to pesticideX in dry areas """ msg_pass = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk." msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_lds_rq_dry] self.out_lds_loc_dry = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lds_rq_dry >= 1.0 #self.out_lds_loc_dry = exceed_boolean.map(lambda x: # 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates a potential risk.' if x == True # else 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to dry areas indicates that potential risk is minimal.') return self.out_lds_loc_dry def lds_rq_semi(self): """ Risk Quotient for LISTED DICOT seedlings exposed to Pesticide X in SEMI-AQUATIC areas """ self.out_lds_rq_semi = self.out_total_semi / self.noaec_listed_seedling_emergence_dicot return self.out_lds_rq_semi def loc_lds_semi(self): """ Level of concern for listed dicot seedlings exposed to pesticide X in dry areas """ msg_pass = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk." msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_lds_rq_semi] self.out_lds_loc_semi = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lds_rq_semi >= 1.0 #self.out_lds_loc_semi = exceed_boolean.map(lambda x: # 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates a potential risk.' if x == True # else 'The risk quotient for listed dicot seedlings exposed to the pesticide via runoff to semi-aquatic areas indicates that potential risk is minimal.') return self.out_lds_loc_semi def lds_rq_spray(self): """ Risk Quotient for LISTED DICOT seedlings exposed to Pesticide X via SPRAY drift """ self.out_lds_rq_spray = self.out_spray / self.out_min_lds_spray return self.out_lds_rq_spray def loc_lds_spray(self): """ Level of concern for listed dicot seedlings exposed to pesticide X via spray drift """ msg_pass = "The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk." msg_fail = "The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal." boo_ratios = [ratio >= 1.0 for ratio in self.out_lds_rq_spray] self.out_lds_loc_spray = pd.Series([msg_pass if boo else msg_fail for boo in boo_ratios]) #exceed_boolean = self.out_lds_rq_spray >= 1.0 #self.out_lds_loc_spray = exceed_boolean.map( # lambda x: # 'The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates a potential risk.' if x == True # else 'The risk quotient for listed dicot seedlings exposed to the pesticide via spray drift indicates that potential risk is minimal.') return self.out_lds_loc_spray def min_nms_spray(self): """ determine minimum toxicity concentration used for RQ spray drift values non-listed monocot EC25 and NOAEC """ s1 = pd.Series(self.ec25_nonlisted_seedling_emergence_monocot, name='seedling') s2 = pd.Series(self.ec25_nonlisted_vegetative_vigor_monocot, name='vegetative') df = pd.concat([s1, s2], axis=1) self.out_min_nms_spray = pd.DataFrame.min(df, axis=1) return self.out_min_nms_spray def min_lms_spray(self): """ determine minimum toxicity concentration used for RQ spray drift values listed monocot EC25 and NOAEC """ s1 = pd.Series(self.noaec_listed_seedling_emergence_monocot, name='seedling') s2 = pd.Series(self.noaec_listed_vegetative_vigor_monocot, name='vegetative') df = pd.concat([s1, s2], axis=1) self.out_min_lms_spray = pd.DataFrame.min(df, axis=1) return self.out_min_lms_spray def min_nds_spray(self): """ determine minimum toxicity concentration used for RQ spray drift values non-listed dicot EC25 and NOAEC """ s1 = pd.Series(self.ec25_nonlisted_seedling_emergence_dicot, name='seedling') s2 = pd.Series(self.ec25_nonlisted_vegetative_vigor_dicot, name='vegetative') df = pd.concat([s1, s2], axis=1) self.out_min_nds_spray = pd.DataFrame.min(df, axis=1) return self.out_min_nds_spray def min_lds_spray(self): """ determine minimum toxicity concentration used for RQ spray drift values listed dicot EC25 and NOAEC """ s1 = pd.Series(self.noaec_listed_seedling_emergence_dicot, name='seedling') s2 = pd.Series(self.noaec_listed_vegetative_vigor_dicot, name='vegetative') df = pd.concat([s1, s2], axis=1) self.out_min_lds_spray = pd.DataFrame.min(df, axis=1) return self.out_min_lds_spray
puruckertom/ubertool
ubertool/terrplant/terrplant_functions.py
Python
unlicense
20,304
module Dpd class Label < ApplicationRecord self.table_name_prefix = 'dpd_' end end
mirko-k/label2k17
app/models/dpd/label.rb
Ruby
unlicense
83
package oculus; import org.joml.Matrix4f; public interface ClientCallback { public void drawScene(final Matrix4f mat); public void shutdown(); public void keyPressed(final int key); }
Weirdbob95/OculusTest
src/main/java/oculus/ClientCallback.java
Java
unlicense
198
{% macro file_icon(mimetype) -%} {%- if mimetype == None -%} fa-file-o {%- elif mimetype == "application/msword" -%} fa-file-word-o {%- elif mimetype.startswith('image') -%} fa-file-image-o {%- elif mimetype == "application/pdf" -%} fa-file-pdf-o {%- elif mimetype == "text/xml" or mimetype == "application/xml" -%} fa-file-code-o {%- elif mimetype == "text/json" or mimetype == "application/json" -%} fa-file-code-o {%- elif mimetype == "text/x-yaml" -%} fa-file-text-o {%- else -%} file-o {%- endif -%} {%- endmacro -%} {% macro dataset_uri(dataset) -%} {%- if dataset.path == None -%} /datasets/{{dataset.name | urlencode}} {%- else -%} /datasets/{{dataset.path}}/ {%- endif -%} {%- endmacro %}
Kungbib/data.kb.se
flaskapp/templates/macros.html
HTML
unlicense
763
"use strict"; const angular = require("angular"); require("angular-sanitize"); const app = require("angular").module("app", ["ngSanitize"]); require("./factories"); require("./controllers"); require("./services");
jadaradix/jam
src/js/index.js
JavaScript
unlicense
216