repo_name
stringlengths 4
116
| path
stringlengths 3
942
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
|---|---|---|---|---|
hamgravy/volk-fft
|
lib/volk_fft_prefs.c
|
1442
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <volk_fft/volk_fft_prefs.h>
//#if defined(_WIN32)
//#include <Windows.h>
//#endif
void volk_fft_get_config_path(char *path)
{
if (!path) return;
const char *suffix = "/.volk_fft/volk_fft_config";
char *home = NULL;
if (home == NULL) home = getenv("HOME");
if (home == NULL) home = getenv("APPDATA");
if (home == NULL){
path[0] = 0;
return;
}
strcpy(path, home);
strcat(path, suffix);
}
size_t volk_fft_load_preferences(volk_fft_arch_pref_t **prefs_res)
{
FILE *config_file;
char path[512], line[512];
size_t n_arch_prefs = 0;
volk_fft_arch_pref_t *prefs = NULL;
//get the config path
volk_fft_get_config_path(path);
if (!path[0]) return n_arch_prefs; //no prefs found
config_file = fopen(path, "r");
if(!config_file) return n_arch_prefs; //no prefs found
//reset the file pointer and write the prefs into volk_fft_arch_prefs
while(fgets(line, sizeof(line), config_file) != NULL)
{
prefs = (volk_fft_arch_pref_t *) realloc(prefs, (n_arch_prefs+1) * sizeof(*prefs));
volk_fft_arch_pref_t *p = prefs + n_arch_prefs;
if(sscanf(line, "%s %s %s", p->name, p->impl_a, p->impl_u) == 3 && !strncmp(p->name, "volk_fft_", 5))
{
n_arch_prefs++;
}
}
fclose(config_file);
*prefs_res = prefs;
return n_arch_prefs;
}
|
gpl-3.0
|
cgwalters/texinfo-git-mirror
|
texi2html/test/singular_manual/res/singular/ainvar_005flib.html
|
9062
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by texi2html, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Singular 2-0-4 Manual: D.6.2 ainvar_lib</title>
<meta name="description" content="Singular 2-0-4 Manual: D.6.2 ainvar_lib">
<meta name="keywords" content="Singular 2-0-4 Manual: D.6.2 ainvar_lib">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:pre}
span.nolinebreak {white-space:pre}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" background="../singular_images/Mybg.png">
<a name="ainvar_005flib"></a>
<table border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
<td align="left">
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr valign="top" align="left">
<td valign="middle" align="left"> <a href="index.htm"><img
src="../singular_images/singular-icon-transparent.png" width="50"
border="0" alt="Top"></a>
</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="image_005fof_005fvariety.html#image_005fof_005fvariety" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.6.1.31 image_of_variety" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="invariantRing.html#invariantRing" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.6.2.1 invariantRing" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Invariant-theory.html#Invariant-theory" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.6 Invariant theory" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td>
</tr>
</table>
</td>
<td align="left">
<a name="ainvar_005flib-1"></a>
<h3 class="subsection">D.6.2 ainvar_lib</h3>
<a name="index-ainvar_002elib"></a>
<a name="index-ainvar_005flib"></a>
<dl compact="compact">
<dt><strong>Library:</strong></dt>
<dd><p>ainvar.lib
</p></dd>
<dt><strong>Purpose:</strong></dt>
<dd><p> Invariant Rings of the Additive Group
</p></dd>
<dt><strong>Authors:</strong></dt>
<dd><p>Gerhard Pfister (email: pfister@mathematik.uni-kl.de),
Gert-Martin Greuel (email: greuel@mathematik.uni-kl.de)
</p>
</dd>
</dl>
<p><strong>Procedures:</strong>
</p><blockquote><table class="menu" border="0" cellspacing="0">
<tr><td align="left" valign="top"><a href="invariantRing.html#invariantRing">D.6.2.1 invariantRing</a></td><td> </td><td align="left" valign="top"> compute ring of invariants of (K,+)-action given by m
</td></tr>
<tr><td align="left" valign="top"><a href="derivate.html#derivate">D.6.2.2 derivate</a></td><td> </td><td align="left" valign="top"> derivation of f with respect to the vector field m
</td></tr>
<tr><td align="left" valign="top"><a href="actionIsProper.html#actionIsProper">D.6.2.3 actionIsProper</a></td><td> </td><td align="left" valign="top"> tests whether action defined by m is proper
</td></tr>
<tr><td align="left" valign="top"><a href="reduction.html#reduction">D.6.2.4 reduction</a></td><td> </td><td align="left" valign="top"> SAGBI reduction of p in the subring generated by I
</td></tr>
<tr><td align="left" valign="top"><a href="completeReduction.html#completeReduction">D.6.2.5 completeReduction</a></td><td> </td><td align="left" valign="top"> complete SAGBI reduction
</td></tr>
<tr><td align="left" valign="top"><a href="localInvar.html#localInvar">D.6.2.6 localInvar</a></td><td> </td><td align="left" valign="top"> invariant polynomial under m computed from p,...
</td></tr>
<tr><td align="left" valign="top"><a href="furtherInvar.html#furtherInvar">D.6.2.7 furtherInvar</a></td><td> </td><td align="left" valign="top"> compute further invariants of m from the given ones
</td></tr>
<tr><td align="left" valign="top"><a href="sortier.html#sortier">D.6.2.8 sortier</a></td><td> </td><td align="left" valign="top"> sorts generators of id by increasing leading terms
</td></tr>
</table></blockquote>
</td>
</tr>
</table>
<hr>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left"> <a href="index.htm"><img
src="../singular_images/singular-icon-transparent.png" width="50"
border="0" alt="Top"></a>
</td>
<td valign="middle" align="left"><a href="image_005fof_005fvariety.html#image_005fof_005fvariety" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.6.1.31 image_of_variety" align="middle"></a></td>
<td valign="middle" align="left"><a href="invariantRing.html#invariantRing" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.6.2.1 invariantRing" align="middle"></a></td>
<td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td>
<td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td>
<td valign="middle" align="left"><a href="Invariant-theory.html#Invariant-theory" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.6 Invariant theory" align="middle"></a></td>
<td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td>
<td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td>
<td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td>
<td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td>
</tr></table>
<font size="-1">
User manual for <a href="http://www.singular.uni-kl.de/"><i>Singular</i></a> version 2-0-4, October 2002,
generated by <a href="http://www.gnu.org/software/texinfo/"><i>texi2html</i></a>.
</font>
</body>
</html>
|
gpl-3.0
|
mbedded-ninja/NinjaTerm
|
src/test/java/ninja/mbedded/ninjaterm/util/rxProcessing/timeStamp/TimeStampParserTests.java
|
17393
|
package ninja.mbedded.ninjaterm.util.rxProcessing.timeStamp;
import javafx.scene.paint.Color;
import ninja.mbedded.ninjaterm.JavaFXThreadingRule;
import ninja.mbedded.ninjaterm.util.rxProcessing.streamedData.StreamedData;
import ninja.mbedded.ninjaterm.util.rxProcessing.streamingFilter.StreamingFilter;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import java.time.Instant;
import java.time.ZoneId;
import static org.junit.Assert.assertEquals;
/**
* Unit tests for the {@link TimeStampParser} class.
*
* @author Geoffrey Hunter <gbmhunter@gmail.com> (www.mbedded.ninja)
* @since 2016-11-23
* @last-modified 2016-11-23
*/
public class TimeStampParserTests {
/**
* Including this variable in class allows JavaFX objects to be created in tests.
*/
@Rule
public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();
private TimeStampParser timeStampParser;
private StreamedData inputStreamedData;
private StreamedData outputStreamedData;
@Before
public void setUp() throws Exception {
timeStampParser = new TimeStampParser("EOL");
inputStreamedData = new StreamedData();
outputStreamedData = new StreamedData();
}
@Test
public void firstCharTest() throws Exception {
inputStreamedData.append("abc");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abc", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
}
@Test
public void oneNewLineTest() throws Exception {
inputStreamedData.append("abcEOLd");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOLd", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
}
@Test
public void temporalTest() throws Exception {
inputStreamedData.append("abcEOL");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOL", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
// Sleep enough that the next TimeStamp is guaranteed to be greater than
// the first (delay must be larger than the min. LocalDateTime resolution)
Thread.sleep(10);
//==============================================//
//====================== RUN 2 =================//
//==============================================//
inputStreamedData.append("d");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("abcEOLd", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
// Check time
Instant time0 = outputStreamedData.getTimeStampMarkers().get(0).localDateTime.atZone(ZoneId.systemDefault()).toInstant();
Instant time1 = outputStreamedData.getTimeStampMarkers().get(1).localDateTime.atZone(ZoneId.systemDefault()).toInstant();
assertEquals(true, time1.isAfter(time0));
}
@Test
public void partialLineTest() throws Exception {
inputStreamedData.append("123EO");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("EO", inputStreamedData.getText());
// Check output
assertEquals("123", outputStreamedData.getText());
assertEquals(1, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
inputStreamedData.append("L456");
timeStampParser.parse(inputStreamedData, outputStreamedData);
// Check input
assertEquals("", inputStreamedData.getText());
// Check output
assertEquals("123EOL456", outputStreamedData.getText());
assertEquals(2, outputStreamedData.getTimeStampMarkers().size());
assertEquals(0, outputStreamedData.getTimeStampMarkers().get(0).charPos);
assertEquals(6, outputStreamedData.getTimeStampMarkers().get(1).charPos);
}
// @Test
// public void multipleLinesTest() throws Exception {
//
// inputStreamedData.append("abcEOLabcEOLdefEOL");
// inputStreamedData.addNewLineMarkerAt(6);
// inputStreamedData.addNewLineMarkerAt(12);
// inputStreamedData.addNewLineMarkerAt(18);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input. Since "defEOL" counts as a valid line, but has no match,
// // it should be removed from the input
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getColourMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
// }
//
// @Test
// public void MatchedLinesBetweenNonMatchTest() throws Exception {
//
// inputStreamedData.append("abcEOLdefEOLabcEOL");
// inputStreamedData.addNewLineMarkerAt(6);
// inputStreamedData.addNewLineMarkerAt(12);
// inputStreamedData.addNewLineMarkerAt(18);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input. Since "defEOL" counts as a valid line, but has no match,
// // it should be removed from the input
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getColourMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
// }
//
// @Test
// public void streamTest() throws Exception {
//
// inputStreamedData.append("ab");
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", inputStreamedData.getText());
// assertEquals("ab", outputStreamedData.getText());
//
// inputStreamedData.append("cEOL");
// inputStreamedData.addNewLineMarkerAt(4);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", inputStreamedData.getText());
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void streamWithNonMatchLineInMiddleTest() throws Exception {
//
// //==============================================//
// //==================== PASS 1 ==================//
// //==============================================//
//
// inputStreamedData.append("ab");
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals("", inputStreamedData.getText());
//
// // Check output
// assertEquals("ab", outputStreamedData.getText());
//
// //==============================================//
// //==================== PASS 2 ==================//
// //==============================================//
//
// inputStreamedData.append("cEOLde");
// inputStreamedData.addNewLineMarkerAt(4);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "de");
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 3 ==================//
// //==============================================//
//
// inputStreamedData.append("fEOLa");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length() - 1);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "");
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOLa", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 4 ==================//
// //==============================================//
//
// inputStreamedData.append("bcEOL");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check input
// assertEquals(inputStreamedData.getText(), "");
// assertEquals(0, inputStreamedData.getNewLineMarkers().size());
//
// // Check output
// assertEquals("abcEOLabcEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// assertEquals(12, outputStreamedData.getNewLineMarkers().get(1).intValue());
//
// }
//
// @Test
// public void coloursAndNewLinesTest() throws Exception {
//
// inputStreamedData.append("abcEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addNewLineMarkerAt(6);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Check output
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void complexNodesTest() throws Exception {
//
// inputStreamedData.append("abcdefEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addColour(3, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(9);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcdefEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getColourMarkers().size());
//
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// assertEquals(3, outputStreamedData.getColourMarkers().get(1).position);
// assertEquals(Color.GREEN, outputStreamedData.getColourMarkers().get(1).color);
//
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(9, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void complexNodes2Test() throws Exception {
//
// //==============================================//
// //==================== PASS 1 ==================//
// //==============================================//
//
// inputStreamedData.append("abcEOL");
// inputStreamedData.addColour(2, Color.RED);
// inputStreamedData.addNewLineMarkerAt(6);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
//
// //==============================================//
// //==================== PASS 2 ==================//
// //==============================================//
//
// inputStreamedData.append("defEOL");
// inputStreamedData.addColour(0, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("abcEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(2, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
// assertEquals(1, outputStreamedData.getNewLineMarkers().size());
// assertEquals(6, outputStreamedData.getNewLineMarkers().get(0).intValue());
// }
//
// @Test
// public void bigTest() throws Exception {
//
// streamingFilter.setFilterPattern("d");
//
// inputStreamedData.append("re");
// inputStreamedData.addColour(0, Color.RED);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("", outputStreamedData.getText());
// assertEquals(0, outputStreamedData.getColourMarkers().size());
//
// inputStreamedData.append("dEOL");
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("redEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// // Nothing should of changed
// assertEquals("redEOL", outputStreamedData.getText());
// assertEquals(1, outputStreamedData.getColourMarkers().size());
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// inputStreamedData.append("greenEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// inputStreamedData.append("redEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 6, Color.RED);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// inputStreamedData.append("greenEOL");
// inputStreamedData.addColour(inputStreamedData.getText().length() - 8, Color.GREEN);
// inputStreamedData.addNewLineMarkerAt(inputStreamedData.getText().length());
//
// streamingFilter.parse(inputStreamedData, outputStreamedData);
//
// assertEquals("redEOLredEOL", outputStreamedData.getText());
// assertEquals(2, outputStreamedData.getColourMarkers().size());
//
// assertEquals(0, outputStreamedData.getColourMarkers().get(0).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(0).color);
//
// assertEquals(6, outputStreamedData.getColourMarkers().get(1).position);
// assertEquals(Color.RED, outputStreamedData.getColourMarkers().get(1).color);
// }
}
|
gpl-3.0
|
crazykeyboard/draw.io
|
war/js/diagramly/Init.js
|
6535
|
// urlParams is null when used for embedding
window.urlParams = window.urlParams || {};
// isLocalStorage controls access to local storage
window.isLocalStorage = window.isLocalStorage || false;
// Checks for SVG support
window.isSvgBrowser = window.isSvgBrowser || (navigator.userAgent.indexOf('MSIE') < 0 || document.documentMode >= 9);
// CUSTOM_PARAMETERS - URLs for save and export
window.EXPORT_URL = window.EXPORT_URL || 'https://exp.draw.io/ImageExport4/export';
window.SAVE_URL = window.SAVE_URL || 'save';
window.OPEN_URL = window.OPEN_URL || 'open';
window.PROXY_URL = window.PROXY_URL || 'proxy';
// Paths and files
window.SHAPES_PATH = window.SHAPES_PATH || 'shapes';
// Path for images inside the diagram
window.GRAPH_IMAGE_PATH = window.GRAPH_IMAGE_PATH || 'img';
window.ICONSEARCH_PATH = window.ICONSEARCH_PATH || (navigator.userAgent.indexOf('MSIE') >= 0 ||
urlParams['dev']) ? 'iconSearch' : 'https://www.draw.io/iconSearch';
window.TEMPLATE_PATH = window.TEMPLATE_PATH || '/templates';
// Directory for i18 files and basename for main i18n file
window.RESOURCES_PATH = window.RESOURCES_PATH || 'resources';
window.RESOURCE_BASE = window.RESOURCE_BASE || RESOURCES_PATH + '/dia';
// URL for logging
window.DRAWIO_LOG_URL = window.DRAWIO_LOG_URL || '';
// Sets the base path, the UI language via URL param and configures the
// supported languages to avoid 404s. The loading of all core language
// resources is disabled as all required resources are in grapheditor.
// properties. Note that in this example the loading of two resource
// files (the special bundle and the default bundle) is disabled to
// save a GET request. This requires that all resources be present in
// the special bundle.
window.mxLoadResources = window.mxLoadResources || false;
window.mxLanguage = window.mxLanguage || (function()
{
var lang = (urlParams['offline'] == '1') ? 'en' : urlParams['lang'];
// Known issue: No JSON object at this point in quirks in IE8
if (lang == null && typeof(JSON) != 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
if (value != null)
{
lang = JSON.parse(value).language || null;
}
}
catch (e)
{
// cookies are disabled, attempts to use local storage will cause
// a DOM error at a minimum on Chrome
isLocalStorage = false;
}
}
}
return lang;
})();
// Add new languages here. First entry is translated to [Automatic]
// in the menu defintion in Diagramly.js.
window.mxLanguageMap = window.mxLanguageMap ||
{
'i18n': '',
'id' : 'Bahasa Indonesia',
'ms' : 'Bahasa Melayu',
'bs' : 'Bosanski',
'ca' : 'Català',
'cs' : 'Čeština',
'da' : 'Dansk',
'de' : 'Deutsch',
'et' : 'Eesti',
'en' : 'English',
'es' : 'Español',
'eo' : 'Esperanto',
'fil' : 'Filipino',
'fr' : 'Français',
'it' : 'Italiano',
'hu' : 'Magyar',
'nl' : 'Nederlands',
'no' : 'Norsk',
'pl' : 'Polski',
'pt-br' : 'Português (Brasil)',
'pt' : 'Português (Portugal)',
'ro' : 'Română',
'fi' : 'Suomi',
'sv' : 'Svenska',
'vi' : 'Tiếng Việt',
'tr' : 'Türkçe',
'el' : 'Ελληνικά',
'ru' : 'Русский',
'sr' : 'Српски',
'uk' : 'Українська',
'he' : 'עברית',
'ar' : 'العربية',
'th' : 'ไทย',
'ko' : '한국어',
'ja' : '日本語',
'zh' : '中文(中国)',
'zh-tw' : '中文(台灣)'
};
if (typeof window.mxBasePath === 'undefined')
{
window.mxBasePath = 'mxgraph';
}
if (window.mxLanguages == null)
{
window.mxLanguages = [];
// Populates the list of supported special language bundles
for (var lang in mxLanguageMap)
{
// Empty means default (ie. browser language), "en" means English (default for unsupported languages)
// Since "en" uses no extension this must not be added to the array of supported language bundles.
if (lang != 'en')
{
window.mxLanguages.push(lang);
}
}
}
/**
* Returns the global UI setting before runngin static draw.io code
*/
window.uiTheme = window.uiTheme || (function()
{
var ui = urlParams['ui'];
// Known issue: No JSON object at this point in quirks in IE8
if (ui == null && typeof JSON !== 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
if (value != null)
{
ui = JSON.parse(value).ui || null;
}
}
catch (e)
{
// cookies are disabled, attempts to use local storage will cause
// a DOM error at a minimum on Chrome
isLocalStorage = false;
}
}
}
return ui;
})();
/**
* Global function for loading local files via servlet
*/
function setCurrentXml(data, filename)
{
if (window.parent != null && window.parent.openFile != null)
{
window.parent.openFile.setData(data, filename);
}
};
/**
* Overrides splash URL parameter via local storage
*/
(function()
{
// Known issue: No JSON object at this point in quirks in IE8
if (typeof JSON !== 'undefined')
{
// Cannot use mxSettings here
if (isLocalStorage)
{
try
{
var value = localStorage.getItem('.drawio-config');
var showSplash = true;
if (value != null)
{
showSplash = JSON.parse(value).showStartScreen;
}
// Undefined means true
if (showSplash == false)
{
urlParams['splash'] = '0';
}
}
catch (e)
{
// ignore
}
}
}
})();
// Customizes export URL
var ex = urlParams['export'];
if (ex != null)
{
if (ex.substring(0, 7) != 'http://' && ex.substring(0, 8) != 'https://')
{
ex = 'http://' + ex;
}
EXPORT_URL = ex;
}
// Enables offline mode
if (urlParams['offline'] == '1' || urlParams['demo'] == '1' || urlParams['stealth'] == '1' || urlParams['local'] == '1')
{
urlParams['analytics'] = '0';
urlParams['picker'] = '0';
urlParams['gapi'] = '0';
urlParams['db'] = '0';
urlParams['od'] = '0';
urlParams['gh'] = '0';
}
// Disables math in offline mode
if (urlParams['offline'] == '1' || urlParams['local'] == '1')
{
urlParams['math'] = '0';
}
// Lightbox enabled chromeless mode
if (urlParams['lightbox'] == '1')
{
urlParams['chrome'] = '0';
}
// Adds hard-coded logging domain for draw.io domains
var host = window.location.host;
var searchString = 'draw.io';
var position = host.length - searchString.length;
var lastIndex = host.lastIndexOf(searchString, position);
if (lastIndex !== -1 && lastIndex === position && host != 'test.draw.io')
{
// endsWith polyfill
window.DRAWIO_LOG_URL = 'https://log.draw.io';
}
|
gpl-3.0
|
NetRevolutions/SICOTYC
|
SICOTYC/UI/src/app/widgets/flot-chart-widget/flot-chart-widget.template.html
|
3725
|
<div class="col-lg-6 col-12">
<section widget class="widget widget-chart-stats-simple">
<header>
<div class="row">
<div class="col-3">
<h6>
Total Sales
</h6>
<p class="value5">
January, 2014
</p>
</div>
<div class="col-3">
<h5>
<small>Best</small>
</h5>
<p class="value6 fs-sm">
March, 2013 + 1
</p>
</div>
</div>
<div class="widget-controls">
<a href="#"><i class="glyphicon glyphicon-cog"></i></a>
<a href="#" data-widgster="close"><i class="glyphicon glyphicon-remove"></i></a>
</div>
</header>
<div class="widget-body">
<div class="chart-stats">
<p class="text-muted fs-mini mt-xs">
<i class="fa fa-map-marker fa-5x pull-left"></i>
<span class="fw-semi-bold text-gray-dark">Jess:</span> Seems like statically it's getting impossible to achieve any sort of
results in nearest future. The only thing we can hope for is pressing one of these two buttons:
</p>
<div class="btn-toolbar">
<button class="btn btn-xs btn-success">Accept</button>
<button class="btn btn-xs btn-default">Reject</button>
</div>
</div>
<div class="chart bg-body-light">
<div flot-chart [data]="generateRandomData([{
label: 'Visitors', color: configFn.darkenColor(config.settings.colors['gray-lighter'], .05)
},{
label: 'Charts', color: config.settings.colors['brand-danger']
}])" class="chart-inner"></div>
</div>
</div>
</section>
</div>
<div class="col-lg-6 col-12">
<section widget class="widget widget-chart-stats-simple">
<header>
<h6 class="mb-0">
<span class="fw-semi-bold">Budget</span> <span class="badge badge-pill badge-danger">2017</span>
</h6>
<span class="text-muted fs-mini">monthly report will be available in <a href="#">6 hours</a></span>
<div class="widget-controls">
<a href="#"><i class="glyphicon glyphicon-cog"></i></a>
<a href="#" data-widgster="close"><i class="glyphicon glyphicon-remove"></i></a>
</div>
</header>
<div class="widget-body">
<div class="chart-stats">
<div class="row">
<div class="col-md-5">
<div class="clearfix m-t-1">
<h6 class="pull-left text-muted mb-xs">
Income
</h6>
<p class="pull-right h6 mb-xs">
<span class="fw-semi-bold">$14,595</span>
</p>
</div>
<div class="clearfix">
<h6 class="pull-left m-0 text-muted">
Recent
</h6>
<p class="pull-right">
<span class="fw-semi-bold">$7,647</span>
</p>
</div>
</div>
<div class="col-md-3 text-right m-t-1">
<h6 class="text-muted mb-xs">Inqueries</h6>
<p class="fw-semi-bold">73 at 14am</p>
</div>
<div class="col-md-4 text-right m-t-1">
<h6 class="text-muted mb-xs">Last Updated</h6>
<p class="fw-semi-bold">23.06.2013</p>
</div>
</div>
</div>
<div class="chart bg-body-light">
<div flot-chart [data] = "generateRandomData([{
label: 'Controllers', color: '#777'
},{
label: 'Scopes', color: config.settings.colors['brand-warning']
}])" class="chart-inner"></div>
</div>
</div>
</section>
</div>
|
gpl-3.0
|
kaoz70/flexcms
|
flexcms/vendor/cartalyst/sentinel/src/migrations/2014_07_02_230147_migration_cartalyst_sentinel.php
|
3705
|
<?php
/**
* Part of the Sentinel package.
*
* NOTICE OF LICENSE
*
* Licensed under the 3-clause BSD License.
*
* This source file is subject to the 3-clause BSD License that is
* bundled with this package in the LICENSE file.
*
* @package Sentinel
* @version 2.0.18
* @author Cartalyst LLC
* @license BSD License (3-clause)
* @copyright (c) 2011-2019, Cartalyst LLC
* @link http://cartalyst.com
*/
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class MigrationCartalystSentinel extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('activations', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->boolean('completed')->default(0);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
Schema::create('persistences', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('code');
});
Schema::create('reminders', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned();
$table->string('code');
$table->boolean('completed')->default(0);
$table->timestamp('completed_at')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
});
Schema::create('roles', function (Blueprint $table) {
$table->increments('id');
$table->string('slug');
$table->string('name');
$table->text('permissions')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('slug');
});
Schema::create('role_users', function (Blueprint $table) {
$table->integer('user_id')->unsigned();
$table->integer('role_id')->unsigned();
$table->nullableTimestamps();
$table->engine = 'InnoDB';
$table->primary(['user_id', 'role_id']);
});
Schema::create('throttle', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->nullable();
$table->string('type');
$table->string('ip')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->index('user_id');
});
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('email');
$table->string('password');
$table->text('permissions')->nullable();
$table->timestamp('last_login')->nullable();
$table->string('first_name')->nullable();
$table->string('last_name')->nullable();
$table->timestamps();
$table->engine = 'InnoDB';
$table->unique('email');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('activations');
Schema::drop('persistences');
Schema::drop('reminders');
Schema::drop('roles');
Schema::drop('role_users');
Schema::drop('throttle');
Schema::drop('users');
}
}
|
gpl-3.0
|
saulario/pruebas
|
csoft/csoft/src/mod2/Worker2.cpp
|
499
|
/*
* File: Worker2.cpp
* Author: saulario
*
* Created on 15 de septiembre de 2016, 6:40
*/
#include "Worker2.h"
#include "Csoft.h"
using namespace csoft::mod2;
Worker2::Worker2(const csoft::Csoft * csoft) {
}
Worker2::Worker2(const Worker2& orig) {
}
Worker2::~Worker2() {
}
void Worker2::doIt(void) {
BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "---> Begin";
BOOST_LOG_SEV(lg, boost::log::trivial::info) << __PRETTY_FUNCTION__ << "<--- End";
}
|
gpl-3.0
|
ravilogaiya/yujvidya
|
android-client/YSchool/Person.cs
|
476
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YSchool
{
public class Person
{
public int id;
public string name ;
public int gender;//1
public string birthDate;//"1900-00-00T00:00:00"
public int mobileNumber;
public int altMobileNumber;
public string fatherName;
public string motherName;
public int batchType;//2
}
}
|
gpl-3.0
|
tonylegrone/platypi-cli
|
test/controllers/cli/updatetemplates.controller.test.js
|
2558
|
var chai = require('chai')
, sinon = require('sinon')
, sinonChai = require('sinon-chai')
, expect = chai.expect
, Promise = require('es6-promise').Promise
, UpdateTemplatesController = require('../../../platypi-cli/controllers/cli/updatetemplates.controller');
chai.use(sinonChai);
describe('TemplateUpdate controller', function () {
it('should return a new controller', function (done) {
try {
var controller = new UpdateTemplatesController({
viewStuff: 'fakeview'
});
expect(controller).to.be.an.object;
expect(controller.model).to.be.an.object;
expect(controller.view).to.be.an.object;
expect(controller.view.model).to.equal(controller.model);
done();
} catch (e) {
done(e);
}
});
describe('getResponseView method', function () {
var sandbox, controller, updateFunc;
beforeEach(function (done) {
sandbox = sinon.sandbox.create();
controller = new UpdateTemplatesController({
viewStuff: 'fakeview'
});
updateFunc = sandbox.stub(controller.__provider, 'update');
done();
});
afterEach(function (done) {
sandbox.restore();
done();
});
it('should call the clean method and return the view', function (done) {
updateFunc.returns(Promise.resolve(''));
controller.getResponseView().then(function (view) {
try {
expect(updateFunc).to.have.been.called;
expect(controller.model.successMessage).not.to.equal('');
expect(view).to.exist;
done();
} catch (e) {
done(e);
}
}, function (err) {
done(err);
});
});
it('should call the update method and throw an error', function (done) {
updateFunc.returns(Promise.reject('Err'));
controller.getResponseView().then(function (view) {
try {
expect(updateFunc).to.have.been.called;
expect(controller.model.errorMessage).not.to.equal('');
expect(view).to.exist;
done();
} catch (e) {
done(e);
}
}, function (err) {
done(err);
});
});
});
});
|
gpl-3.0
|
avedaee/DIRAC
|
TransformationSystem/Client/TransformationClient.py
|
22189
|
""" Class that contains client access to the transformation DB handler. """
__RCSID__ = "$Id$"
import types
from DIRAC import S_OK, S_ERROR, gLogger
from DIRAC.Core.Base.Client import Client
from DIRAC.Core.Utilities.List import breakListIntoChunks
from DIRAC.Resources.Catalog.FileCatalogueBase import FileCatalogueBase
from DIRAC.ConfigurationSystem.Client.Helpers.Operations import Operations
rpc = None
url = None
class TransformationClient( Client, FileCatalogueBase ):
""" Exposes the functionality available in the DIRAC/TransformationHandler
This inherits the DIRAC base Client for direct execution of server functionality.
The following methods are available (although not visible here).
Transformation (table) manipulation
deleteTransformation(transName)
getTransformationParameters(transName,paramNames)
getTransformationWithStatus(status)
setTransformationParameter(transName,paramName,paramValue)
deleteTransformationParameter(transName,paramName)
TransformationFiles table manipulation
addFilesToTransformation(transName,lfns)
addTaskForTransformation(transName,lfns=[],se='Unknown')
getTransformationStats(transName)
TransformationTasks table manipulation
setTaskStatus(transName, taskID, status)
setTaskStatusAndWmsID(transName, taskID, status, taskWmsID)
getTransformationTaskStats(transName)
deleteTasks(transName, taskMin, taskMax)
extendTransformation( transName, nTasks)
getTasksToSubmit(transName,numTasks,site='')
TransformationLogging table manipulation
getTransformationLogging(transName)
File/directory manipulation methods (the remainder of the interface can be found below)
getFileSummary(lfns)
exists(lfns)
Web monitoring tools
getDistinctAttributeValues(attribute, selectDict)
getTransformationStatusCounters()
getTransformationSummary()
getTransformationSummaryWeb(selectDict, sortList, startItem, maxItems)
"""
def __init__( self, **kwargs ):
Client.__init__( self, **kwargs )
opsH = Operations()
self.maxResetCounter = opsH.getValue( 'Productions/ProductionFilesMaxResetCounter', 10 )
self.setServer( 'Transformation/TransformationManager' )
def setServer( self, url ):
self.serverURL = url
def getCounters( self, table, attrList, condDict, older = None, newer = None, timeStamp = None,
rpc = '', url = '' ):
rpcClient = self._getRPC( rpc = rpc, url = url )
return rpcClient. getCounters( table, attrList, condDict, older, newer, timeStamp )
def addTransformation( self, transName, description, longDescription, transType, plugin, agentType, fileMask,
transformationGroup = 'General',
groupSize = 1,
inheritedFrom = 0,
body = '',
maxTasks = 0,
eventsPerTask = 0,
addFiles = True,
rpc = '', url = '', timeout = 1800 ):
""" add a new transformation
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addTransformation( transName, description, longDescription, transType, plugin,
agentType, fileMask, transformationGroup, groupSize, inheritedFrom,
body, maxTasks, eventsPerTask, addFiles )
def getTransformations( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationDate',
orderAttribute = None, limit = 100, extraParams = False, rpc = '', url = '', timeout = None ):
""" gets all the transformations in the system, incrementally. "limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformations = []
# getting transformations - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformations( condDict, older, newer, timeStamp, orderAttribute, limit,
extraParams, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformations = transformations + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformations )
def getTransformation( self, transName, extraParams = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getTransformation( transName, extraParams )
def getTransformationFiles( self, condDict = {}, older = None, newer = None, timeStamp = 'LastUpdate',
orderAttribute = None, limit = 10000, rpc = '', url = '', timeout = 1800 ):
""" gets all the transformation files for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationFiles = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationFiles( condDict, older, newer, timeStamp, orderAttribute, limit, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationFiles = transformationFiles + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationFiles )
def getTransformationTasks( self, condDict = {}, older = None, newer = None, timeStamp = 'CreationTime',
orderAttribute = None, limit = 10000, inputVector = False, rpc = '',
url = '', timeout = None ):
""" gets all the transformation tasks for a transformation, incrementally.
"limit" here is just used to determine the offset.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
transformationTasks = []
# getting transformationFiles - incrementally
offsetToApply = 0
while True:
res = rpcClient.getTransformationTasks( condDict, older, newer, timeStamp, orderAttribute, limit,
inputVector, offsetToApply )
if not res['OK']:
return res
else:
gLogger.verbose( "Result for limit %d, offset %d: %d" % ( limit, offsetToApply, len( res['Value'] ) ) )
if res['Value']:
transformationTasks = transformationTasks + res['Value']
offsetToApply += limit
if len( res['Value'] ) < limit:
break
return S_OK( transformationTasks )
def cleanTransformation( self, transID, rpc = '', url = '', timeout = None ):
""" Clean the transformation, and set the status parameter (doing it here, for easier extensibility)
"""
# Cleaning
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
res = rpcClient.cleanTransformation( transID )
if not res['OK']:
return res
# Setting the status
return self.setTransformationParameter( transID, 'Status', 'TransformationCleaned' )
def moveFilesToDerivedTransformation( self, transDict, resetUnused = True ):
""" move files input to a transformation, to the derived one
"""
prod = transDict['TransformationID']
parentProd = int( transDict.get( 'InheritedFrom', 0 ) )
movedFiles = {}
if not parentProd:
gLogger.warn( "[None] [%d] .moveFilesToDerivedTransformation: Transformation was not derived..." % prod )
return S_OK( ( parentProd, movedFiles ) )
# get the lfns in status Unused/MaxReset of the parent production
res = self.getTransformationFiles( condDict = {'TransformationID': parentProd, 'Status': [ 'Unused', 'MaxReset' ]} )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting Unused files from transformation %s:" % ( prod, parentProd ), res['Message'] )
return res
parentFiles = res['Value']
lfns = [lfnDict['LFN'] for lfnDict in parentFiles]
if not lfns:
gLogger.info( "[None] [%d] .moveFilesToDerivedTransformation: No files found to be moved from transformation %d" % ( prod, parentProd ) )
return S_OK( ( parentProd, movedFiles ) )
# get the lfns of the derived production that were Unused/MaxReset in the parent one
res = self.getTransformationFiles( condDict = { 'TransformationID': prod, 'LFN': lfns} )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error getting files from derived transformation" % prod, res['Message'] )
return res
derivedFiles = res['Value']
suffix = '-%d' % parentProd
derivedStatusDict = dict( [( derivedDict['LFN'], derivedDict['Status'] ) for derivedDict in derivedFiles] )
newStatusFiles = {}
parentStatusFiles = {}
force = False
for parentDict in parentFiles:
lfn = parentDict['LFN']
derivedStatus = derivedStatusDict.get( lfn )
if derivedStatus:
parentStatus = parentDict['Status']
if resetUnused and parentStatus == 'MaxReset':
status = 'Unused'
moveStatus = 'Unused from MaxReset'
force = True
else:
status = parentStatus
moveStatus = parentStatus
if derivedStatus.endswith( suffix ):
# This file is Unused or MaxReset while it was most likely Assigned at the time of derivation
parentStatusFiles.setdefault( 'Moved-%s' % str( prod ), [] ).append( lfn )
newStatusFiles.setdefault( ( status, parentStatus ), [] ).append( lfn )
movedFiles[moveStatus] = movedFiles.setdefault( moveStatus, 0 ) + 1
elif parentDict['Status'] == 'Unused':
# If the file was Unused already at derivation time, set it NotProcessed
parentStatusFiles.setdefault( 'NotProcessed', [] ).append( lfn )
# Set the status in the parent transformation first
for status, lfnList in parentStatusFiles.items():
for lfnChunk in breakListIntoChunks( lfnList, 5000 ):
res = self.setFileStatusForTransformation( parentProd, status, lfnChunk )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d "
% ( prod, status, len( lfnList ), parentProd ),
res['Message'] )
# Set the status in the new transformation
for ( status, oldStatus ), lfnList in newStatusFiles.items():
for lfnChunk in breakListIntoChunks( lfnList, 5000 ):
res = self.setFileStatusForTransformation( prod, status, lfnChunk, force = force )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files; resetting them %s in transformation %d"
% ( prod, status, len( lfnChunk ), oldStatus, parentProd ),
res['Message'] )
res = self.setFileStatusForTransformation( parentProd, oldStatus, lfnChunk )
if not res['OK']:
gLogger.error( "[None] [%d] .moveFilesToDerivedTransformation: Error setting status %s for %d files in transformation %d"
% ( prod, oldStatus, len( lfnChunk ), parentProd ),
res['Message'] )
return S_OK( ( parentProd, movedFiles ) )
def setFileStatusForTransformation( self, transName, newLFNsStatus = {}, lfns = [], force = False,
rpc = '', url = '', timeout = 120 ):
""" sets the file status for LFNs of a transformation
For backward compatibility purposes, the status and LFNs can be passed in 2 ways:
- newLFNsStatus is a dictionary with the form:
{'/this/is/an/lfn1.txt': 'StatusA', '/this/is/an/lfn2.txt': 'StatusB', ... }
and at this point lfns is not considered
- newLFNStatus is a string, that applies to all the LFNs in lfns
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
# create dictionary in case newLFNsStatus is a string
if type( newLFNsStatus ) == type( '' ):
newLFNsStatus = dict( [( lfn, newLFNsStatus ) for lfn in lfns ] )
# gets status as of today
tsFiles = self.getTransformationFiles( {'TransformationID':transName, 'LFN': newLFNsStatus.keys()} )
if not tsFiles['OK']:
return tsFiles
tsFiles = tsFiles['Value']
if tsFiles:
# for convenience, makes a small dictionary out of the tsFiles, with the lfn as key
tsFilesAsDict = {}
for tsFile in tsFiles:
tsFilesAsDict[tsFile['LFN']] = [tsFile['Status'], tsFile['ErrorCount'], tsFile['FileID']]
# applying the state machine to the proposed status
newStatuses = self._applyTransformationFilesStateMachine( tsFilesAsDict, newLFNsStatus, force )
if newStatuses: # if there's something to update
# must do it for the file IDs...
newStatusForFileIDs = dict( [( tsFilesAsDict[lfn][2], newStatuses[lfn] ) for lfn in newStatuses.keys()] )
res = rpcClient.setFileStatusForTransformation( transName, newStatusForFileIDs )
if not res['OK']:
return res
return S_OK( newStatuses )
def _applyTransformationFilesStateMachine( self, tsFilesAsDict, dictOfProposedLFNsStatus, force ):
""" For easier extension, here we apply the state machine of the production files.
VOs might want to replace the standard here with something they prefer.
tsFiles is a dictionary with the lfn as key and as value a list of [Status, ErrorCount, FileID]
dictOfNewLFNsStatus is a dictionary with the proposed status
force is a boolean
It returns a dictionary with the status updates
"""
newStatuses = {}
for lfn in dictOfProposedLFNsStatus.keys():
if lfn not in tsFilesAsDict.keys():
continue
else:
newStatus = dictOfProposedLFNsStatus[lfn]
# Apply optional corrections
if tsFilesAsDict[lfn][0].lower() == 'processed' and dictOfProposedLFNsStatus[lfn].lower() != 'processed':
if not force:
newStatus = 'Processed'
elif tsFilesAsDict[lfn][0].lower() == 'maxreset':
if not force:
newStatus = 'MaxReset'
elif dictOfProposedLFNsStatus[lfn].lower() == 'unused':
errorCount = tsFilesAsDict[lfn][1]
# every 10 retries (by default)
if errorCount and ( ( errorCount % self.maxResetCounter ) == 0 ):
if not force:
newStatus = 'MaxReset'
if tsFilesAsDict[lfn][0].lower() != newStatus:
newStatuses[lfn] = newStatus
return newStatuses
def setTransformationParameter( self, transID, paramName, paramValue, force = False,
rpc = '', url = '', timeout = 120 ):
""" Sets a transformation parameter. There's a special case when coming to setting the status of a transformation.
"""
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
if paramName.lower() == 'status':
# get transformation Type
transformation = self.getTransformation( transID )
if not transformation['OK']:
return transformation
transformationType = transformation['Value']['Type']
# get status as of today
originalStatus = self.getTransformationParameters( transID, 'Status' )
if not originalStatus['OK']:
return originalStatus
originalStatus = originalStatus['Value']
transIDAsDict = {transID: [originalStatus, transformationType]}
dictOfProposedstatus = {transID: paramValue}
# applying the state machine to the proposed status
value = self._applyTransformationStatusStateMachine( transIDAsDict, dictOfProposedstatus, force )
else:
value = paramValue
return rpcClient.setTransformationParameter( transID, paramName, value )
def _applyTransformationStatusStateMachine( self, transIDAsDict, dictOfProposedstatus, force ):
""" For easier extension, here we apply the state machine of the transformation status.
VOs might want to replace the standard here with something they prefer.
transIDAsDict is a dictionary with the transID as key and as value a list with [Status, Type]
dictOfProposedstatus is a dictionary with the proposed status
force is a boolean
It returns the new status (the standard is just doing nothing: everything is possible)
"""
return dictOfProposedstatus.values()[0]
#####################################################################
#
# These are the file catalog interface methods
#
def isOK( self ):
return self.valid
def getName( self, DN = '' ):
""" Get the file catalog type name
"""
return self.name
def addDirectory( self, path, force = False, rpc = '', url = '', timeout = None ):
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addDirectory( path, force )
def getReplicas( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfns = res['Value'].keys()
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getReplicas( lfns )
def addFile( self, lfn, force = False, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addFile( lfndicts, force )
def addReplica( self, lfn, force = False, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.addReplica( lfndicts, force )
def removeFile( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfns = res['Value'].keys()
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
successful = {}
failed = {}
listOfLists = breakListIntoChunks( lfns, 100 )
for fList in listOfLists:
res = rpcClient.removeFile( fList )
if not res['OK']:
return res
successful.update( res['Value']['Successful'] )
failed.update( res['Value']['Failed'] )
resDict = {'Successful': successful, 'Failed':failed}
return S_OK( resDict )
def removeReplica( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndicts = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
successful = {}
failed = {}
# as lfndicts is a dict, the breakListIntoChunks will fail. Fake it!
listOfDicts = []
localdicts = {}
for lfn, info in lfndicts.items():
localdicts.update( { lfn : info } )
if len( localdicts.keys() ) % 100 == 0:
listOfDicts.append( localdicts )
localdicts = {}
for fDict in listOfDicts:
res = rpcClient.removeReplica( fDict )
if not res['OK']:
return res
successful.update( res['Value']['Successful'] )
failed.update( res['Value']['Failed'] )
resDict = {'Successful': successful, 'Failed':failed}
return S_OK( resDict )
def getReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.getReplicaStatus( lfndict )
def setReplicaStatus( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.setReplicaStatus( lfndict )
def setReplicaHost( self, lfn, rpc = '', url = '', timeout = None ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
lfndict = res['Value']
rpcClient = self._getRPC( rpc = rpc, url = url, timeout = timeout )
return rpcClient.setReplicaHost( lfndict )
def removeDirectory( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def createDirectory( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def createLink( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def removeLink( self, lfn, rpc = '', url = '', timeout = None ):
return self.__returnOK( lfn )
def __returnOK( self, lfn ):
res = self.__checkArgumentFormat( lfn )
if not res['OK']:
return res
successful = {}
for lfn in res['Value'].keys():
successful[lfn] = True
resDict = {'Successful':successful, 'Failed':{}}
return S_OK( resDict )
def __checkArgumentFormat( self, path ):
if type( path ) in types.StringTypes:
urls = {path:False}
elif type( path ) == types.ListType:
urls = {}
for url in path:
urls[url] = False
elif type( path ) == types.DictType:
urls = path
else:
return S_ERROR( "TransformationClient.__checkArgumentFormat: Supplied path is not of the correct format." )
return S_OK( urls )
|
gpl-3.0
|
quadwitharm/DebugConsole
|
mainwindow.h
|
2007
|
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "serial.h"
#include "inputprocessor.h"
#include "commandsender.h"
#include "plothelper.h"
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void verticalSlider();
void sendmotor();
public slots:
void refreshDevices();
private slots:
void on_openButton_pressed();
void on_closeButton_pressed();
void on_clearButton_pressed();
void on_Send_pressed();
void rollPIDPressed();
void pitchPIDPressed();
void yawPIDPressed();
void rollRatePIDPressed();
void pitchRatePIDPressed();
void yawRatePIDPressed();
void rollSliderChanged();
void pitchSliderChanged();
void yawSliderChanged();
void rollRateSliderChanged();
void pitchRateSliderChanged();
void yawRateSliderChanged();
void sendRollPIDParam();
void sendPitchPIDParam();
void sendYawPIDParam();
void sendRollRatePIDParam();
void sendPitchRatePIDParam();
void sendYawRatePIDParam();
void on_pushButton_pressed();
void on_pushButton_4_pressed();
void on_pushButton_3_pressed();
void on_pushButton_2_pressed();
void on_lineEdit_2_returnPressed();
void on_lineEdit_5_returnPressed();
void on_lineEdit_4_returnPressed();
void on_lineEdit_3_returnPressed();
signals:
void rollPIDReleased();
void pitchPIDReleased();
void yawPIDReleased();
void rollRatePIDReleased();
void pitchRatePIDReleased();
void yawRatePIDReleased();
private:
void sendSetPoints();
Ui::MainWindow *ui;
Serial serial;
InputProcessor *ip;
CommandSender *cs;
QTimer *timer;
PlotHelper controllerLine1, controllerLine2, controllerLine3;
PlotHelper grawLine1, grawLine2, grawLine3;
PlotHelper arawLine1, arawLine2, arawLine3;
PlotHelper filterLine1, filterLine2, filterLine3;
};
#endif // MAINWINDOW_H
|
gpl-3.0
|
electricpandafishstudios/Spoon
|
game/modules/tome-1.4.1/data/zones/ruined-dungeon/traps.lua
|
901
|
-- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2016 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
load("/data/general/traps/complex.lua")
load("/data/general/traps/alarm.lua")
load("/data/general/traps/natural_forest.lua")
|
gpl-3.0
|
CoderDuan/mantaflow
|
source/timing.h
|
1387
|
/******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* GNU General Public License (GPL)
* http://www.gnu.org/licenses
*
* Plugin timing
*
******************************************************************************/
#ifndef _TIMING_H
#define _TIMING_H
#include "manta.h"
#include <map>
namespace Manta {
class TimingData {
private:
TimingData();
public:
static TimingData& instance() { static TimingData a; return a; }
void print();
void saveMean(const std::string& filename);
void start(FluidSolver* parent, const std::string& name);
void stop(FluidSolver* parent, const std::string& name);
protected:
void step();
struct TimingSet {
TimingSet() : num(0),updated(false) { cur.clear(); total.clear(); }
MuTime cur, total;
int num;
bool updated;
std::string solver;
};
bool updated;
int num;
MuTime mPluginTimer;
std::string mLastPlugin;
std::map<std::string, std::vector<TimingSet> > mData;
};
// Python interface
PYTHON() class Timings : public PbClass {
public:
PYTHON() Timings() : PbClass(0) {}
PYTHON() void display() { TimingData::instance().print(); }
PYTHON() void saveMean(std::string file) { TimingData::instance().saveMean(file); }
};
}
#endif
|
gpl-3.0
|
darciga/cf
|
blog/models.py
|
1127
|
from django.db import models
from django.contrib.auth.models import User
import MySQLdb
# Create your models here.
class Comentario(models.Model):
"""Comentario"""
contenido = models.TextField(help_text='Escribe un comentario')
fecha_coment = models.DateField(auto_now=True)
def __unicode__(self):
return self.contenido
class Estado(models.Model):
"""Estado"""
nom_estado = models.CharField(max_length=50)
def __unicode__(self):
return nom_estado
class Categoria(models.Model):
"""Categoria"""
nombre = models.CharField(max_length=50)
descripcion = models.TextField(help_text='Escribe una descripcion de la categoria')
class Entrada(models.Model):
"""Entrada"""
autor = models.ForeignKey(User)
comentario = models.ForeignKey(Comentario)
estado = models.ForeignKey(Estado)
titulo = models.CharField(max_length=100)
contenido = models.TextField(help_text='Redacta el contenido')
fecha_pub = models.DateField(auto_now=True)
def __unicode__(self):
return self.titulo
class Agregador(models.Model):
"""agreador"""
entrada = models.ForeignKey(Entrada)
categoria = models.ManyToManyField(Categoria)
|
gpl-3.0
|
joshbohde/xbmc-notify-mqtt
|
README.md
|
923
|
XBMC Notify MQTT
=============================
An XBMC addon to display notifications received over mqtt.
Install
-------
Install the zip file through the XBMC add on interface.
Configure
---------
Insert the broker host, port, and the root path on in the configuration.
Topics
------
The root topic is configurable, but defaults to "/house/xbmc".
Status will be published to the root + "/status".
The service will display notifications published to root + "/all/messages".
Play status is published under the topic root + "player/status". It will be json string of with at least a state attribute, with optional type, current, and total time attributes.
Usage
-----
Publish a JSON message to the notification topic with title, text, duration (in seconds), and optional image attributes.
An example `{"title":"Here's a message", "text":"Here's the body", "image":"http://example.com/image.png, "duration":10}`
|
gpl-3.0
|
ethereum/solidity
|
libsolutil/CommonIO.cpp
|
4494
|
/*
This file is part of solidity.
solidity 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.
solidity 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 solidity. If not, see <http://www.gnu.org/licenses/>.
*/
// SPDX-License-Identifier: GPL-3.0
/** @file CommonIO.cpp
* @author Gav Wood <i@gavwood.com>
* @date 2014
*/
#include <libsolutil/CommonIO.h>
#include <libsolutil/Assertions.h>
#include <fstream>
#if defined(_WIN32)
#include <windows.h>
#else
#include <unistd.h>
#include <termios.h>
#endif
using namespace std;
using namespace solidity::util;
namespace
{
template <typename T>
inline T readFile(boost::filesystem::path const& _file)
{
assertThrow(boost::filesystem::exists(_file), FileNotFound, _file.string());
// ifstream does not always fail when the path leads to a directory. Instead it might succeed
// with tellg() returning a nonsensical value so that std::length_error gets raised in resize().
assertThrow(boost::filesystem::is_regular_file(_file), NotAFile, _file.string());
T ret;
size_t const c_elementSize = sizeof(typename T::value_type);
std::ifstream is(_file.string(), std::ifstream::binary);
// Technically, this can still fail even though we checked above because FS content can change at any time.
assertThrow(is, FileNotFound, _file.string());
// get length of file:
is.seekg(0, is.end);
streamoff length = is.tellg();
if (length == 0)
return ret; // do not read empty file (MSVC does not like it)
is.seekg(0, is.beg);
ret.resize((static_cast<size_t>(length) + c_elementSize - 1) / c_elementSize);
is.read(const_cast<char*>(reinterpret_cast<char const*>(ret.data())), static_cast<streamsize>(length));
return ret;
}
}
string solidity::util::readFileAsString(boost::filesystem::path const& _file)
{
return readFile<string>(_file);
}
string solidity::util::readUntilEnd(istream& _stdin)
{
ostringstream ss;
ss << _stdin.rdbuf();
return ss.str();
}
string solidity::util::readBytes(istream& _input, size_t _length)
{
string output;
output.resize(_length);
_input.read(output.data(), static_cast<streamsize>(_length));
// If read() reads fewer bytes it sets failbit in addition to eofbit.
if (_input.fail())
output.resize(static_cast<size_t>(_input.gcount()));
return output;
}
#if defined(_WIN32)
class DisableConsoleBuffering
{
public:
DisableConsoleBuffering()
{
m_stdin = GetStdHandle(STD_INPUT_HANDLE);
GetConsoleMode(m_stdin, &m_oldMode);
SetConsoleMode(m_stdin, m_oldMode & (~(ENABLE_ECHO_INPUT | ENABLE_LINE_INPUT)));
}
~DisableConsoleBuffering()
{
SetConsoleMode(m_stdin, m_oldMode);
}
private:
HANDLE m_stdin;
DWORD m_oldMode;
};
#else
class DisableConsoleBuffering
{
public:
DisableConsoleBuffering()
{
tcgetattr(0, &m_termios);
m_termios.c_lflag &= ~tcflag_t(ICANON);
m_termios.c_lflag &= ~tcflag_t(ECHO);
m_termios.c_cc[VMIN] = 1;
m_termios.c_cc[VTIME] = 0;
tcsetattr(0, TCSANOW, &m_termios);
}
~DisableConsoleBuffering()
{
m_termios.c_lflag |= ICANON;
m_termios.c_lflag |= ECHO;
tcsetattr(0, TCSADRAIN, &m_termios);
}
private:
struct termios m_termios;
};
#endif
int solidity::util::readStandardInputChar()
{
DisableConsoleBuffering disableConsoleBuffering;
return cin.get();
}
string solidity::util::absolutePath(string const& _path, string const& _reference)
{
boost::filesystem::path p(_path);
// Anything that does not start with `.` is an absolute path.
if (p.begin() == p.end() || (*p.begin() != "." && *p.begin() != ".."))
return _path;
boost::filesystem::path result(_reference);
// If filename is "/", then remove_filename() throws.
// See: https://github.com/boostorg/filesystem/issues/176
if (result.filename() != boost::filesystem::path("/"))
result.remove_filename();
for (boost::filesystem::path::iterator it = p.begin(); it != p.end(); ++it)
if (*it == "..")
result = result.parent_path();
else if (*it != ".")
result /= *it;
return result.generic_string();
}
string solidity::util::sanitizePath(string const& _path) {
return boost::filesystem::path(_path).generic_string();
}
|
gpl-3.0
|
xVir/tasks
|
src/main/java/com/todoroo/astrid/reminders/NotificationFragment.java
|
2884
|
/**
* Copyright (c) 2012 Todoroo Inc
*
* See the file "LICENSE" for the full license governing this code.
*/
package com.todoroo.astrid.reminders;
import android.app.Dialog;
import android.content.Intent;
import android.view.View;
import android.widget.TextView;
import com.todoroo.astrid.activity.AstridActivity;
import com.todoroo.astrid.activity.TaskListFragment;
import org.tasks.Broadcaster;
import org.tasks.R;
import org.tasks.reminders.SnoozeActivity;
import javax.inject.Inject;
/**
* This activity is launched when a user opens up a notification from the
* tray. It launches the appropriate activity based on the passed in parameters.
*
* @author timsu
*
*/
public class NotificationFragment extends TaskListFragment {
public static final String TOKEN_ID = "id"; //$NON-NLS-1$
@Inject Broadcaster broadcaster;
@Override
protected void initializeData() {
displayNotificationPopup();
super.initializeData();
}
private void displayNotificationPopup() {
final String title = extras.getString(Notifications.EXTRAS_TITLE);
final long taskId = extras.getLong(TOKEN_ID);
final AstridActivity activity = (AstridActivity) getActivity();
new Dialog(activity, R.style.ReminderDialog) {{
setContentView(R.layout.astrid_reminder_view_portrait);
findViewById(R.id.speech_bubble_container).setVisibility(View.GONE);
// set up listeners
findViewById(R.id.dismiss).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dismiss();
}
});
findViewById(R.id.reminder_snooze).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
dismiss();
activity.startActivity(new Intent(activity, SnoozeActivity.class) {{
putExtra(SnoozeActivity.TASK_ID, taskId);
}});
}
});
findViewById(R.id.reminder_complete).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
broadcaster.completeTask(taskId);
dismiss();
}
});
findViewById(R.id.reminder_edit).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
activity.onTaskListItemClicked(taskId);
}
});
((TextView) findViewById(R.id.reminder_title)).setText(activity.getString(R.string.rmd_NoA_dlg_title) + " " + title);
setOwnerActivity(activity);
}}.show();
}
}
|
gpl-3.0
|
timusus/Shuttle
|
app/src/main/java/com/simplecity/amp_library/model/ArtworkModel.java
|
1505
|
package com.simplecity.amp_library.model;
import android.content.Context;
import com.simplecity.amp_library.R;
import java.io.File;
public class ArtworkModel {
private static final String TAG = "ArtworkModel";
@ArtworkProvider.Type
public int type;
public File file;
public ArtworkModel(@ArtworkProvider.Type int type, File file) {
this.type = type;
this.file = file;
}
public static String getTypeString(Context context, @ArtworkProvider.Type int type) {
switch (type) {
case ArtworkProvider.Type.MEDIA_STORE:
return context.getString(R.string.artwork_type_media_store);
case ArtworkProvider.Type.TAG:
return context.getString(R.string.artwork_type_tag);
case ArtworkProvider.Type.FOLDER:
return "Folder";
case ArtworkProvider.Type.REMOTE:
return context.getString(R.string.artwork_type_internet);
}
return null;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ArtworkModel that = (ArtworkModel) o;
if (type != that.type) return false;
return file != null ? file.equals(that.file) : that.file == null;
}
@Override
public int hashCode() {
int result = type;
result = 31 * result + (file != null ? file.hashCode() : 0);
return result;
}
}
|
gpl-3.0
|
beyondckw/SynchronizeOfPPT
|
Android_v5/src/com/newppt/android/ui/ScaleImage.java
|
1835
|
package com.newppt.android.ui;
import com.newppt.android.data.AnimUtils2;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;
public class ScaleImage extends ImageView {
final private int FLIP_DISTANCE = 30;
public ScaleImage(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public ScaleImage(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public ScaleImage(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
private int count = 0;
private long firClick;
private long secClick;
private boolean scaleTip = true;
private float x;
private float y;
@Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if (MotionEvent.ACTION_DOWN == event.getAction()) {
count++;
if (count == 1) {
firClick = System.currentTimeMillis();
x = event.getX();
y = event.getY();
} else if (count == 2) {
secClick = System.currentTimeMillis();
float mx = event.getX();
float my = event.getY();
if (secClick - firClick < 700
&& Math.abs(mx - x) < FLIP_DISTANCE
&& Math.abs(my - y) < FLIP_DISTANCE) {
// ˫���¼�
if (scaleTip) {
x = event.getX();
y = event.getY();
AnimUtils2 animUtils2 = new AnimUtils2();
animUtils2.imageZoomOut(this, 200, x, y);
scaleTip = false;
}
else {
AnimUtils2 animUtils2 = new AnimUtils2();
animUtils2.imageZoomIn(this, 200, x, y);
scaleTip = true;
}
}
count = 0;
firClick = 0;
secClick = 0;
}
}
return true;
// return super.onTouchEvent(event);
}
}
|
gpl-3.0
|
stevenvergenz/pyVenture
|
README.md
|
454
|
pyVenture - A python text-based adventure game engine
-----------------------------------------------------
This is a generalized framework that allows construction and playing of text-based-adventure-style worlds. Stores world information in JSON files.
This code is licensed under the General Public License Version 3 (http://www.gnu.org/licenses/gpl-3.0.html)
The following dependencies are required:
* Python 2.6+
* Qt4
* PyQt4
* GraphViz
* pydot
|
gpl-3.0
|
williamfdevine/PrettyLinux
|
drivers/video/fbdev/omap2/omapfb/displays/panel-dsi-cm.c
|
28860
|
/*
* Generic DSI Command Mode panel driver
*
* Copyright (C) 2013 Texas Instruments
* Author: Tomi Valkeinen <tomi.valkeinen@ti.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
/* #define DEBUG */
#include <linux/backlight.h>
#include <linux/delay.h>
#include <linux/fb.h>
#include <linux/gpio.h>
#include <linux/interrupt.h>
#include <linux/jiffies.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/workqueue.h>
#include <linux/of_device.h>
#include <linux/of_gpio.h>
#include <video/omapfb_dss.h>
#include <video/mipi_display.h>
/* DSI Virtual channel. Hardcoded for now. */
#define TCH 0
#define DCS_READ_NUM_ERRORS 0x05
#define DCS_BRIGHTNESS 0x51
#define DCS_CTRL_DISPLAY 0x53
#define DCS_GET_ID1 0xda
#define DCS_GET_ID2 0xdb
#define DCS_GET_ID3 0xdc
struct panel_drv_data
{
struct omap_dss_device dssdev;
struct omap_dss_device *in;
struct omap_video_timings timings;
struct platform_device *pdev;
struct mutex lock;
struct backlight_device *bldev;
unsigned long hw_guard_end; /* next value of jiffies when we can
* issue the next sleep in/out command
*/
unsigned long hw_guard_wait; /* max guard time in jiffies */
/* panel HW configuration from DT or platform data */
int reset_gpio;
int ext_te_gpio;
bool use_dsi_backlight;
struct omap_dsi_pin_config pin_config;
/* runtime variables */
bool enabled;
bool te_enabled;
atomic_t do_update;
int channel;
struct delayed_work te_timeout_work;
bool intro_printed;
bool ulps_enabled;
unsigned ulps_timeout;
struct delayed_work ulps_work;
};
#define to_panel_data(p) container_of(p, struct panel_drv_data, dssdev)
static irqreturn_t dsicm_te_isr(int irq, void *data);
static void dsicm_te_timeout_work_callback(struct work_struct *work);
static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable);
static int dsicm_panel_reset(struct panel_drv_data *ddata);
static void dsicm_ulps_work(struct work_struct *work);
static void hw_guard_start(struct panel_drv_data *ddata, int guard_msec)
{
ddata->hw_guard_wait = msecs_to_jiffies(guard_msec);
ddata->hw_guard_end = jiffies + ddata->hw_guard_wait;
}
static void hw_guard_wait(struct panel_drv_data *ddata)
{
unsigned long wait = ddata->hw_guard_end - jiffies;
if ((long)wait > 0 && wait <= ddata->hw_guard_wait)
{
set_current_state(TASK_UNINTERRUPTIBLE);
schedule_timeout(wait);
}
}
static int dsicm_dcs_read_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 *data)
{
struct omap_dss_device *in = ddata->in;
int r;
u8 buf[1];
r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd, buf, 1);
if (r < 0)
{
return r;
}
*data = buf[0];
return 0;
}
static int dsicm_dcs_write_0(struct panel_drv_data *ddata, u8 dcs_cmd)
{
struct omap_dss_device *in = ddata->in;
return in->ops.dsi->dcs_write(in, ddata->channel, &dcs_cmd, 1);
}
static int dsicm_dcs_write_1(struct panel_drv_data *ddata, u8 dcs_cmd, u8 param)
{
struct omap_dss_device *in = ddata->in;
u8 buf[2] = { dcs_cmd, param };
return in->ops.dsi->dcs_write(in, ddata->channel, buf, 2);
}
static int dsicm_sleep_in(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
u8 cmd;
int r;
hw_guard_wait(ddata);
cmd = MIPI_DCS_ENTER_SLEEP_MODE;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, &cmd, 1);
if (r)
{
return r;
}
hw_guard_start(ddata, 120);
usleep_range(5000, 10000);
return 0;
}
static int dsicm_sleep_out(struct panel_drv_data *ddata)
{
int r;
hw_guard_wait(ddata);
r = dsicm_dcs_write_0(ddata, MIPI_DCS_EXIT_SLEEP_MODE);
if (r)
{
return r;
}
hw_guard_start(ddata, 120);
usleep_range(5000, 10000);
return 0;
}
static int dsicm_get_id(struct panel_drv_data *ddata, u8 *id1, u8 *id2, u8 *id3)
{
int r;
r = dsicm_dcs_read_1(ddata, DCS_GET_ID1, id1);
if (r)
{
return r;
}
r = dsicm_dcs_read_1(ddata, DCS_GET_ID2, id2);
if (r)
{
return r;
}
r = dsicm_dcs_read_1(ddata, DCS_GET_ID3, id3);
if (r)
{
return r;
}
return 0;
}
static int dsicm_set_update_window(struct panel_drv_data *ddata,
u16 x, u16 y, u16 w, u16 h)
{
struct omap_dss_device *in = ddata->in;
int r;
u16 x1 = x;
u16 x2 = x + w - 1;
u16 y1 = y;
u16 y2 = y + h - 1;
u8 buf[5];
buf[0] = MIPI_DCS_SET_COLUMN_ADDRESS;
buf[1] = (x1 >> 8) & 0xff;
buf[2] = (x1 >> 0) & 0xff;
buf[3] = (x2 >> 8) & 0xff;
buf[4] = (x2 >> 0) & 0xff;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf));
if (r)
{
return r;
}
buf[0] = MIPI_DCS_SET_PAGE_ADDRESS;
buf[1] = (y1 >> 8) & 0xff;
buf[2] = (y1 >> 0) & 0xff;
buf[3] = (y2 >> 8) & 0xff;
buf[4] = (y2 >> 0) & 0xff;
r = in->ops.dsi->dcs_write_nosync(in, ddata->channel, buf, sizeof(buf));
if (r)
{
return r;
}
in->ops.dsi->bta_sync(in, ddata->channel);
return r;
}
static void dsicm_queue_ulps_work(struct panel_drv_data *ddata)
{
if (ddata->ulps_timeout > 0)
schedule_delayed_work(&ddata->ulps_work,
msecs_to_jiffies(ddata->ulps_timeout));
}
static void dsicm_cancel_ulps_work(struct panel_drv_data *ddata)
{
cancel_delayed_work(&ddata->ulps_work);
}
static int dsicm_enter_ulps(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
if (ddata->ulps_enabled)
{
return 0;
}
dsicm_cancel_ulps_work(ddata);
r = _dsicm_enable_te(ddata, false);
if (r)
{
goto err;
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
disable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
in->ops.dsi->disable(in, false, true);
ddata->ulps_enabled = true;
return 0;
err:
dev_err(&ddata->pdev->dev, "enter ULPS failed");
dsicm_panel_reset(ddata);
ddata->ulps_enabled = false;
dsicm_queue_ulps_work(ddata);
return r;
}
static int dsicm_exit_ulps(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
if (!ddata->ulps_enabled)
{
return 0;
}
r = in->ops.dsi->enable(in);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to enable DSI\n");
goto err1;
}
in->ops.dsi->enable_hs(in, ddata->channel, true);
r = _dsicm_enable_te(ddata, true);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to re-enable TE");
goto err2;
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
enable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
dsicm_queue_ulps_work(ddata);
ddata->ulps_enabled = false;
return 0;
err2:
dev_err(&ddata->pdev->dev, "failed to exit ULPS");
r = dsicm_panel_reset(ddata);
if (!r)
{
if (gpio_is_valid(ddata->ext_te_gpio))
{
enable_irq(gpio_to_irq(ddata->ext_te_gpio));
}
ddata->ulps_enabled = false;
}
err1:
dsicm_queue_ulps_work(ddata);
return r;
}
static int dsicm_wake_up(struct panel_drv_data *ddata)
{
if (ddata->ulps_enabled)
{
return dsicm_exit_ulps(ddata);
}
dsicm_cancel_ulps_work(ddata);
dsicm_queue_ulps_work(ddata);
return 0;
}
static int dsicm_bl_update_status(struct backlight_device *dev)
{
struct panel_drv_data *ddata = dev_get_drvdata(&dev->dev);
struct omap_dss_device *in = ddata->in;
int r;
int level;
if (dev->props.fb_blank == FB_BLANK_UNBLANK &&
dev->props.power == FB_BLANK_UNBLANK)
{
level = dev->props.brightness;
}
else
{
level = 0;
}
dev_dbg(&ddata->pdev->dev, "update brightness to %d\n", level);
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
{
r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, level);
}
in->ops.dsi->bus_unlock(in);
}
else
{
r = 0;
}
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_bl_get_intensity(struct backlight_device *dev)
{
if (dev->props.fb_blank == FB_BLANK_UNBLANK &&
dev->props.power == FB_BLANK_UNBLANK)
{
return dev->props.brightness;
}
return 0;
}
static const struct backlight_ops dsicm_bl_ops =
{
.get_brightness = dsicm_bl_get_intensity,
.update_status = dsicm_bl_update_status,
};
static void dsicm_get_resolution(struct omap_dss_device *dssdev,
u16 *xres, u16 *yres)
{
*xres = dssdev->panel.timings.x_res;
*yres = dssdev->panel.timings.y_res;
}
static ssize_t dsicm_num_errors_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
u8 errors = 0;
int r;
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
r = dsicm_dcs_read_1(ddata, DCS_READ_NUM_ERRORS,
&errors);
in->ops.dsi->bus_unlock(in);
}
else
{
r = -ENODEV;
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return snprintf(buf, PAGE_SIZE, "%d\n", errors);
}
static ssize_t dsicm_hw_revision_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
u8 id1, id2, id3;
int r;
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (!r)
{
r = dsicm_get_id(ddata, &id1, &id2, &id3);
}
in->ops.dsi->bus_unlock(in);
}
else
{
r = -ENODEV;
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return snprintf(buf, PAGE_SIZE, "%02x.%02x.%02x\n", id1, id2, id3);
}
static ssize_t dsicm_store_ulps(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
unsigned long t;
int r;
r = kstrtoul(buf, 0, &t);
if (r)
{
return r;
}
mutex_lock(&ddata->lock);
if (ddata->enabled)
{
in->ops.dsi->bus_lock(in);
if (t)
{
r = dsicm_enter_ulps(ddata);
}
else
{
r = dsicm_wake_up(ddata);
}
in->ops.dsi->bus_unlock(in);
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return count;
}
static ssize_t dsicm_show_ulps(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
unsigned t;
mutex_lock(&ddata->lock);
t = ddata->ulps_enabled;
mutex_unlock(&ddata->lock);
return snprintf(buf, PAGE_SIZE, "%u\n", t);
}
static ssize_t dsicm_store_ulps_timeout(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t count)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in = ddata->in;
unsigned long t;
int r;
r = kstrtoul(buf, 0, &t);
if (r)
{
return r;
}
mutex_lock(&ddata->lock);
ddata->ulps_timeout = t;
if (ddata->enabled)
{
/* dsicm_wake_up will restart the timer */
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
in->ops.dsi->bus_unlock(in);
}
mutex_unlock(&ddata->lock);
if (r)
{
return r;
}
return count;
}
static ssize_t dsicm_show_ulps_timeout(struct device *dev,
struct device_attribute *attr,
char *buf)
{
struct platform_device *pdev = to_platform_device(dev);
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
unsigned t;
mutex_lock(&ddata->lock);
t = ddata->ulps_timeout;
mutex_unlock(&ddata->lock);
return snprintf(buf, PAGE_SIZE, "%u\n", t);
}
static DEVICE_ATTR(num_dsi_errors, S_IRUGO, dsicm_num_errors_show, NULL);
static DEVICE_ATTR(hw_revision, S_IRUGO, dsicm_hw_revision_show, NULL);
static DEVICE_ATTR(ulps, S_IRUGO | S_IWUSR,
dsicm_show_ulps, dsicm_store_ulps);
static DEVICE_ATTR(ulps_timeout, S_IRUGO | S_IWUSR,
dsicm_show_ulps_timeout, dsicm_store_ulps_timeout);
static struct attribute *dsicm_attrs[] =
{
&dev_attr_num_dsi_errors.attr,
&dev_attr_hw_revision.attr,
&dev_attr_ulps.attr,
&dev_attr_ulps_timeout.attr,
NULL,
};
static struct attribute_group dsicm_attr_group =
{
.attrs = dsicm_attrs,
};
static void dsicm_hw_reset(struct panel_drv_data *ddata)
{
if (!gpio_is_valid(ddata->reset_gpio))
{
return;
}
gpio_set_value(ddata->reset_gpio, 1);
udelay(10);
/* reset the panel */
gpio_set_value(ddata->reset_gpio, 0);
/* assert reset */
udelay(10);
gpio_set_value(ddata->reset_gpio, 1);
/* wait after releasing reset */
usleep_range(5000, 10000);
}
static int dsicm_power_on(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
u8 id1, id2, id3;
int r;
struct omap_dss_dsi_config dsi_config =
{
.mode = OMAP_DSS_DSI_CMD_MODE,
.pixel_format = OMAP_DSS_DSI_FMT_RGB888,
.timings = &ddata->timings,
.hs_clk_min = 150000000,
.hs_clk_max = 300000000,
.lp_clk_min = 7000000,
.lp_clk_max = 10000000,
};
if (ddata->pin_config.num_pins > 0)
{
r = in->ops.dsi->configure_pins(in, &ddata->pin_config);
if (r)
{
dev_err(&ddata->pdev->dev,
"failed to configure DSI pins\n");
goto err0;
}
}
r = in->ops.dsi->set_config(in, &dsi_config);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to configure DSI\n");
goto err0;
}
r = in->ops.dsi->enable(in);
if (r)
{
dev_err(&ddata->pdev->dev, "failed to enable DSI\n");
goto err0;
}
dsicm_hw_reset(ddata);
in->ops.dsi->enable_hs(in, ddata->channel, false);
r = dsicm_sleep_out(ddata);
if (r)
{
goto err;
}
r = dsicm_get_id(ddata, &id1, &id2, &id3);
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, DCS_BRIGHTNESS, 0xff);
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, DCS_CTRL_DISPLAY,
(1 << 2) | (1 << 5)); /* BL | BCTRL */
if (r)
{
goto err;
}
r = dsicm_dcs_write_1(ddata, MIPI_DCS_SET_PIXEL_FORMAT,
MIPI_DCS_PIXEL_FMT_24BIT);
if (r)
{
goto err;
}
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_DISPLAY_ON);
if (r)
{
goto err;
}
r = _dsicm_enable_te(ddata, ddata->te_enabled);
if (r)
{
goto err;
}
r = in->ops.dsi->enable_video_output(in, ddata->channel);
if (r)
{
goto err;
}
ddata->enabled = 1;
if (!ddata->intro_printed)
{
dev_info(&ddata->pdev->dev, "panel revision %02x.%02x.%02x\n",
id1, id2, id3);
ddata->intro_printed = true;
}
in->ops.dsi->enable_hs(in, ddata->channel, true);
return 0;
err:
dev_err(&ddata->pdev->dev, "error while enabling panel, issuing HW reset\n");
dsicm_hw_reset(ddata);
in->ops.dsi->disable(in, true, false);
err0:
return r;
}
static void dsicm_power_off(struct panel_drv_data *ddata)
{
struct omap_dss_device *in = ddata->in;
int r;
in->ops.dsi->disable_video_output(in, ddata->channel);
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_DISPLAY_OFF);
if (!r)
{
r = dsicm_sleep_in(ddata);
}
if (r)
{
dev_err(&ddata->pdev->dev,
"error disabling panel, issuing HW reset\n");
dsicm_hw_reset(ddata);
}
in->ops.dsi->disable(in, true, false);
ddata->enabled = 0;
}
static int dsicm_panel_reset(struct panel_drv_data *ddata)
{
dev_err(&ddata->pdev->dev, "performing LCD reset\n");
dsicm_power_off(ddata);
dsicm_hw_reset(ddata);
return dsicm_power_on(ddata);
}
static int dsicm_connect(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
struct device *dev = &ddata->pdev->dev;
int r;
if (omapdss_device_is_connected(dssdev))
{
return 0;
}
r = in->ops.dsi->connect(in, dssdev);
if (r)
{
dev_err(dev, "Failed to connect to video source\n");
return r;
}
r = in->ops.dsi->request_vc(ddata->in, &ddata->channel);
if (r)
{
dev_err(dev, "failed to get virtual channel\n");
goto err_req_vc;
}
r = in->ops.dsi->set_vc_id(ddata->in, ddata->channel, TCH);
if (r)
{
dev_err(dev, "failed to set VC_ID\n");
goto err_vc_id;
}
return 0;
err_vc_id:
in->ops.dsi->release_vc(ddata->in, ddata->channel);
err_req_vc:
in->ops.dsi->disconnect(in, dssdev);
return r;
}
static void dsicm_disconnect(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
if (!omapdss_device_is_connected(dssdev))
{
return;
}
in->ops.dsi->release_vc(in, ddata->channel);
in->ops.dsi->disconnect(in, dssdev);
}
static int dsicm_enable(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "enable\n");
mutex_lock(&ddata->lock);
if (!omapdss_device_is_connected(dssdev))
{
r = -ENODEV;
goto err;
}
if (omapdss_device_is_enabled(dssdev))
{
r = 0;
goto err;
}
in->ops.dsi->bus_lock(in);
r = dsicm_power_on(ddata);
in->ops.dsi->bus_unlock(in);
if (r)
{
goto err;
}
dssdev->state = OMAP_DSS_DISPLAY_ACTIVE;
mutex_unlock(&ddata->lock);
return 0;
err:
dev_dbg(&ddata->pdev->dev, "enable failed\n");
mutex_unlock(&ddata->lock);
return r;
}
static void dsicm_disable(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "disable\n");
mutex_lock(&ddata->lock);
dsicm_cancel_ulps_work(ddata);
in->ops.dsi->bus_lock(in);
if (omapdss_device_is_enabled(dssdev))
{
r = dsicm_wake_up(ddata);
if (!r)
{
dsicm_power_off(ddata);
}
}
in->ops.dsi->bus_unlock(in);
dssdev->state = OMAP_DSS_DISPLAY_DISABLED;
mutex_unlock(&ddata->lock);
}
static void dsicm_framedone_cb(int err, void *data)
{
struct panel_drv_data *ddata = data;
struct omap_dss_device *in = ddata->in;
dev_dbg(&ddata->pdev->dev, "framedone, err %d\n", err);
in->ops.dsi->bus_unlock(ddata->in);
}
static irqreturn_t dsicm_te_isr(int irq, void *data)
{
struct panel_drv_data *ddata = data;
struct omap_dss_device *in = ddata->in;
int old;
int r;
old = atomic_cmpxchg(&ddata->do_update, 1, 0);
if (old)
{
cancel_delayed_work(&ddata->te_timeout_work);
r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb,
ddata);
if (r)
{
goto err;
}
}
return IRQ_HANDLED;
err:
dev_err(&ddata->pdev->dev, "start update failed\n");
in->ops.dsi->bus_unlock(in);
return IRQ_HANDLED;
}
static void dsicm_te_timeout_work_callback(struct work_struct *work)
{
struct panel_drv_data *ddata = container_of(work, struct panel_drv_data,
te_timeout_work.work);
struct omap_dss_device *in = ddata->in;
dev_err(&ddata->pdev->dev, "TE not received for 250ms!\n");
atomic_set(&ddata->do_update, 0);
in->ops.dsi->bus_unlock(in);
}
static int dsicm_update(struct omap_dss_device *dssdev,
u16 x, u16 y, u16 w, u16 h)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
dev_dbg(&ddata->pdev->dev, "update %d, %d, %d x %d\n", x, y, w, h);
mutex_lock(&ddata->lock);
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (r)
{
goto err;
}
if (!ddata->enabled)
{
r = 0;
goto err;
}
/* XXX no need to send this every frame, but dsi break if not done */
r = dsicm_set_update_window(ddata, 0, 0,
dssdev->panel.timings.x_res,
dssdev->panel.timings.y_res);
if (r)
{
goto err;
}
if (ddata->te_enabled && gpio_is_valid(ddata->ext_te_gpio))
{
schedule_delayed_work(&ddata->te_timeout_work,
msecs_to_jiffies(250));
atomic_set(&ddata->do_update, 1);
}
else
{
r = in->ops.dsi->update(in, ddata->channel, dsicm_framedone_cb,
ddata);
if (r)
{
goto err;
}
}
/* note: no bus_unlock here. unlock is in framedone_cb */
mutex_unlock(&ddata->lock);
return 0;
err:
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_sync(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
dev_dbg(&ddata->pdev->dev, "sync\n");
mutex_lock(&ddata->lock);
in->ops.dsi->bus_lock(in);
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
dev_dbg(&ddata->pdev->dev, "sync done\n");
return 0;
}
static int _dsicm_enable_te(struct panel_drv_data *ddata, bool enable)
{
struct omap_dss_device *in = ddata->in;
int r;
if (enable)
{
r = dsicm_dcs_write_1(ddata, MIPI_DCS_SET_TEAR_ON, 0);
}
else
{
r = dsicm_dcs_write_0(ddata, MIPI_DCS_SET_TEAR_OFF);
}
if (!gpio_is_valid(ddata->ext_te_gpio))
{
in->ops.dsi->enable_te(in, enable);
}
/* possible panel bug */
msleep(100);
return r;
}
static int dsicm_enable_te(struct omap_dss_device *dssdev, bool enable)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
mutex_lock(&ddata->lock);
if (ddata->te_enabled == enable)
{
goto end;
}
in->ops.dsi->bus_lock(in);
if (ddata->enabled)
{
r = dsicm_wake_up(ddata);
if (r)
{
goto err;
}
r = _dsicm_enable_te(ddata, enable);
if (r)
{
goto err;
}
}
ddata->te_enabled = enable;
in->ops.dsi->bus_unlock(in);
end:
mutex_unlock(&ddata->lock);
return 0;
err:
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_get_te(struct omap_dss_device *dssdev)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
int r;
mutex_lock(&ddata->lock);
r = ddata->te_enabled;
mutex_unlock(&ddata->lock);
return r;
}
static int dsicm_memory_read(struct omap_dss_device *dssdev,
void *buf, size_t size,
u16 x, u16 y, u16 w, u16 h)
{
struct panel_drv_data *ddata = to_panel_data(dssdev);
struct omap_dss_device *in = ddata->in;
int r;
int first = 1;
int plen;
unsigned buf_used = 0;
if (size < w * h * 3)
{
return -ENOMEM;
}
mutex_lock(&ddata->lock);
if (!ddata->enabled)
{
r = -ENODEV;
goto err1;
}
size = min(w * h * 3,
dssdev->panel.timings.x_res *
dssdev->panel.timings.y_res * 3);
in->ops.dsi->bus_lock(in);
r = dsicm_wake_up(ddata);
if (r)
{
goto err2;
}
/* plen 1 or 2 goes into short packet. until checksum error is fixed,
* use short packets. plen 32 works, but bigger packets seem to cause
* an error. */
if (size % 2)
{
plen = 1;
}
else
{
plen = 2;
}
dsicm_set_update_window(ddata, x, y, w, h);
r = in->ops.dsi->set_max_rx_packet_size(in, ddata->channel, plen);
if (r)
{
goto err2;
}
while (buf_used < size)
{
u8 dcs_cmd = first ? 0x2e : 0x3e;
first = 0;
r = in->ops.dsi->dcs_read(in, ddata->channel, dcs_cmd,
buf + buf_used, size - buf_used);
if (r < 0)
{
dev_err(dssdev->dev, "read error\n");
goto err3;
}
buf_used += r;
if (r < plen)
{
dev_err(&ddata->pdev->dev, "short read\n");
break;
}
if (signal_pending(current))
{
dev_err(&ddata->pdev->dev, "signal pending, "
"aborting memory read\n");
r = -ERESTARTSYS;
goto err3;
}
}
r = buf_used;
err3:
in->ops.dsi->set_max_rx_packet_size(in, ddata->channel, 1);
err2:
in->ops.dsi->bus_unlock(in);
err1:
mutex_unlock(&ddata->lock);
return r;
}
static void dsicm_ulps_work(struct work_struct *work)
{
struct panel_drv_data *ddata = container_of(work, struct panel_drv_data,
ulps_work.work);
struct omap_dss_device *dssdev = &ddata->dssdev;
struct omap_dss_device *in = ddata->in;
mutex_lock(&ddata->lock);
if (dssdev->state != OMAP_DSS_DISPLAY_ACTIVE || !ddata->enabled)
{
mutex_unlock(&ddata->lock);
return;
}
in->ops.dsi->bus_lock(in);
dsicm_enter_ulps(ddata);
in->ops.dsi->bus_unlock(in);
mutex_unlock(&ddata->lock);
}
static struct omap_dss_driver dsicm_ops =
{
.connect = dsicm_connect,
.disconnect = dsicm_disconnect,
.enable = dsicm_enable,
.disable = dsicm_disable,
.update = dsicm_update,
.sync = dsicm_sync,
.get_resolution = dsicm_get_resolution,
.get_recommended_bpp = omapdss_default_get_recommended_bpp,
.enable_te = dsicm_enable_te,
.get_te = dsicm_get_te,
.memory_read = dsicm_memory_read,
};
static int dsicm_probe_of(struct platform_device *pdev)
{
struct device_node *node = pdev->dev.of_node;
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *in;
int gpio;
gpio = of_get_named_gpio(node, "reset-gpios", 0);
if (!gpio_is_valid(gpio))
{
dev_err(&pdev->dev, "failed to parse reset gpio\n");
return gpio;
}
ddata->reset_gpio = gpio;
gpio = of_get_named_gpio(node, "te-gpios", 0);
if (gpio_is_valid(gpio) || gpio == -ENOENT)
{
ddata->ext_te_gpio = gpio;
}
else
{
dev_err(&pdev->dev, "failed to parse TE gpio\n");
return gpio;
}
in = omapdss_of_find_source_for_first_ep(node);
if (IS_ERR(in))
{
dev_err(&pdev->dev, "failed to find video source\n");
return PTR_ERR(in);
}
ddata->in = in;
/* TODO: ulps, backlight */
return 0;
}
static int dsicm_probe(struct platform_device *pdev)
{
struct backlight_properties props;
struct panel_drv_data *ddata;
struct backlight_device *bldev = NULL;
struct device *dev = &pdev->dev;
struct omap_dss_device *dssdev;
int r;
dev_dbg(dev, "probe\n");
if (!pdev->dev.of_node)
{
return -ENODEV;
}
ddata = devm_kzalloc(dev, sizeof(*ddata), GFP_KERNEL);
if (!ddata)
{
return -ENOMEM;
}
platform_set_drvdata(pdev, ddata);
ddata->pdev = pdev;
r = dsicm_probe_of(pdev);
if (r)
{
return r;
}
ddata->timings.x_res = 864;
ddata->timings.y_res = 480;
ddata->timings.pixelclock = 864 * 480 * 60;
dssdev = &ddata->dssdev;
dssdev->dev = dev;
dssdev->driver = &dsicm_ops;
dssdev->panel.timings = ddata->timings;
dssdev->type = OMAP_DISPLAY_TYPE_DSI;
dssdev->owner = THIS_MODULE;
dssdev->panel.dsi_pix_fmt = OMAP_DSS_DSI_FMT_RGB888;
dssdev->caps = OMAP_DSS_DISPLAY_CAP_MANUAL_UPDATE |
OMAP_DSS_DISPLAY_CAP_TEAR_ELIM;
r = omapdss_register_display(dssdev);
if (r)
{
dev_err(dev, "Failed to register panel\n");
goto err_reg;
}
mutex_init(&ddata->lock);
atomic_set(&ddata->do_update, 0);
if (gpio_is_valid(ddata->reset_gpio))
{
r = devm_gpio_request_one(dev, ddata->reset_gpio,
GPIOF_OUT_INIT_LOW, "taal rst");
if (r)
{
dev_err(dev, "failed to request reset gpio\n");
return r;
}
}
if (gpio_is_valid(ddata->ext_te_gpio))
{
r = devm_gpio_request_one(dev, ddata->ext_te_gpio,
GPIOF_IN, "taal irq");
if (r)
{
dev_err(dev, "GPIO request failed\n");
return r;
}
r = devm_request_irq(dev, gpio_to_irq(ddata->ext_te_gpio),
dsicm_te_isr,
IRQF_TRIGGER_RISING,
"taal vsync", ddata);
if (r)
{
dev_err(dev, "IRQ request failed\n");
return r;
}
INIT_DEFERRABLE_WORK(&ddata->te_timeout_work,
dsicm_te_timeout_work_callback);
dev_dbg(dev, "Using GPIO TE\n");
}
INIT_DELAYED_WORK(&ddata->ulps_work, dsicm_ulps_work);
dsicm_hw_reset(ddata);
if (ddata->use_dsi_backlight)
{
memset(&props, 0, sizeof(struct backlight_properties));
props.max_brightness = 255;
props.type = BACKLIGHT_RAW;
bldev = backlight_device_register(dev_name(dev),
dev, ddata, &dsicm_bl_ops, &props);
if (IS_ERR(bldev))
{
r = PTR_ERR(bldev);
goto err_reg;
}
ddata->bldev = bldev;
bldev->props.fb_blank = FB_BLANK_UNBLANK;
bldev->props.power = FB_BLANK_UNBLANK;
bldev->props.brightness = 255;
dsicm_bl_update_status(bldev);
}
r = sysfs_create_group(&dev->kobj, &dsicm_attr_group);
if (r)
{
dev_err(dev, "failed to create sysfs files\n");
goto err_sysfs_create;
}
return 0;
err_sysfs_create:
if (bldev != NULL)
{
backlight_device_unregister(bldev);
}
err_reg:
return r;
}
static int __exit dsicm_remove(struct platform_device *pdev)
{
struct panel_drv_data *ddata = platform_get_drvdata(pdev);
struct omap_dss_device *dssdev = &ddata->dssdev;
struct backlight_device *bldev;
dev_dbg(&pdev->dev, "remove\n");
omapdss_unregister_display(dssdev);
dsicm_disable(dssdev);
dsicm_disconnect(dssdev);
sysfs_remove_group(&pdev->dev.kobj, &dsicm_attr_group);
bldev = ddata->bldev;
if (bldev != NULL)
{
bldev->props.power = FB_BLANK_POWERDOWN;
dsicm_bl_update_status(bldev);
backlight_device_unregister(bldev);
}
omap_dss_put_device(ddata->in);
dsicm_cancel_ulps_work(ddata);
/* reset, to be sure that the panel is in a valid state */
dsicm_hw_reset(ddata);
return 0;
}
static const struct of_device_id dsicm_of_match[] =
{
{ .compatible = "omapdss,panel-dsi-cm", },
{},
};
MODULE_DEVICE_TABLE(of, dsicm_of_match);
static struct platform_driver dsicm_driver =
{
.probe = dsicm_probe,
.remove = __exit_p(dsicm_remove),
.driver = {
.name = "panel-dsi-cm",
.of_match_table = dsicm_of_match,
.suppress_bind_attrs = true,
},
};
module_platform_driver(dsicm_driver);
MODULE_AUTHOR("Tomi Valkeinen <tomi.valkeinen@ti.com>");
MODULE_DESCRIPTION("Generic DSI Command Mode Panel Driver");
MODULE_LICENSE("GPL");
|
gpl-3.0
|
publicinsightnetwork/audience-insight-repository
|
lib/AIR2_Record.php
|
13214
|
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**************************************************************************
*
* Copyright 2010 American Public Media Group
*
* This file is part of AIR2.
*
* AIR2 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.
*
* AIR2 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 AIR2. If not, see <http://www.gnu.org/licenses/>.
*
*************************************************************************/
require_once "AIR2Logger.php";
require_once 'AirValidHtml.php'; //custom validator extension
require_once 'AirValidNoHtml.php'; //custom validator extension
/**
* AIR2_Record base class
*
* @author pkarman
* @package default
*/
abstract class AIR2_Record extends Doctrine_Record {
/* fields which the discriminator will treat as case-insensitive */
protected static $DISC_CASE_INSENSITIVE_FLDS = array('src_username',
'src_first_name', 'src_last_name', 'src_middle_initial', 'src_pre_name',
'src_post_name', 'sa_name', 'sa_first_name', 'sa_last_name', 'sa_post_name',
'smadd_line_1', 'smadd_line_2', 'smadd_city', 'sf_src_value');
/**
* tests validity of the record using the current data.
*
* (This is an override of base Doctrine functionality, to fix a bug with validation.)
*
* @param boolean $deep (optional) run the validation process on the relations
* @param boolean $hooks (optional) invoke save hooks before start
* @return boolean whether or not this record is valid
*/
public function isValid($deep = false, $hooks = true) {
if ( ! $this->_table->getAttribute(Doctrine_Core::ATTR_VALIDATE)) {
return true;
}
if ($this->_state == self::STATE_LOCKED || $this->_state == self::STATE_TLOCKED) {
return true;
}
if ($hooks) {
$this->invokeSaveHooks('pre', 'save');
$this->invokeSaveHooks('pre', $this->exists() ? 'update' : 'insert');
}
// Clear the stack from any previous errors.
$this->getErrorStack()->clear();
// Run validation process
$event = new Doctrine_Event($this, Doctrine_Event::RECORD_VALIDATE);
$this->preValidate($event);
$this->getTable()->getRecordListener()->preValidate($event);
if ( ! $event->skipOperation) {
$validator = new Doctrine_Validator();
$validator->validateRecord($this);
$this->validate();
if ($this->_state == self::STATE_TDIRTY || $this->_state == self::STATE_TCLEAN) {
$this->validateOnInsert();
}
else {
$this->validateOnUpdate();
}
}
$this->getTable()->getRecordListener()->postValidate($event);
$this->postValidate($event);
$valid = $this->getErrorStack()->count() == 0 ? true : false;
if ($valid && $deep) {
$stateBeforeLock = $this->_state;
$this->_state = $this->exists() ? self::STATE_LOCKED : self::STATE_TLOCKED;
foreach ($this->_references as $reference) {
if ($reference instanceof Doctrine_Record) {
if ( ! $valid = $reference->isValid($deep)) {
break;
}
}
elseif ($reference instanceof Doctrine_Collection) {
foreach ($reference as $record) {
if ( ! $valid = $record->isValid($deep, $hooks)) {
break;
}
}
// Bugfix.
if (!$valid) {
break;
}
}
}
$this->_state = $stateBeforeLock;
}
return $valid;
}
/**
* Save the record to the database
*
* @param object $conn (optional)
*/
public function save( Doctrine_Connection $conn=null ) {
// unless explicitly passed, we find the _master connection
// for the current env.
if ( $conn === null ) {
$conn = AIR2_DBManager::get_master_connection();
}
parent::save($conn);
}
/**
* Insert or update record in the database.
*
* @param object $conn (optional)
*/
public function replace( Doctrine_Connection $conn=null ) {
// unless explicitly passed, we find the _master connection
// for the current env.
if ( $conn === null ) {
$conn = AIR2_DBManager::get_master_connection();
}
parent::replace($conn);
}
/**
* All AIR2_Record tables should be UTF8
*/
public function setTableDefinition() {
// utf8 charset
$this->option('collate', 'utf8_unicode_ci');
$this->option('charset', 'utf8');
}
/**
* Detect whether to add CreUser and UpdUser relations
*/
public function setUp() {
parent::setUp();
$cols = $this->getTable()->getColumnNames();
foreach ($cols as $name) {
if (preg_match('/_cre_user$/', $name)) {
$this->hasOne('UserStamp as CreUser',
array('local' => $name, 'foreign' => 'user_id')
);
}
elseif (preg_match('/_upd_user$/', $name)) {
$this->hasOne('UserStamp as UpdUser',
array('local' => $name, 'foreign' => 'user_id')
);
}
}
}
/**
* Custom AIR2 validation before update/save
*
* @param Doctrine_Event $event
*/
public function preValidate($event) {
air2_model_prevalidate($this);
}
/**
* Determines if a record produced from the tank can be safely moved into
* AIR2, or if it conflicts with existing AIR2 data.
*
* @param array $data
* @param TankSource $tsrc
* @param int $op
*/
public function discriminate($data, &$tsrc, $op=null) {
// update the record
$exists = $this->exists();
foreach ($data as $key => $val) {
// trim any incoming string values
if ($val && is_string($val)) {
$val = trim($val);
}
// always update new records
if (!$exists) {
$this->$key = $val;
}
// replace NULLs
elseif (is_null($this->$key)) {
$this->$key = $val;
}
// check for conflict
elseif ($this->disc_is_conflict($key, $this->$key, $val)) {
// CONFLICT! check the $op value
if ($op == AIR2_DISCRIM_REPLACE) {
$this->$key = $val;
}
else {
$this->disc_add_conflict($tsrc, $key, $this->$key, $val);
}
}
}
}
/**
* Compares 2 values, and determines if there is a conflict. Returning
* false will NOT update the field, so do it yourself if that's what you
* want.
*
* @param string $field
* @param mixed $oldval
* @param mixed $newval
* @return boolean
*/
protected function disc_is_conflict($field, $oldval, $newval) {
// check for case-insensitive fields
if (in_array($field, self::$DISC_CASE_INSENSITIVE_FLDS)) {
$oldval = strtolower($oldval);
$newval = strtolower($newval);
}
$result = ($oldval != $newval); // default php comparison
return $result;
}
/**
* Add a conflict to the tank_source
*
* @param TankSource $tsrc
* @param string $field
* @param mixed $oldval
* @param mixed $newval
*/
protected function disc_add_conflict($tsrc, $field, $oldval, $newval) {
$cls = $this->getTable()->getClassnameToReturn();
$uuidcol = air2_get_model_uuid_col($cls);
$uuid = $this->$uuidcol;
$tsrc->add_conflict($cls, $field, 'Conflicting tank value', $uuid);
}
/**
* Determine if a User has permission to read this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_read(User $u) {
throw new Exception('user_may_read not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission to write to this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_write(User $u) {
throw new Exception('user_may_write not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission to manage this record.
*
* @param User $u
* @return authz integer
*/
public function user_may_manage(User $u) {
throw new Exception('user_may_manage not implemented for ' . get_class($this));
return false;
}
/**
* Determine if a User has permission delete this record.
* By default calls through to user_may_manage().
*
* @param User $u
* @return authz integer
*/
public function user_may_delete(User $u) {
return $this->user_may_manage($u);
}
/**
* Record a visit against this record by a given user, at a given IPv4 address.
*
* @return void
* @author sgilbertson
* @param array $config Keys: user (@see User); ip (string|int).
* */
public function visit($config) {
$user = null;
$ip = null;
extract($config);
UserVisit::create_visit(
array(
'record' => $this,
'user' => $user,
'ip' => $ip,
)
);
}
/**
* Add User reading-authorization conditions to a Doctrine Query. By
* default, any restrictions must come from subclasses.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_read(AIR2_Query $q, User $u, $alias=null) {
//TODO: alter query in subclasses
}
/**
* Add User write-authorization conditions to a Doctrine Query.
* TODO: by default, this is the same as read permissions.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_write(AIR2_Query $q, User $u, $alias=null) {
self::query_may_read($q, $u, $alias);
}
/**
* Add User managing-authorization conditions to a Doctrine Query.
* TODO: by default, this is the same as write permissions.
*
* @param AIR2_Query $q
* @param User $u
* @param string $alias (optional)
*/
public static function query_may_manage(AIR2_Query $q, User $u, $alias=null) {
self::query_may_write($q, $u, $alias);
}
/**
*
*
* @param string $model_name
* @param string $uuid
* @return AIR2_Record object for $model_name
*/
public static function find($model_name, $uuid) {
$tbl = Doctrine::getTable($model_name);
$col = air2_get_model_uuid_col($model_name);
return $tbl->findOneBy($col, $uuid);
}
/**
* Preinsert hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function preInsert($event) {
parent::preInsert($event);
AIR2Logger::log($this, 'insert');
}
/**
* Preupdate hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function preUpdate($event) {
parent::preUpdate($event);
AIR2Logger::log($this, 'update');
}
/**
* Postdelete hook for transactional activity logging.
*
* @param Doctrine_Event $event
*/
public function postDelete($event) {
AIR2Logger::log($this, 'delete');
parent::postDelete($event);
}
/**
* Returns object as JSON string. Only immediate columns
* (no related objects) are encoded.
*
* @return $json
*/
public function asJSON() {
$cols = $this->toArray(false);
return Encoding::json_encode_utf8($cols);
}
/**
* Custom mutator to reset timestamp to NULL value.
*
* @param unknown $field
* @param timestamp $value
*/
public function _set_timestamp($field, $value) {
if (empty($value) || !isset($value)) {
$this->_set($field, null);
}
else {
$this->_set($field, $value);
}
}
}
|
gpl-3.0
|
tamw-wnet/pbs-passport-authenticate
|
templates/oauthcallback.php
|
3067
|
<?php
/*
oauthcallback.php
This script handles the oAuth grant 'code' that is returned from the provider
(google/fb/openid), and calls the 'authenticate' method of the PBS_LAAS_Client.
That method exchanges the grant 'code' with PBS's endpoints to get access and refresh tokens,
uses those to get user info (email, name, etc), and then stores the tokens and userinfo encrypted
in session variables.
If the 'rememberme' variable was true, those tokens are also stored in an encrypted cookie.
*/
show_admin_bar(false);
remove_all_actions('wp_footer',1);
remove_all_actions('wp_header',1);
$defaults = get_option('pbs_passport_authenticate');
$passport = new PBS_Passport_Authenticate(dirname(__FILE__));
$laas_client = $passport->get_laas_client();
// log any current session out
$laas_client->logout();
$login_referrer = !empty($defaults['landing_page_url']) ? $defaults['landing_page_url'] : site_url();
if (!empty($_COOKIE["pbsoauth_login_referrer"])){
$login_referrer = $_COOKIE["pbsoauth_login_referrer"];
setcookie( 'pbsoauth_login_referrer', '', 1, '/', $_SERVER['HTTP_HOST']);
}
$membership_id = false;
// where to direct a logged in visitor who isn't a member
$not_member_path = 'pbsoauth/userinfo';
if (isset($_GET["state"])){
$state=($_GET["state"]);
$jwt = $passport->read_jwt($state);
if ($jwt) {
$membership_id = !empty($jwt['sub']) ? $jwt['sub'] : false;
// allow the jwt to override the current value with a return_path
$login_referrer = !empty($jwt['return_path']) ? site_url($jwt['return_path']) : $login_referrer;
// allow the jwt to set where the authenticated visitor who is not a member is sent
$not_member_path = !empty($jwt['not_member_path']) ? $jwt['not_member_path'] : $not_member_path;
} else {
// fallback case for older clients when membership_id was passed as a plaintext string
$membership_id = (!empty($state) ? $state : false);
}
}
$rememberme = false;
if (!empty($_COOKIE["pbsoauth_rememberme"])) {
$rememberme = $_COOKIE["pbsoauth_rememberme"];
}
// nonce is going to be in the jwt
$nonce = false;
$errors = array();
if (isset($_GET["code"])){
$code = $_GET["code"];
$userinfo = $laas_client->authenticate($code, $rememberme, $nonce);
}
// now we either have userinfo or null.
if (isset($userinfo["pid"])){
$pbs_uid = $userinfo["pid"];
// now we work with the mvault
$mvault_client = $passport->get_mvault_client();
$mvaultinfo = array();
if ($membership_id) {
// this is an activation!
$mvaultinfo = $mvault_client->get_membership($membership_id);
if (isset($mvaultinfo["membership_id"])) {
$mvaultinfo = $mvault_client->activate($membership_id, $pbs_uid);
}
}
// is the person activated now?
if (!isset($mvaultinfo["membership_id"])) {
$mvaultinfo = $mvault_client->get_membership_by_uid($pbs_uid);
if (!isset($mvaultinfo["membership_id"])) {
// still not activated, redirect the member as needed
$login_referrer = site_url($not_member_path);
}
}
}
wp_redirect($login_referrer);
exit();
?>
|
gpl-3.0
|
NuclearBacon/FWSyslog
|
Batch/installservice.bat
|
302
|
@ECHO OFF
IF EXIST %cd%\fwservice.exe (
c:\windows\microsoft.net\framework\v4.0.30319\installutil.exe %cd%\fwsyslog.exe
) ELSE (
GOTO FNFAbort
)
ECHO.
ECHO Batch complete.
ECHO.
GOTO EOB
:FNFAbort
ECHO.
ECHO Batch aborted! File fwsyslog.exe not found in current directory.
ECHO.
:EOB
ECHO ON
|
gpl-3.0
|
talos/docker4data
|
data/socrata/data.acgov.org/alameda_county_content_config/schema.sql
|
87
|
CREATE TABLE "alameda_county_content_config" (
"homepage" text,
"about_page" text
);
|
gpl-3.0
|
1npy0/easy-mapper
|
docs/easy-mapper-sample.html
|
4827
|
<!doctype html><html><head><title>Easy Image Mapper</title><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1"><link rel="stylesheet" href="easy-mapper.css">
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script><script src="easy-mapper-1.2.0.js"></script></head><body>
<!-- 딤 스크린 -->
<div id="dim"></div>
<div class="pop" id="pop-local">
<p class="pop-title">LOAD LOCAL IMAGE</p>
<div class="pop-content">
<input type="file" id="pop-local-input">
</div>
<div class="pop-btn">
<div class="pop-btn-confirm">LOAD</div>
<div class="pop-btn-cancel">CANCEL</div>
</div>
</div>
<div class="pop" id="pop-url">
<p class="pop-title">LINK IMAGE URL</p>
<div class="pop-content">
<input type="text" id="pop-url-input">
</div>
<div class="pop-btn">
<div class="pop-btn-confirm">LINK</div>
<div class="pop-btn-cancel">CANCEL</div>
</div>
</div>
<div class="pop" id="pop-code">
<p class="pop-title">CODE GENERATED</p>
<div class="pop-btn">
<div class="pop-btn-copy" id="pop-btn-copy-a">SHOW MARKUP AS <em><A> TAG</em> FORM</div>
<div class="pop-btn-copy" id="pop-btn-copy-im">SHOW MARKUP AS <em>IMAGE MAP</em> FORM</div>
<div class="pop-btn-cancel _full">CLOSE</div>
</div>
</div>
<div class="pop" id="pop-codegen-a">
<p class="pop-title"><A> TAG FORM</p>
<div class="pop-content">
<p></p>
</div>
<div class="pop-btn-cancel _back">BACK</div>
<div class="pop-btn-cancel">CLOSE</div>
</div>
<div class="pop" id="pop-codegen-im">
<p class="pop-title">IMAGE MAP FORM</p>
<div class="pop-content">
<p></p>
</div>
<div class="pop-btn-cancel _back">BACK</div>
<div class="pop-btn-cancel">CLOSE</div>
</div>
<div class="pop" id="pop-info">
<p class="pop-title">APP INFORMATION</p>
<div class="pop-content">
<p>
<em class="pop-content-alert">⚠ This app works on IE10+ only.</em>
<strong>Easy Image Mapper (v1.2.0)</strong><br>
Author: Inpyo Jeon<br>
Contact: inpyoj@gmail.com<br>
Website: <a class="_hover-ul" href="https://github.com/1npy0/easy-mapper" target="_blank">GitHub Repository</a>
</p>
</div>
<div class="pop-btn-cancel _full">CLOSE</div>
</div>
<div class="pop" id="pop-addlink">
<p class="pop-title">ADD URL LINK</p>
<div class="pop-content">
<input type="text" id="pop-addlink-input">
<label><input type="radio" name="pop-addlink-target" value="_blank" checked>New Window (target:_blank)</label>
<label><input type="radio" name="pop-addlink-target" value="_self">Self Frame (target:_self)</label>
<label><input type="radio" name="pop-addlink-target" value="_parent">Parent Frame (target:_parent)</label>
<label><input type="radio" name="pop-addlink-target" value="_top">Full Body (target:_top)</label>
</div>
<div class="pop-btn">
<div class="pop-btn-confirm">ADD LINK</div>
<div class="pop-btn-cancel">CANCEL</div>
</div>
</div>
<!-- 헤더 -->
<div id="gnb">
<a id="gnb-title" href="easy-mapper.html" onclick="if (!confirm('Do you want to reset all the changes?')) return false;">↻ REFRESH</a>
<!-- 드롭다운 메뉴 -->
<ul id="gnb-menu">
<li id="gnb-menu-source">
<span>SOURCE ▾</span>
<ul class="gnb-menu-sub">
<li id="gnb-menu-local">LOCAL</li>
<li id="gnb-menu-url">URL</li>
</ul>
</li>
<li id="gnb-menu-measure">
<span>MEASURE ▾</span>
<ul class="gnb-menu-sub _toggle">
<li id="gnb-menu-drag" class="_active">DRAG<em> ✓</em></li>
<li id="gnb-menu-click">CLICK<em> ✓</em></li>
</ul>
</li>
<li id="gnb-menu-unit">
<span>UNIT ▾</span>
<ul class="gnb-menu-sub _toggle">
<li id="gnb-menu-pixel" class="_active">PX<em> ✓</em></li>
<li id="gnb-menu-percent">%<em> ✓</em></li>
</ul>
</li>
<li id="gnb-menu-clear">
<span>CLEAR</span>
</li>
<li id="gnb-menu-generate">
<span>GENERATE</span>
</li>
<li id="gnb-menu-info">
<span>?</span>
</li>
</ul>
</div>
<!-- 작업공간 -->
<div id="workspace">
<!-- 눈금자 -->
<div id="workspace-ruler">
<div id="workspace-ruler-x">
<div id="workspace-ruler-x-2"></div>
<div id="workspace-ruler-x-1"></div>
</div>
<div id="workspace-ruler-y">
<div id="workspace-ruler-y-2"></div>
<div id="workspace-ruler-y-1"></div>
</div>
</div>
<!-- 이미지 -->
<div id="workspace-img-wrap">
<img id="workspace-img" src="sampleimg.png">
<!-- 그리드 -->
<div id="grid-x1" class="grid-1"></div>
<div id="grid-y1" class="grid-1"></div>
<div id="grid-x2" class="grid-2"></div>
<div id="grid-y2" class="grid-2"></div>
<span id="grid-coords"></span>
</div>
</div>
</body></html>
|
gpl-3.0
|
jpmac26/PGE-Project
|
MusicPlayer/MainWindow/musplayer_qt.cpp
|
19656
|
#ifndef MUSPLAY_USE_WINAPI
#include <QtDebug>
#include <QFileDialog>
#include <QMessageBox>
#include <QSlider>
#include <QSettings>
#include <QMenu>
#include <QDesktopServices>
#include <QUrl>
#include "ui_mainwindow.h"
#include "musplayer_qt.h"
#include "../Player/mus_player.h"
#include "../AssocFiles/assoc_files.h"
#include "../Effects/reverb.h"
#include <math.h>
#include "../version.h"
MusPlayer_Qt::MusPlayer_Qt(QWidget *parent) : QMainWindow(parent),
MusPlayerBase(),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
PGE_MusicPlayer::setMainWindow(this);
#ifdef Q_OS_MAC
this->setWindowIcon(QIcon(":/cat_musplay.icns"));
#endif
#ifdef Q_OS_WIN
this->setWindowIcon(QIcon(":/cat_musplay.ico"));
#endif
ui->fmbank->clear();
int totalBakns = MIX_ADLMIDI_getTotalBanks();
const char *const *names = MIX_ADLMIDI_getBankNames();
for(int i = 0; i < totalBakns; i++)
ui->fmbank->addItem(QString("%1 = %2").arg(i).arg(names[i]));
ui->centralWidget->window()->setWindowFlags(
Qt::WindowTitleHint |
Qt::WindowSystemMenuHint |
Qt::WindowCloseButtonHint |
Qt::WindowMinimizeButtonHint |
Qt::MSWindowsFixedSizeDialogHint);
connect(&m_blinker, SIGNAL(timeout()), this, SLOT(_blink_red()));
connect(this, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextMenu(QPoint)));
connect(ui->volume, &QSlider::valueChanged, [this](int x)
{
on_volume_valueChanged(x);
});
connect(ui->fmbank, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int x)
{
on_fmbank_currentIndexChanged(x);
});
connect(ui->volumeModel, static_cast<void(QComboBox::*)(int)>(&QComboBox::currentIndexChanged), this, [this](int x)
{
on_volumeModel_currentIndexChanged(x);
});
connect(ui->tremolo, &QCheckBox::clicked, this, [this](int x)
{
on_tremolo_clicked(x);
});
connect(ui->vibrato, &QCheckBox::clicked, this, [this](int x)
{
on_vibrato_clicked(x);
});
connect(ui->modulation, &QCheckBox::clicked, this, [this](int x)
{
on_modulation_clicked(x);
});
connect(ui->adlibMode, &QCheckBox::clicked, this, [this](int x)
{
on_adlibMode_clicked(x);
});
connect(ui->logVolumes, &QCheckBox::clicked, this, [this](int x)
{
on_logVolumes_clicked(x);
});
connect(ui->playListPush, &QPushButton::clicked, this, &MusPlayer_Qt::playList_pushCurrent);
connect(ui->playListPop, &QPushButton::clicked, this, &MusPlayer_Qt::playList_popCurrent);
QApplication::setOrganizationName(_COMPANY);
QApplication::setOrganizationDomain(_PGE_URL);
QApplication::setApplicationName("PGE Music Player");
ui->playList->setModel(&playList);
ui->playList->setVisible(false);
ui->playListPush->setVisible(false);
ui->playListPop->setVisible(false);
ui->sfx_testing->setVisible(false);
QSettings setup;
restoreGeometry(setup.value("Window-Geometry").toByteArray());
ui->mididevice->setCurrentIndex(setup.value("MIDI-Device", 0).toInt());
ui->opnmidi_extra->setVisible(ui->mididevice->currentIndex() == 3);
ui->adlmidi_xtra->setVisible(ui->mididevice->currentIndex() == 0);
switch(ui->mididevice->currentIndex())
{
case 0:
MIX_SetMidiDevice(MIDI_ADLMIDI);
break;
case 1:
MIX_SetMidiDevice(MIDI_Timidity);
break;
case 2:
MIX_SetMidiDevice(MIDI_Native);
break;
case 3:
MIX_SetMidiDevice(MIDI_OPNMIDI);
break;
case 4:
MIX_SetMidiDevice(MIDI_Fluidsynth);
break;
default:
MIX_SetMidiDevice(MIDI_ADLMIDI);
break;
}
ui->fmbank->setCurrentIndex(setup.value("ADLMIDI-Bank-ID", 58).toInt());
MIX_ADLMIDI_setBankID(ui->fmbank->currentIndex());
ui->volumeModel->setCurrentIndex(setup.value("ADLMIDI-VolumeModel", 0).toInt());
MIX_ADLMIDI_setVolumeModel(ui->volumeModel->currentIndex());
ui->tremolo->setChecked(setup.value("ADLMIDI-Tremolo", true).toBool());
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
ui->vibrato->setChecked(setup.value("ADLMIDI-Vibrato", true).toBool());
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
ui->adlibMode->setChecked(setup.value("ADLMIDI-AdLib-Drums-Mode", false).toBool());
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
ui->modulation->setChecked(setup.value("ADLMIDI-Scalable-Modulation", false).toBool());
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
ui->logVolumes->setChecked(setup.value("ADLMIDI-LogarithmicVolumes", false).toBool());
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->logVolumes->isChecked()));
ui->volume->setValue(setup.value("Volume", 128).toInt());
m_prevTrackID = ui->trackID->value();
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(false);
ui->gme_setup->setVisible(false);
currentMusic = setup.value("RecentMusic", "").toString();
m_testSfxDir = setup.value("RecentSfxDir", "").toString();
adjustSize();
}
MusPlayer_Qt::~MusPlayer_Qt()
{
on_stop_clicked();
if(m_testSfx)
Mix_FreeChunk(m_testSfx);
m_testSfx = nullptr;
Mix_CloseAudio();
QSettings setup;
setup.setValue("Window-Geometry", saveGeometry());
setup.setValue("MIDI-Device", ui->mididevice->currentIndex());
setup.setValue("ADLMIDI-Bank-ID", ui->fmbank->currentIndex());
setup.setValue("ADLMIDI-VolumeModel", ui->volumeModel->currentIndex());
setup.setValue("ADLMIDI-Tremolo", ui->tremolo->isChecked());
setup.setValue("ADLMIDI-Vibrato", ui->vibrato->isChecked());
setup.setValue("ADLMIDI-AdLib-Drums-Mode", ui->adlibMode->isChecked());
setup.setValue("ADLMIDI-Scalable-Modulation", ui->modulation->isChecked());
setup.setValue("ADLMIDI-LogarithmicVolumes", ui->logVolumes->isChecked());
setup.setValue("Volume", ui->volume->value());
setup.setValue("RecentMusic", currentMusic);
setup.setValue("RecentSfxDir", m_testSfxDir);
delete ui;
}
void MusPlayer_Qt::dropEvent(QDropEvent *e)
{
this->raise();
this->setFocus(Qt::ActiveWindowFocusReason);
if(ui->recordWav->isChecked())
return;
for(const QUrl &url : e->mimeData()->urls())
{
const QString &fileName = url.toLocalFile();
currentMusic = fileName;
}
ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
this->raise();
e->accept();
}
void MusPlayer_Qt::dragEnterEvent(QDragEnterEvent *e)
{
if(e->mimeData()->hasUrls())
e->acceptProposedAction();
}
void MusPlayer_Qt::contextMenu(const QPoint &pos)
{
QMenu x;
QAction *open = x.addAction("Open");
QAction *playpause = x.addAction("Play/Pause");
QAction *stop = x.addAction("Stop");
x.addSeparator();
QAction *reverb = x.addAction("Reverb");
reverb->setCheckable(true);
reverb->setChecked(PGE_MusicPlayer::reverbEnabled);
QAction *assoc_files = x.addAction("Associate files");
QAction *play_list = x.addAction("Play-list mode [WIP]");
play_list->setCheckable(true);
play_list->setChecked(playListMode);
QAction *sfx_testing = x.addAction("SFX testing");
sfx_testing->setCheckable(true);
sfx_testing->setChecked(ui->sfx_testing->isVisible());
x.addSeparator();
QMenu *about = x.addMenu("About");
QAction *version = about->addAction("SDL Mixer X Music Player v." _FILE_VERSION);
version->setEnabled(false);
QAction *license = about->addAction("Licensed under GNU GPLv3 license");
about->addSeparator();
QAction *source = about->addAction("Get source code");
QAction *ret = x.exec(this->mapToGlobal(pos));
if(open == ret)
on_open_clicked();
else if(playpause == ret)
on_play_clicked();
else if(stop == ret)
on_stop_clicked();
else if(reverb == ret)
{
PGE_MusicPlayer::reverbEnabled = reverb->isChecked();
if(PGE_MusicPlayer::reverbEnabled)
Mix_RegisterEffect(MIX_CHANNEL_POST, reverbEffect, reverbEffectDone, NULL);
else
Mix_UnregisterEffect(MIX_CHANNEL_POST, reverbEffect);
}
else if(assoc_files == ret)
{
AssocFiles af(this);
af.setWindowModality(Qt::WindowModal);
af.exec();
}
else if(ret == play_list)
{
setPlayListMode(!playListMode);
}
else if(ret == sfx_testing)
{
ui->sfx_testing->setVisible(!ui->sfx_testing->isVisible());
updateGeometry();
adjustSize();
}
else if(ret == license)
QDesktopServices::openUrl(QUrl("http://www.gnu.org/licenses/gpl"));
else if(ret == source)
QDesktopServices::openUrl(QUrl("https://github.com/WohlSoft/PGE-Project"));
}
void MusPlayer_Qt::openMusicByArg(QString musPath)
{
if(ui->recordWav->isChecked()) return;
currentMusic = musPath;
//ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::setPlayListMode(bool plMode)
{
on_stop_clicked();
playListMode = plMode;
if(!plMode)
{
playList.clear();
} else {
playList_pushCurrent();
}
ui->playList->setVisible(plMode);
ui->playListPush->setVisible(plMode);
ui->playListPop->setVisible(plMode);
if(ui->recordWav->isChecked())
ui->recordWav->click();
ui->recordWav->setVisible(!plMode);
PGE_MusicPlayer::setPlayListMode(playListMode);
adjustSize();
}
void MusPlayer_Qt::playList_pushCurrent(bool)
{
PlayListEntry e;
e.name = ui->musTitle->text();
e.fullPath = currentMusic;
e.gme_trackNum = ui->trackID->value();
e.midi_device = ui->mididevice->currentIndex();
e.adl_bankNo = ui->fmbank->currentIndex();
e.adl_cmfVolumes = ui->volumeModel->currentIndex();
e.adl_tremolo = ui->tremolo->isChecked();
e.adl_vibrato = ui->vibrato->isChecked();
e.adl_adlibDrums = ui->adlibMode->isChecked();
e.adl_modulation = ui->modulation->isChecked();
e.adl_cmfVolumes = ui->logVolumes->isChecked();
playList.insertEntry(e);
}
void MusPlayer_Qt::playList_popCurrent(bool)
{
playList.removeEntry();
}
void MusPlayer_Qt::playListNext()
{
PlayListEntry e = playList.nextEntry();
currentMusic = e.fullPath;
switchMidiDevice(e.midi_device);
ui->trackID->setValue(e.gme_trackNum);
ui->fmbank->setCurrentIndex(e.adl_bankNo);
ui->volumeModel->setCurrentIndex(e.adl_volumeModel);
ui->tremolo->setChecked(e.adl_tremolo);
ui->vibrato->setChecked(e.adl_vibrato);
ui->adlibMode->setChecked(e.adl_adlibDrums);
ui->modulation->setChecked(e.adl_modulation);
ui->logVolumes->setChecked(e.adl_cmfVolumes);
MIX_ADLMIDI_setBankID(e.adl_bankNo);
MIX_ADLMIDI_setVolumeModel(e.adl_volumeModel);
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
MIX_ADLMIDI_setLogarithmicVolumes(static_cast<int>(ui->logVolumes->isChecked()));
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::switchMidiDevice(int index)
{
ui->midi_setup->setVisible(false);
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(true);
switch(index)
{
case 0:
MIX_SetMidiDevice(MIDI_ADLMIDI);
ui->adlmidi_xtra->setVisible(true);
break;
case 1:
MIX_SetMidiDevice(MIDI_Timidity);
break;
case 2:
MIX_SetMidiDevice(MIDI_Native);
break;
case 3:
MIX_SetMidiDevice(MIDI_OPNMIDI);
ui->opnmidi_extra->setVisible(true);
break;
case 4:
MIX_SetMidiDevice(MIDI_Fluidsynth);
break;
default:
MIX_SetMidiDevice(MIDI_ADLMIDI);
ui->adlmidi_xtra->setVisible(true);
break;
}
}
void MusPlayer_Qt::on_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open music file"),
(currentMusic.isEmpty() ? QApplication::applicationDirPath() : currentMusic), "All (*.*)");
if(file.isEmpty())
return;
currentMusic = file;
//ui->recordWav->setEnabled(!currentMusic.endsWith(".wav", Qt::CaseInsensitive));//Avoid self-trunkling!
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
void MusPlayer_Qt::on_stop_clicked()
{
PGE_MusicPlayer::MUS_stopMusic();
ui->play->setText(tr("Play"));
if(ui->recordWav->isChecked())
{
ui->recordWav->setChecked(false);
PGE_MusicPlayer::stopWavRecording();
ui->open->setEnabled(true);
ui->play->setEnabled(true);
ui->frame->setEnabled(true);
m_blinker.stop();
ui->recordWav->setStyleSheet("");
}
}
void MusPlayer_Qt::on_play_clicked()
{
if(Mix_PlayingMusic())
{
if(Mix_PausedMusic())
{
Mix_ResumeMusic();
ui->play->setText(tr("Pause"));
return;
}
else
{
Mix_PauseMusic();
ui->play->setText(tr("Resume"));
return;
}
}
ui->play->setText(tr("Play"));
m_prevTrackID = ui->trackID->value();
if(PGE_MusicPlayer::MUS_openFile(currentMusic + "|" + ui->trackID->text()))
{
PGE_MusicPlayer::MUS_changeVolume(ui->volume->value());
PGE_MusicPlayer::MUS_playMusic();
ui->play->setText(tr("Pause"));
}
ui->musTitle->setText(PGE_MusicPlayer::MUS_getMusTitle());
ui->musArtist->setText(PGE_MusicPlayer::MUS_getMusArtist());
ui->musAlbum->setText(PGE_MusicPlayer::MUS_getMusAlbum());
ui->musCopyright->setText(PGE_MusicPlayer::MUS_getMusCopy());
ui->gme_setup->setVisible(false);
ui->adlmidi_xtra->setVisible(false);
ui->opnmidi_extra->setVisible(false);
ui->midi_setup->setVisible(false);
ui->frame->setVisible(false);
ui->frame->setVisible(true);
ui->smallInfo->setText(PGE_MusicPlayer::musicType());
ui->gridLayout->update();
switch(PGE_MusicPlayer::type)
{
case MUS_MID:
ui->adlmidi_xtra->setVisible(ui->mididevice->currentIndex() == 0);
ui->opnmidi_extra->setVisible(ui->mididevice->currentIndex() == 3);
ui->midi_setup->setVisible(true);
ui->frame->setVisible(true);
break;
case MUS_SPC:
ui->gme_setup->setVisible(true);
ui->frame->setVisible(true);
break;
default:
break;
}
adjustSize();
}
void MusPlayer_Qt::on_mididevice_currentIndexChanged(int index)
{
switchMidiDevice(index);
adjustSize();
if(Mix_PlayingMusic())
{
if(PGE_MusicPlayer::type == MUS_MID)
{
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
}
}
void MusPlayer_Qt::on_trackID_editingFinished()
{
if(Mix_PlayingMusic())
{
if((PGE_MusicPlayer::type == MUS_SPC) && (m_prevTrackID != ui->trackID->value()))
{
PGE_MusicPlayer::MUS_stopMusic();
on_play_clicked();
}
}
}
void MusPlayer_Qt::on_recordWav_clicked(bool checked)
{
if(checked)
{
PGE_MusicPlayer::MUS_stopMusic();
ui->play->setText(tr("Play"));
QFileInfo twav(currentMusic);
PGE_MusicPlayer::stopWavRecording();
QString wavPathBase = twav.absoluteDir().absolutePath() + "/" + twav.baseName();
QString wavPath = wavPathBase + ".wav";
int count = 1;
while(QFile::exists(wavPath))
wavPath = wavPathBase + QString("-%1.wav").arg(count++);
PGE_MusicPlayer::startWavRecording(wavPath);
on_play_clicked();
ui->open->setEnabled(false);
ui->play->setEnabled(false);
ui->frame->setEnabled(false);
m_blinker.start(500);
}
else
{
on_stop_clicked();
PGE_MusicPlayer::stopWavRecording();
ui->open->setEnabled(true);
ui->play->setEnabled(true);
ui->frame->setEnabled(true);
m_blinker.stop();
ui->recordWav->setStyleSheet("");
}
}
void MusPlayer_Qt::on_resetDefaultADLMIDI_clicked()
{
ui->fmbank->setCurrentIndex(58);
ui->tremolo->setChecked(true);
ui->vibrato->setChecked(true);
ui->adlibMode->setChecked(false);
ui->modulation->setChecked(false);
ui->logVolumes->setChecked(false);
MIX_ADLMIDI_setTremolo(static_cast<int>(ui->tremolo->isChecked()));
MIX_ADLMIDI_setVibrato(static_cast<int>(ui->vibrato->isChecked()));
MIX_ADLMIDI_setAdLibMode(static_cast<int>(ui->adlibMode->isChecked()));
MIX_ADLMIDI_setScaleMod(static_cast<int>(ui->modulation->isChecked()));
MIX_ADLMIDI_setLogarithmicVolumes(static_cast<int>(ui->logVolumes->isChecked()));
on_volumeModel_currentIndexChanged(ui->volumeModel->currentIndex());
on_fmbank_currentIndexChanged(ui->fmbank->currentIndex());
}
void MusPlayer_Qt::_blink_red()
{
m_blink_state = !m_blink_state;
if(m_blink_state)
ui->recordWav->setStyleSheet("background-color : red; color : black;");
else
ui->recordWav->setStyleSheet("background-color : black; color : red;");
}
void MusPlayer_Qt::on_sfx_open_clicked()
{
QString file = QFileDialog::getOpenFileName(this, tr("Open SFX file"),
(m_testSfxDir.isEmpty() ? QApplication::applicationDirPath() : m_testSfxDir), "All (*.*)");
if(file.isEmpty())
return;
if(m_testSfx)
{
Mix_HaltChannel(0);
Mix_FreeChunk(m_testSfx);
m_testSfx = nullptr;
}
m_testSfx = Mix_LoadWAV(file.toUtf8().data());
if(!m_testSfx)
QMessageBox::warning(this, "SFX open error!", QString("Mix_LoadWAV: ") + Mix_GetError());
else
{
QFileInfo f(file);
m_testSfxDir = f.absoluteDir().absolutePath();
ui->sfx_file->setText(f.fileName());
}
}
void MusPlayer_Qt::on_sfx_play_clicked()
{
if(!m_testSfx)
return;
if(Mix_PlayChannelTimedVolume(0,
m_testSfx,
ui->sfx_loops->value(),
ui->sfx_timed->value(),
ui->sfx_volume->value()) == -1)
{
QMessageBox::warning(this, "SFX play error!", QString("Mix_PlayChannelTimedVolume: ") + Mix_GetError());
}
}
void MusPlayer_Qt::on_sfx_fadeIn_clicked()
{
if(!m_testSfx)
return;
if(Mix_FadeInChannelTimedVolume(0,
m_testSfx,
ui->sfx_loops->value(),
ui->sfx_fadems->value(),
ui->sfx_timed->value(),
ui->sfx_volume->value()) == -1)
{
QMessageBox::warning(this, "SFX play error!", QString("Mix_PlayChannelTimedVolume: ") + Mix_GetError());
}
}
void MusPlayer_Qt::on_sfx_stop_clicked()
{
if(!m_testSfx)
return;
Mix_HaltChannel(0);
}
void MusPlayer_Qt::on_sfx_fadeout_clicked()
{
if(!m_testSfx)
return;
Mix_FadeOutChannel(0, ui->sfx_fadems->value());
}
#endif
|
gpl-3.0
|
Freenex1911/FeexRanks
|
Database/EQueryType.cs
|
128
|
namespace Freenex.FeexRanks.Database
{
public enum EQueryType
{
Scalar,
Reader,
NonQuery
}
}
|
gpl-3.0
|
j9recurses/whirld
|
vendor/assets/components/normalize.css/normalize.css
|
7799
|
/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS and IE text size adjust after device orientation change,
* without disabling user zoom.
*/
html {
font-family: sans-serif; /* 1 */
height: 100%;
-ms-text-size-adjust: 100%; /* 2 */
-webkit-text-size-adjust: 100%; /* 2 */
width: 100%;
}
/**
* Remove default margin.
*/
body {
background-color: #e6e7e8;
height: 100%;
margin: 0;
width: 100%;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block; /* 1 */
vertical-align: baseline; /* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/10/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* Improve readability of focused elements when they are also in an
* active/hover state.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit; /* 1 */
font: inherit; /* 2 */
margin: 0; /* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"], /* 1 */
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button; /* 2 */
cursor: pointer; /* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box; /* 1 */
padding: 0; /* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome.
*/
input[type="search"] {
-webkit-appearance: textfield; /* 1 */
box-sizing: content-box; /* 2 */
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0; /* 1 */
padding: 0; /* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
|
gpl-3.0
|
cjforman/pele
|
pele/angleaxis/tests/test_otp.py
|
11705
|
import unittest
from itertools import izip
import numpy as np
from numpy import cos, sin, pi
from pele.angleaxis import RBTopology, RigidFragment, RBPotentialWrapper
from pele.potentials import LJ
from pele.angleaxis._otp_cluster import OTPCluster
from pele.thermodynamics import get_thermodynamic_information
from pele.utils import rotations
from pele.angleaxis._aa_utils import _rot_mat_derivative, _sitedist_grad, _sitedist
from pele.angleaxis.aamindist import MeasureRigidBodyCluster
_x03 = np.array([2.550757898788, 2.591553038507, 3.696836364193,
2.623281513163, 3.415794212648, 3.310786279789,
1.791383852327, 2.264321752809, 4.306217333671,
0.761945654023, -0.805817782109, 1.166981882601,
0.442065301864, -2.747066418223, -1.784325262714,
-1.520905562598, 0.403670860200, -0.729768985400])
_x03_atomistic = np.array([3.064051819556, 2.474533745459, 3.646107658946,
2.412011983074, 2.941152759499, 4.243695098053,
2.176209893734, 2.358972610563, 3.200706335581,
2.786627589565, 3.211876105193, 2.850924310983,
1.962626909252, 3.436918873216, 3.370903763850,
3.120590040673, 3.598587659535, 3.710530764535,
1.697360211099, 2.317229950712, 4.823998989452,
2.283487958310, 1.840698306602, 4.168734267290,
1.393303387573, 2.635037001113, 3.925918744272
])
class TestOTPExplicit(unittest.TestCase):
def make_otp(self):
"""this constructs a single OTP molecule"""
otp = RigidFragment()
otp.add_atom("O", np.array([0.0, -2./3 * np.sin( 7.*pi/24.), 0.0]), 1.)
otp.add_atom("O", np.array([cos( 7.*pi/24.), 1./3. * sin( 7.* pi/24.), 0.0]), 1.)
otp.add_atom("O", np.array([-cos( 7.* pi/24.), 1./3. * sin( 7.*pi/24), 0.0]), 1.)
otp.finalize_setup()
return otp
def setUp(self):
nrigid = 3
self.topology = RBTopology()
self.topology.add_sites([self.make_otp() for i in xrange(nrigid)])
self.topology.finalize_setup()
cartesian_potential = LJ()
self.pot = RBPotentialWrapper(self.topology, cartesian_potential)
self.x0 = _x03
self.x0 = np.array(self.x0)
self.e0 = -17.3387670023
assert nrigid * 6 == self.x0.size
self.x0atomistic = _x03_atomistic
self.nrigid = nrigid
def test_energy(self):
e = self.pot.getEnergy(self.x0)
self.assertAlmostEqual(e, self.e0, delta=1e-4)
def test_energy_gradient(self):
e = self.pot.getEnergy(self.x0)
gnum = self.pot.NumericalDerivative(self.x0)
e2, g = self.pot.getEnergyGradient(self.x0)
self.assertAlmostEqual(e, e2, delta=1e-4)
for i in xrange(g.size):
self.assertAlmostEqual(g[i], gnum[i], 2)
def test_to_atomistic(self):
xatom = self.topology.to_atomistic(self.x0).flatten()
for i in xrange(xatom.size):
self.assertAlmostEqual(xatom[i], self.x0atomistic[i], 2)
def test_site_to_atomistic(self):
rf = self.make_otp()
p = np.array([1., 2, 3])
p /= np.linalg.norm(p)
com = np.array([4., 5, 6])
print "otp to atomistic"
print rf.to_atomistic(com, p)
print "otp transform grad"
g = np.array(range(9), dtype=float).reshape([-1,3])
print g.reshape(-1)
print rf.transform_grad(p, g)
def test_to_atomistic2(self):
x0 = np.array(range(self.nrigid * 6), dtype=float)
x2 = x0.reshape([-1,3])
for p in x2[self.nrigid:,:]:
p /= np.linalg.norm(p)
atomistic = self.topology.to_atomistic(x0).flatten()
from pele.potentials import LJ
lj = LJ()
e, g = lj.getEnergyGradient(atomistic.reshape(-1))
grb = self.topology.transform_gradient(x0, g)
rbpot = RBPotentialWrapper(self.topology, lj)
print rbpot.getEnergy(x0)
class TestCppRBPotentialWrapper(TestOTPExplicit):
def test_pot_wrapper(self):
from pele.angleaxis import _cpp_aa
from pele.potentials import LJ
rbpot_cpp = _cpp_aa.RBPotentialWrapper(self.topology, LJ())
rbpot = RBPotentialWrapper(self.topology, LJ())
self.assertAlmostEqual(rbpot_cpp.getEnergy(self.x0),
rbpot.getEnergy(self.x0), 4)
e1, grad1 = rbpot_cpp.getEnergyGradient(self.x0)
e2, grad2 = rbpot.getEnergyGradient(self.x0)
self.assertAlmostEqual(e1, e2, 4)
for g1, g2 in zip(grad1, grad2):
self.assertAlmostEqual(g1, g2, 3)
# print "energy cpp"
# print e1, e2
# print grad1
# print grad2
_x1 = np.array([ 1.9025655 , 0.39575842, 2.70994994, 1.12711741, 0.63413933,
1.99433564, 1.86553644, 1.71434811, 2.22927686, 0.80189315,
1.19513512, 3.02357997, 1.25845172, -0.06244027, 1.27217385,
-2.26564485, 0.25537024, 0.66231258, -1.49510664, 0.94428774,
-0.04120075, -0.87664883, -0.21441754, 2.05796547])
_x2 = np.array([ 2.01932983, 0.32928065, 2.34949584, 1.12261277, 0.84195098,
2.08827517, 1.42644916, 1.83608794, 2.23147536, 1.12872074,
0.93206141, 3.28789605, 1.73243138, -0.1199651 , 1.02925229,
-1.64603729, 0.30701482, 0.90204992, -1.96259809, 0.06557119,
0.11010908, -0.37462588, -0.42374544, 1.97728056])
class TestOTPCluster(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.nmol = 4
self.system = OTPCluster(self.nmol)
pot = self.system.get_potential()
self.db = self.system.create_database()
self.m1 = self.db.addMinimum(pot.getEnergy(_x1), _x1)
self.m2 = self.db.addMinimum(pot.getEnergy(_x2), _x2)
def test1(self):
pot = self.system.get_potential()
self.assertLess(np.linalg.norm(pot.getGradient(self.m1.coords)), .1)
self.assertLess(np.linalg.norm(pot.getGradient(self.m2.coords)), .1)
def test_basinhopping(self):
db = self.system.create_database()
bh = self.system.get_basinhopping(db)
bh.setPrinting(ostream=None)
bh.run(5)
self.assertGreaterEqual(db.number_of_minima(), 1)
def test_double_ended_connect(self):
connect = self.system.get_double_ended_connect(self.m1, self.m2, self.db)
connect.connect()
self.assertTrue(connect.success())
path = connect.returnPath()
def test_thermodynamics(self):
get_thermodynamic_information(self.system, self.db, nproc=None, recalculate=True)
self.assertIsNotNone(self.m1.fvib)
mt = self.system.get_metric_tensor(self.m1.coords)
print "metric tensor"
print mt
class TestRBTopologyOTP(unittest.TestCase):
def setUp(self):
np.random.seed(0)
self.nmol = 3
self.system = OTPCluster(self.nmol)
# pot = self.system.get_potential()
# self.db = self.system.create_database()
# self.m1 = self.db.addMinimum(pot.getEnergy(_x1), _x1)
# self.m2 = self.db.addMinimum(pot.getEnergy(_x2), _x2)
self.x0 = np.array([ 0, 1, 2, 3, 4, 5, 6, 7, 8,
0.517892, 0.575435, 0.632979,
0.531891, 0.576215, 0.620539,
0.540562, 0.5766, 0.612637 ])
from pele.angleaxis.aamindist import TransformAngleAxisCluster
self.topology = self.system.aatopology
self.transform = TransformAngleAxisCluster(self.topology)
self.p0 = np.array(range(1,4), dtype=float)
self.p0 /= np.linalg.norm(self.p0)
def test_transform_rotate(self):
print "\ntest rotate"
x = self.x0.copy()
p = np.array(range(1,4), dtype=float)
p /= np.linalg.norm(p)
self.transform.rotate(x, rotations.aa2mx(p))
xnewtrue = np.array([ 0.48757698, 0.61588594, 2.09355038, 2.02484605, 4.76822812,
4.81289924, 3.56211511, 8.92057031, 7.53224809, 0.71469473,
1.23875927, 1.36136748, 0.72426504, 1.24674367, 1.34426835,
0.73015833, 1.25159032, 1.33345003])
for v1, v2 in izip(x, xnewtrue):
self.assertAlmostEqual(v1, v2, 5)
def test_align_path(self):
print "\ntest align_path"
x1 = self.x0.copy()
x2 = self.x0 + 5
self.topology.align_path([x1, x2])
x2true = np.array([ 5. , 6. , 7. , 8. ,
9. , 10. , 11. , 12. ,
13. , 1.92786071, 1.94796529, 1.96807021,
1.93320298, 1.94869267, 1.96418236, 1.93645608,
1.94905155, 1.96164668])
for v1, v2 in izip(x1, self.x0):
self.assertAlmostEqual(v1, v2, 5)
for v1, v2 in izip(x2, x2true):
self.assertAlmostEqual(v1, v2, 5)
def test_cpp_zero_ev(self):
print "\ntest zeroEV cpp"
x = self.x0.copy()
zev = self.topology._zeroEV_python(x)
czev = self.topology.cpp_topology.get_zero_modes(x)
self.assertEqual(len(czev), 6)
for ev, cev in izip(zev, czev):
for v1, v2 in izip(ev, cev):
self.assertAlmostEqual(v1, v2, 5)
def test_site_distance_squared(self):
print "\ntest site distance squared"
c0 = np.zeros(3)
c1 = np.ones(3)
p0 = self.p0.copy()
p1 = p0 + 1
site = self.system.make_otp()
d2 = site.distance_squared(c0, p0, c1, p1)
d2p = _sitedist(c1-c0, p0, p1, site.S, site.W, site.cog)
self.assertAlmostEqual(d2, 10.9548367929, 5)
def test_distance_squared(self):
print "\ntest distance squared"
x1 = self.x0.copy()
x2 = self.x0 + 1.1
d2 = self.topology.distance_squared(x1, x2)
d3 = self.topology._distance_squared_python(x1, x2)
self.assertAlmostEqual(d2, 38.9401810973, 5)
self.assertAlmostEqual(d2, d3, 5)
def test_distance_squared_grad(self):
print "\ntest distance squared grad"
x1 = self.x0.copy()
x2 = self.x0 + 1.1
grad = self.topology.distance_squared_grad(x1, x2)
g2 = self.topology._distance_squared_grad_python(x1, x2)
gtrue = np.array([-6.6 , -6.6 , -6.6 , -6.6 , -6.6 ,
-6.6 , -6.6 , -6.6 , -6.6 , -1.21579025,
-0.07013805, -1.2988823 , -1.21331786, -0.06984532, -1.28945301,
-1.2116105 , -0.06975828, -1.28362943])
for v1, v2 in izip(grad, gtrue):
self.assertAlmostEqual(v1, v2, 5)
for v1, v2 in izip(grad, g2):
self.assertAlmostEqual(v1, v2, 5)
def test_measure_align(self):
print "\ntest measure align"
x1 = self.x0.copy()
x2 = self.x0 + 5.1
x2[-1] = x1[-1] + .1
x20 = x2.copy()
measure = MeasureRigidBodyCluster(self.topology)
measure.align(x1, x2)
if __name__ == "__main__":
unittest.main()
|
gpl-3.0
|
AironSkythe/guess-word-game
|
guess_game/guess_game/Program.cs
|
518
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace guess_word_game
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new DAOForm());
}
}
}
|
gpl-3.0
|
pwldp/rodzice-na-czasie-pl
|
node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/Makefile
|
13026
|
# We borrow heavily from the kernel build setup, though we are simpler since
# we don't have Kconfig tweaking settings on us.
# The implicit make rules have it looking for RCS files, among other things.
# We instead explicitly write all the rules we care about.
# It's even quicker (saves ~200ms) to pass -r on the command line.
MAKEFLAGS=-r
# The source directory tree.
srcdir := ..
abs_srcdir := $(abspath $(srcdir))
# The name of the builddir.
builddir_name ?= .
# The V=1 flag on command line makes us verbosely print command lines.
ifdef V
quiet=
else
quiet=quiet_
endif
# Specify BUILDTYPE=Release on the command line for a release build.
BUILDTYPE ?= Release
# Directory all our build output goes into.
# Note that this must be two directories beneath src/ for unit tests to pass,
# as they reach into the src/ directory for data with relative paths.
builddir ?= $(builddir_name)/$(BUILDTYPE)
abs_builddir := $(abspath $(builddir))
depsdir := $(builddir)/.deps
# Object output directory.
obj := $(builddir)/obj
abs_obj := $(abspath $(obj))
# We build up a list of every single one of the targets so we can slurp in the
# generated dependency rule Makefiles in one pass.
all_deps :=
# C++ apps need to be linked with g++.
#
# Note: flock is used to seralize linking. Linking is a memory-intensive
# process so running parallel links can often lead to thrashing. To disable
# the serialization, override LINK via an envrionment variable as follows:
#
# export LINK=g++
#
# This will allow make to invoke N linker processes as specified in -jN.
LINK ?= flock $(builddir)/linker.lock $(CXX)
CC.target ?= $(CC)
CFLAGS.target ?= $(CFLAGS)
CXX.target ?= $(CXX)
CXXFLAGS.target ?= $(CXXFLAGS)
LINK.target ?= $(LINK)
LDFLAGS.target ?= $(LDFLAGS)
AR.target ?= $(AR)
# TODO(evan): move all cross-compilation logic to gyp-time so we don't need
# to replicate this environment fallback in make as well.
CC.host ?= gcc
CFLAGS.host ?=
CXX.host ?= g++
CXXFLAGS.host ?=
LINK.host ?= g++
LDFLAGS.host ?=
AR.host ?= ar
# Define a dir function that can handle spaces.
# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions
# "leading spaces cannot appear in the text of the first argument as written.
# These characters can be put into the argument value by variable substitution."
empty :=
space := $(empty) $(empty)
# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces
replace_spaces = $(subst $(space),?,$1)
unreplace_spaces = $(subst ?,$(space),$1)
dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1)))
# Flags to make gcc output dependency info. Note that you need to be
# careful here to use the flags that ccache and distcc can understand.
# We write to a dep file on the side first and then rename at the end
# so we can't end up with a broken dep file.
depfile = $(depsdir)/$(call replace_spaces,$@).d
DEPFLAGS = -MMD -MF $(depfile).raw
# We have to fixup the deps output in a few ways.
# (1) the file output should mention the proper .o file.
# ccache or distcc lose the path to the target, so we convert a rule of
# the form:
# foobar.o: DEP1 DEP2
# into
# path/to/foobar.o: DEP1 DEP2
# (2) we want missing files not to cause us to fail to build.
# We want to rewrite
# foobar.o: DEP1 DEP2 \
# DEP3
# to
# DEP1:
# DEP2:
# DEP3:
# so if the files are missing, they're just considered phony rules.
# We have to do some pretty insane escaping to get those backslashes
# and dollar signs past make, the shell, and sed at the same time.
# Doesn't work with spaces, but that's fine: .d files have spaces in
# their names replaced with other characters.
define fixup_dep
# The depfile may not exist if the input file didn't have any #includes.
touch $(depfile).raw
# Fixup path as in (1).
sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile)
# Add extra rules as in (2).
# We remove slashes and replace spaces with new lines;
# remove blank lines;
# delete the first line and append a colon to the remaining lines.
sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\
grep -v '^$$' |\
sed -e 1d -e 's|$$|:|' \
>> $(depfile)
rm $(depfile).raw
endef
# Command definitions:
# - cmd_foo is the actual command to run;
# - quiet_cmd_foo is the brief-output summary of the command.
quiet_cmd_cc = CC($(TOOLSET)) $@
cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_cxx = CXX($(TOOLSET)) $@
cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $<
quiet_cmd_touch = TOUCH $@
cmd_touch = touch $@
quiet_cmd_copy = COPY $@
# send stderr to /dev/null to ignore messages when linking directories.
cmd_copy = rm -rf "$@" && cp -af "$<" "$@"
quiet_cmd_alink = AR($(TOOLSET)) $@
cmd_alink = rm -f $@ && $(AR.$(TOOLSET)) crs $@ $(filter %.o,$^)
quiet_cmd_alink_thin = AR($(TOOLSET)) $@
cmd_alink_thin = rm -f $@ && $(AR.$(TOOLSET)) crsT $@ $(filter %.o,$^)
# Due to circular dependencies between libraries :(, we wrap the
# special "figure out circular dependencies" flags around the entire
# input list during linking.
quiet_cmd_link = LINK($(TOOLSET)) $@
cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ -Wl,--start-group $(LD_INPUTS) -Wl,--end-group $(LIBS)
# We support two kinds of shared objects (.so):
# 1) shared_library, which is just bundling together many dependent libraries
# into a link line.
# 2) loadable_module, which is generating a module intended for dlopen().
#
# They differ only slightly:
# In the former case, we want to package all dependent code into the .so.
# In the latter case, we want to package just the API exposed by the
# outermost module.
# This means shared_library uses --whole-archive, while loadable_module doesn't.
# (Note that --whole-archive is incompatible with the --start-group used in
# normal linking.)
# Other shared-object link notes:
# - Set SONAME to the library filename so our binaries don't reference
# the local, absolute paths used on the link command-line.
quiet_cmd_solink = SOLINK($(TOOLSET)) $@
cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--whole-archive $(LD_INPUTS) -Wl,--no-whole-archive $(LIBS)
quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@
cmd_solink_module = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -Wl,-soname=$(@F) -o $@ -Wl,--start-group $(filter-out FORCE_DO_CMD, $^) -Wl,--end-group $(LIBS)
# Define an escape_quotes function to escape single quotes.
# This allows us to handle quotes properly as long as we always use
# use single quotes and escape_quotes.
escape_quotes = $(subst ','\'',$(1))
# This comment is here just to include a ' to unconfuse syntax highlighting.
# Define an escape_vars function to escape '$' variable syntax.
# This allows us to read/write command lines with shell variables (e.g.
# $LD_LIBRARY_PATH), without triggering make substitution.
escape_vars = $(subst $$,$$$$,$(1))
# Helper that expands to a shell command to echo a string exactly as it is in
# make. This uses printf instead of echo because printf's behaviour with respect
# to escape sequences is more portable than echo's across different shells
# (e.g., dash, bash).
exact_echo = printf '%s\n' '$(call escape_quotes,$(1))'
# Helper to compare the command we're about to run against the command
# we logged the last time we ran the command. Produces an empty
# string (false) when the commands match.
# Tricky point: Make has no string-equality test function.
# The kernel uses the following, but it seems like it would have false
# positives, where one string reordered its arguments.
# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \
# $(filter-out $(cmd_$@), $(cmd_$(1))))
# We instead substitute each for the empty string into the other, and
# say they're equal if both substitutions produce the empty string.
# .d files contain ? instead of spaces, take that into account.
command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\
$(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1))))
# Helper that is non-empty when a prerequisite changes.
# Normally make does this implicitly, but we force rules to always run
# so we can check their command lines.
# $? -- new prerequisites
# $| -- order-only dependencies
prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?))
# Helper that executes all postbuilds, and deletes the output file when done
# if any of the postbuilds failed.
define do_postbuilds
@E=0;\
for p in $(POSTBUILDS); do\
eval $$p;\
F=$$?;\
if [ $$F -ne 0 ]; then\
E=$$F;\
fi;\
done;\
if [ $$E -ne 0 ]; then\
rm -rf "$@";\
exit $$E;\
fi
endef
# do_cmd: run a command via the above cmd_foo names, if necessary.
# Should always run for a given target to handle command-line changes.
# Second argument, if non-zero, makes it do asm/C/C++ dependency munging.
# Third argument, if non-zero, makes it do POSTBUILDS processing.
# Note: We intentionally do NOT call dirx for depfile, since it contains ? for
# spaces already and dirx strips the ? characters.
define do_cmd
$(if $(or $(command_changed),$(prereq_changed)),
@$(call exact_echo, $($(quiet)cmd_$(1)))
@mkdir -p "$(call dirx,$@)" "$(dir $(depfile))"
$(if $(findstring flock,$(word 1,$(cmd_$1))),
@$(cmd_$(1))
@echo " $(quiet_cmd_$(1)): Finished",
@$(cmd_$(1))
)
@$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile)
@$(if $(2),$(fixup_dep))
$(if $(and $(3), $(POSTBUILDS)),
$(call do_postbuilds)
)
)
endef
# Declare the "all" target first so it is the default,
# even though we don't have the deps yet.
.PHONY: all
all:
# make looks for ways to re-generate included makefiles, but in our case, we
# don't have a direct way. Explicitly telling make that it has nothing to do
# for them makes it go faster.
%.d: ;
# Use FORCE_DO_CMD to force a target to run. Should be coupled with
# do_cmd.
.PHONY: FORCE_DO_CMD
FORCE_DO_CMD:
TOOLSET := target
# Suffix rules, putting all outputs into $(obj).
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
# Try building from generated source, too.
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD
@$(call do_cmd,cxx,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD
@$(call do_cmd,cc,1)
$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD
@$(call do_cmd,cc,1)
ifeq ($(strip $(foreach prefix,$(NO_LOAD),\
$(findstring $(join ^,$(prefix)),\
$(join ^,bson.target.mk)))),)
include bson.target.mk
endif
quiet_cmd_regen_makefile = ACTION Regenerating $@
cmd_regen_makefile = /usr/lib/nodejs/npm/node_modules/node-gyp/gyp/gyp -fmake --ignore-environment "--toplevel-dir=." -I/home/madateam/RNC/node_modules/mongoose/node_modules/mongodb/node_modules/bson/build/config.gypi -I/usr/lib/nodejs/npm/node_modules/node-gyp/addon.gypi -I/home/madateam/.node-gyp/0.8.23/common.gypi "--depth=." "-Goutput_dir=." "--generator-output=build" "-Dlibrary=shared_library" "-Dvisibility=default" "-Dnode_root_dir=/home/madateam/.node-gyp/0.8.23" "-Dmodule_root_dir=/home/madateam/RNC/node_modules/mongoose/node_modules/mongodb/node_modules/bson" binding.gyp
Makefile: $(srcdir)/../../../../../../../../../usr/lib/nodejs/npm/node_modules/node-gyp/addon.gypi $(srcdir)/../../../../../../../.node-gyp/0.8.23/common.gypi $(srcdir)/build/config.gypi $(srcdir)/binding.gyp
$(call do_cmd,regen_makefile)
# "all" is a concatenation of the "all" targets from all the included
# sub-makefiles. This is just here to clarify.
all:
# Add in dependency-tracking rules. $(all_deps) is the list of every single
# target in our tree. Only consider the ones with .d (dependency) info:
d_files := $(wildcard $(foreach f,$(all_deps),$(depsdir)/$(f).d))
ifneq ($(d_files),)
include $(d_files)
endif
|
gpl-3.0
|
AlienCowEatCake/ImageViewer
|
src/ThirdParty/highway/highway-0.15.0/hwy/targets.h
|
9864
|
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef HIGHWAY_HWY_TARGETS_H_
#define HIGHWAY_HWY_TARGETS_H_
#include <vector>
// For SIMD module implementations and their callers. Defines which targets to
// generate and call.
#include "hwy/base.h"
#include "hwy/detect_targets.h"
namespace hwy {
// Returns (cached) bitfield of enabled targets that are supported on this CPU.
// Implemented in targets.cc; unconditionally compiled to support the use case
// of binary-only distributions. The HWY_SUPPORTED_TARGETS wrapper may allow
// eliding calls to this function.
uint32_t SupportedTargets();
// Evaluates to a function call, or literal if there is a single target.
#if (HWY_TARGETS & (HWY_TARGETS - 1)) == 0
#define HWY_SUPPORTED_TARGETS HWY_TARGETS
#else
#define HWY_SUPPORTED_TARGETS hwy::SupportedTargets()
#endif
// Disable from runtime dispatch the mask of compiled in targets. Targets that
// were not enabled at compile time are ignored. This function is useful to
// disable a target supported by the CPU that is known to have bugs or when a
// lower target is desired. For this reason, attempts to disable targets which
// are in HWY_ENABLED_BASELINE have no effect so SupportedTargets() always
// returns at least the baseline target.
void DisableTargets(uint32_t disabled_targets);
// Set the mock mask of CPU supported targets instead of the actual CPU
// supported targets computed in SupportedTargets(). The return value of
// SupportedTargets() will still be affected by the DisableTargets() mask
// regardless of this mock, to prevent accidentally adding targets that are
// known to be buggy in the current CPU. Call with a mask of 0 to disable the
// mock and use the actual CPU supported targets instead.
void SetSupportedTargetsForTest(uint32_t targets);
// Returns whether the SupportedTargets() function was called since the last
// SetSupportedTargetsForTest() call.
bool SupportedTargetsCalledForTest();
// Return the list of targets in HWY_TARGETS supported by the CPU as a list of
// individual HWY_* target macros such as HWY_SCALAR or HWY_NEON. This list
// is affected by the current SetSupportedTargetsForTest() mock if any.
HWY_INLINE std::vector<uint32_t> SupportedAndGeneratedTargets() {
std::vector<uint32_t> ret;
for (uint32_t targets = SupportedTargets() & HWY_TARGETS; targets != 0;
targets = targets & (targets - 1)) {
uint32_t current_target = targets & ~(targets - 1);
ret.push_back(current_target);
}
return ret;
}
static inline HWY_MAYBE_UNUSED const char* TargetName(uint32_t target) {
switch (target) {
#if HWY_ARCH_X86
case HWY_SSSE3:
return "SSSE3";
case HWY_SSE4:
return "SSE4";
case HWY_AVX2:
return "AVX2";
case HWY_AVX3:
return "AVX3";
case HWY_AVX3_DL:
return "AVX3_DL";
#endif
#if HWY_ARCH_ARM
case HWY_SVE2:
return "SVE2";
case HWY_SVE:
return "SVE";
case HWY_NEON:
return "Neon";
#endif
#if HWY_ARCH_PPC
case HWY_PPC8:
return "Power8";
#endif
#if HWY_ARCH_WASM
case HWY_WASM:
return "Wasm";
#endif
#if HWY_ARCH_RVV
case HWY_RVV:
return "RVV";
#endif
case HWY_SCALAR:
return "Scalar";
default:
return "Unknown"; // must satisfy gtest IsValidParamName()
}
}
// The maximum number of dynamic targets on any architecture is defined by
// HWY_MAX_DYNAMIC_TARGETS and depends on the arch.
// For the ChosenTarget mask and index we use a different bit arrangement than
// in the HWY_TARGETS mask. Only the targets involved in the current
// architecture are used in this mask, and therefore only the least significant
// (HWY_MAX_DYNAMIC_TARGETS + 2) bits of the uint32_t mask are used. The least
// significant bit is set when the mask is not initialized, the next
// HWY_MAX_DYNAMIC_TARGETS more significant bits are a range of bits from the
// HWY_TARGETS or SupportedTargets() mask for the given architecture shifted to
// that position and the next more significant bit is used for the scalar
// target. Because of this we need to define equivalent values for HWY_TARGETS
// in this representation.
// This mask representation allows to use ctz() on this mask and obtain a small
// number that's used as an index of the table for dynamic dispatch. In this
// way the first entry is used when the mask is uninitialized, the following
// HWY_MAX_DYNAMIC_TARGETS are for dynamic dispatch and the last one is for
// scalar.
// The HWY_SCALAR bit in the ChosenTarget mask format.
#define HWY_CHOSEN_TARGET_MASK_SCALAR (1u << (HWY_MAX_DYNAMIC_TARGETS + 1))
// Converts from a HWY_TARGETS mask to a ChosenTarget mask format for the
// current architecture.
#define HWY_CHOSEN_TARGET_SHIFT(X) \
((((X) >> (HWY_HIGHEST_TARGET_BIT + 1 - HWY_MAX_DYNAMIC_TARGETS)) & \
((1u << HWY_MAX_DYNAMIC_TARGETS) - 1)) \
<< 1)
// The HWY_TARGETS mask in the ChosenTarget mask format.
#define HWY_CHOSEN_TARGET_MASK_TARGETS \
(HWY_CHOSEN_TARGET_SHIFT(HWY_TARGETS) | HWY_CHOSEN_TARGET_MASK_SCALAR | 1u)
#if HWY_ARCH_X86
// Maximum number of dynamic targets, changing this value is an ABI incompatible
// change
#define HWY_MAX_DYNAMIC_TARGETS 10
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_X86
// These must match the order in which the HWY_TARGETS are defined
// starting by the least significant (HWY_HIGHEST_TARGET_BIT + 1 -
// HWY_MAX_DYNAMIC_TARGETS) bit. This list must contain exactly
// HWY_MAX_DYNAMIC_TARGETS elements and does not include SCALAR. The first entry
// corresponds to the best target. Don't include a "," at the end of the list.
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_AVX3_DL(func_name), /* AVX3_DL */ \
HWY_CHOOSE_AVX3(func_name), /* AVX3 */ \
HWY_CHOOSE_AVX2(func_name), /* AVX2 */ \
nullptr, /* AVX */ \
HWY_CHOOSE_SSE4(func_name), /* SSE4 */ \
HWY_CHOOSE_SSSE3(func_name), /* SSSE3 */ \
nullptr, /* SSE3 */ \
nullptr /* SSE2 */
#elif HWY_ARCH_ARM
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 4
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_ARM
#define HWY_CHOOSE_TARGET_LIST(func_name) \
HWY_CHOOSE_SVE2(func_name), /* SVE2 */ \
HWY_CHOOSE_SVE(func_name), /* SVE */ \
nullptr, /* reserved */ \
HWY_CHOOSE_NEON(func_name) /* NEON */
#elif HWY_ARCH_PPC
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 5
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_PPC
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_PPC8(func_name), /* PPC8 */ \
nullptr, /* VSX */ \
nullptr /* AltiVec */
#elif HWY_ARCH_WASM
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 4
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_WASM
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_WASM2(func_name), /* WASM2 */ \
HWY_CHOOSE_WASM(func_name) /* WASM */
#elif HWY_ARCH_RVV
// See HWY_ARCH_X86 above for details.
#define HWY_MAX_DYNAMIC_TARGETS 4
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_RVV
#define HWY_CHOOSE_TARGET_LIST(func_name) \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
nullptr, /* reserved */ \
HWY_CHOOSE_RVV(func_name) /* RVV */
#else
// Unknown architecture, will use HWY_SCALAR without dynamic dispatch, though
// still creating single-entry tables in HWY_EXPORT to ensure portability.
#define HWY_MAX_DYNAMIC_TARGETS 1
#define HWY_HIGHEST_TARGET_BIT HWY_HIGHEST_TARGET_BIT_SCALAR
#endif
struct ChosenTarget {
public:
// Update the ChosenTarget mask based on the current CPU supported
// targets.
void Update();
// Reset the ChosenTarget to the uninitialized state.
void DeInit() { mask_.store(1); }
// Whether the ChosenTarget was initialized. This is useful to know whether
// any HWY_DYNAMIC_DISPATCH function was called.
bool IsInitialized() const { return mask_.load() != 1; }
// Return the index in the dynamic dispatch table to be used by the current
// CPU. Note that this method must be in the header file so it uses the value
// of HWY_CHOSEN_TARGET_MASK_TARGETS defined in the translation unit that
// calls it, which may be different from others. This allows to only consider
// those targets that were actually compiled in this module.
size_t HWY_INLINE GetIndex() const {
return hwy::Num0BitsBelowLS1Bit_Nonzero32(mask_.load() &
HWY_CHOSEN_TARGET_MASK_TARGETS);
}
private:
// Initialized to 1 so GetChosenTargetIndex() returns 0.
std::atomic<uint32_t> mask_{1};
};
extern ChosenTarget chosen_target;
} // namespace hwy
#endif // HIGHWAY_HWY_TARGETS_H_
|
gpl-3.0
|
clbr/stk
|
src/tinygettext/dictionary.cpp
|
5378
|
// tinygettext - A gettext replacement that works directly on .po files
// Copyright (C) 2006 Ingo Ruhnke <grumbel@gmx.de>
//
// 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#include <assert.h>
#include "log_stream.hpp"
#include "dictionary.hpp"
namespace tinygettext {
Dictionary::Dictionary(const std::string& charset_) :
entries(),
ctxt_entries(),
charset(charset_),
plural_forms()
{
m_has_fallback = false;
}
Dictionary::~Dictionary()
{
}
std::string
Dictionary::get_charset() const
{
return charset;
}
void
Dictionary::set_plural_forms(const PluralForms& plural_forms_)
{
plural_forms = plural_forms_;
}
PluralForms
Dictionary::get_plural_forms() const
{
return plural_forms;
}
std::string
Dictionary::translate_plural(const std::string& msgid, const std::string& msgid_plural, int num)
{
return translate_plural(entries, msgid, msgid_plural, num);
}
std::string
Dictionary::translate_plural(const Entries& dict, const std::string& msgid, const std::string& msgid_plural, int count)
{
Entries::const_iterator i = dict.find(msgid);
const std::vector<std::string>& msgstrs = i->second;
if (i != dict.end())
{
unsigned int n = 0;
n = plural_forms.get_plural(count);
assert(/*n >= 0 &&*/ n < msgstrs.size());
if (!msgstrs[n].empty())
return msgstrs[n];
else
if (count == 1) // default to english rules
return msgid;
else
return msgid_plural;
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
//log_info << "Candidates: " << std::endl;
//for (i = dict.begin(); i != dict.end(); ++i)
// log_info << "'" << i->first << "'" << std::endl;
if (count == 1) // default to english rules
return msgid;
else
return msgid_plural;
}
}
std::string
Dictionary::translate(const std::string& msgid)
{
return translate(entries, msgid);
}
std::string
Dictionary::translate(const Entries& dict, const std::string& msgid)
{
Entries::const_iterator i = dict.find(msgid);
if (i != dict.end() && !i->second.empty())
{
return i->second[0];
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
if (m_has_fallback) return m_fallback->translate(msgid);
else return msgid;
}
}
std::string
Dictionary::translate_ctxt(const std::string& msgctxt, const std::string& msgid)
{
CtxtEntries::iterator i = ctxt_entries.find(msgctxt);
if (i != ctxt_entries.end())
{
return translate(i->second, msgid);
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
return msgid;
}
}
std::string
Dictionary::translate_ctxt_plural(const std::string& msgctxt,
const std::string& msgid, const std::string& msgidplural, int num)
{
CtxtEntries::iterator i = ctxt_entries.find(msgctxt);
if (i != ctxt_entries.end())
{
return translate_plural(i->second, msgid, msgidplural, num);
}
else
{
//log_info << "Couldn't translate: " << msgid << std::endl;
if (num != 1) // default to english
return msgidplural;
else
return msgid;
}
}
void
Dictionary::add_translation(const std::string& msgid, const std::string& ,
const std::vector<std::string>& msgstrs)
{
// Do we need msgid2 for anything? its after all supplied to the
// translate call, so we just throw it away here
entries[msgid] = msgstrs;
}
void
Dictionary::add_translation(const std::string& msgid, const std::string& msgstr)
{
std::vector<std::string>& vec = entries[msgid];
if (vec.empty())
{
vec.push_back(msgstr);
}
else
{
log_warning << "collision in add_translation: '"
<< msgid << "' -> '" << msgstr << "' vs '" << vec[0] << "'" << std::endl;
vec[0] = msgstr;
}
}
void
Dictionary::add_translation(const std::string& msgctxt,
const std::string& msgid, const std::string& msgid_plural,
const std::vector<std::string>& msgstrs)
{
std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid];
if (vec.empty())
{
vec = msgstrs;
}
else
{
log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\", \"" << msgid_plural << "\")" << std::endl;
vec = msgstrs;
}
}
void
Dictionary::add_translation(const std::string& msgctxt, const std::string& msgid, const std::string& msgstr)
{
std::vector<std::string>& vec = ctxt_entries[msgctxt][msgid];
if (vec.empty())
{
vec.push_back(msgstr);
}
else
{
log_warning << "collision in add_translation(\"" << msgctxt << "\", \"" << msgid << "\")" << std::endl;
vec[0] = msgstr;
}
}
} // namespace tinygettext
/* EOF */
|
gpl-3.0
|
jkadlec/knot-dns-zoneapi
|
tests/query_module.c
|
2585
|
/* Copyright (C) 2014 CZ.NIC, z.s.p.o. <knot-dns@labs.nic.cz>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <tap/basic.h>
#include <string.h>
#include <stdlib.h>
#include "libknot/internal/mempattern.h"
#include "libknot/internal/mempool.h"
#include "libknot/errcode.h"
#include "knot/nameserver/query_module.h"
#include "libknot/packet/pkt.h"
/* Universal processing stage. */
int state_visit(int state, knot_pkt_t *pkt, struct query_data *qdata, void *ctx)
{
/* Visit current state */
bool *state_map = ctx;
state_map[state] = true;
return state + 1;
}
int main(int argc, char *argv[])
{
plan(4);
/* Create processing context. */
mm_ctx_t mm;
mm_ctx_mempool(&mm, MM_DEFAULT_BLKSIZE);
/* Create a map of expected steps. */
bool state_map[QUERY_PLAN_STAGES] = { false };
/* Prepare query plan. */
struct query_plan *plan = query_plan_create(&mm);
ok(plan != NULL, "query_plan: create");
/* Register all stage visits. */
int ret = KNOT_EOK;
for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) {
ret = query_plan_step(plan, stage, state_visit, state_map);
if (ret != KNOT_EOK) {
break;
}
}
ok(ret == KNOT_EOK, "query_plan: planned all steps");
/* Execute the plan. */
int state = 0, next_state = 0;
for (unsigned stage = QPLAN_BEGIN; stage < QUERY_PLAN_STAGES; ++stage) {
struct query_step *step = NULL;
WALK_LIST(step, plan->stage[stage]) {
next_state = step->process(state, NULL, NULL, step->ctx);
if (next_state != state + 1) {
break;
}
state = next_state;
}
}
ok(state == QUERY_PLAN_STAGES, "query_plan: executed all steps");
/* Verify if all steps executed their callback. */
for (state = 0; state < QUERY_PLAN_STAGES; ++state) {
if (state_map[state] == false) {
break;
}
}
ok(state == QUERY_PLAN_STAGES, "query_plan: executed all callbacks");
/* Free the query plan. */
query_plan_free(plan);
/* Cleanup. */
mp_delete((struct mempool *)mm.ctx);
return 0;
}
|
gpl-3.0
|
doronic/llib
|
src/tpm/mgr/gtpm_mgr.c
|
5773
|
/*
* gtpm-mgr
*
* Version 1.00
* Copyright (C) 2012-2014 Nicolas Provost dev AT doronic DOT fr
*
* 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 <gtk/gtk.h>
#include "llib_tpm.h"
#include "llib_opt.h"
#include "llib_print.h"
#include "llib_gtk.h"
#include "gtpm_mgr.h"
#include "gtpm_ui.h"
#include "gtpm_tpm.h"
#include "gtpm_uio.h"
static void gtpm_mgr_reset_vars(gtpm_config_t* gmgr)
{
llib_data_free(&gmgr->args.output);
llib_data_free(&gmgr->args.data);
llib_data_free(&gmgr->args.data2);
llib_data_free(&gmgr->args.encdata);
gmgr->args.set = 0;
llib_tpm_keystore_release_one_shot_key(gmgr->args.keystore);
}
/* run a command from the label of the clicked item */
void gtpm_mgr_run (gtpm_config_t* gmgr, const char* label)
{
lbool res;
const struct gtpm_menu_action_t* entry = >pm_tpm_menu_entries[0];
/* find the command from the label */
while (entry && entry->label && entry->job)
{
if (llib_str_equ(entry->label, label,0))
break;
entry++;
}
if (!entry || !entry->label || !entry->job)
{
gmgr->tpm.last_error = LLIB_TPM_ERROR_UNIMPLEMENTED;
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
llib_print_f(2, "[gtpm-mgr] unknown command label '%s'\n", label);
return;
}
/* get descriptor */
gmgr->args.desc = llib_tpm_find_descriptor (entry->job);
if (!gmgr->args.desc)
{
gmgr->tpm.last_error = LLIB_TPM_ERROR_UNIMPLEMENTED;
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
llib_print_f(2, "[gtpm-mgr] unknown descriptor '%s'\n",
gmgr->args.desc);
return;
}
/* set standard output if no other choice */
if ((gmgr->args.desc->in & LLIB_TPM_FOUTPUT) &&
!gmgr->args.cargs->output &&
!(gmgr->args.desc->sin & LLIB_TPM_FSOUTPUTNODEF))
{
gmgr->args.output = llib_data_create_text_buffer();
if (!gmgr->args.output)
{
llib_tpm_uio_printf (&gmgr->args, LLIB_TPM_UIO_ERR,
"unable to open standard output\n");
return;
}
gmgr->args.set |= LLIB_TPM_FOUTPUT;
}
/* run the command */
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_CIRCLE);
llib_gtku_process_signals ();
if (llib_tpm_run (&gmgr->tpm, entry->job, &gmgr->args, &res) && res)
{
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
llib_tpm_keystore_add_one_shot_key (gmgr->args.keystore);
if (gmgr->args.output &&
(gmgr->args.output->type == LLIB_DATA_TYPE_BUFFER) &&
(llib_buffer_type(&gmgr->args.output->data.buffer)
== LLIB_BUFFER_TEXT))
{
gtpmuio_output_text (&gmgr->args, "command result",
&gmgr->args.output->data.buffer);
}
}
else
{
llib_gtku_set_cursor (GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
llib_tpm_uio_error (&gmgr->args, "Unable to run command");
}
gtpm_mgr_reset_vars(gmgr);
llib_gtku_set_cursor(GTK_WIDGET(gmgr->ui.gWindow), GDK_ARROW);
}
static void gtpm_mgr_clean(gtpm_config_t* gmgr) {
llib_tpm_free(&gmgr->tpm);
llib_tpm_store_free(gmgr->args.store);
llib_tpm_keystore_free(gmgr->args.keystore);
llib_tpm_uio_free(&gmgr->uio);
}
int main(int argc, char* argv[])
{
gtpm_config_t gmgr;
int retcode = EXIT_FAILURE;
char c;
char* arg = NULL;
char* devpath = NULL;
llib_mem_zero(&gmgr, sizeof(gtpm_config_t));
gmgr.args.cargs = &gmgr.cargs;
gmgr.args.store = gmgr.cargs.store = &gmgr.cargs.st.store;
llib_tpm_key_init(&gmgr.cargs.st.store_key);
llib_tpm_store_init(gmgr.args.store, &gmgr.tpm, NULL);
gmgr.cargs.st.store.key = &gmgr.cargs.st.store_key;
gmgr.args.uio = &gmgr.uio;
gmgr.cargs.st.ui = &gmgr.ui;
gmgr.args.tpm = &gmgr.tpm;
gmgr.args.keystore = &gmgr.cargs.st.keystore;
gmgr.args.o = gmgr.cargs.o = &gmgr.cargs.st.o;
llib_tpm_store_object_init(gmgr.args.o, NULL, NULL);
gtpmuio_init(&gmgr.uio, &gmgr.args);
llib_tpm_keystore_init(gmgr.args.keystore);
llib_print_f(1, "gtpm-mgr v" VERSION "\n");
llib_print_f(1, "usage: [-dtpm|store|all (debug)] [-v (verbose)] "
"[-tTPM_DEV_PATH (default is /dev/tpm0)]\n");
while ((c = llib_opt_get_short(argc, argv, "vd::t::", &arg)) != -1)
{
switch (c)
{
case 'v':
gmgr.args.verbose = TRUE;
break;
case 'd':
if (llib_str_equ(arg, "all", 0) ||
llib_str_equ(arg, "store", 0))
{
gmgr.args.debug = TRUE;
gmgr.args.store->debug = TRUE;
}
if (llib_str_equ(arg, "all", 0) ||
llib_str_equ(arg, "tpm",0))
gmgr.tpm.debug = TRUE;
break;
case 't':
if (!arg)
{
llib_print_f(2, "[gtpm-mgr] FATAL: missing TPM device path\n");
return EXIT_FAILURE;
}
devpath = llib_str_dup(arg);
llib_print_f(2, "[gtpm-mgr] using TPM at %s\n", arg);
break;
}
llib_str_release(&arg);
}
gtk_init(&argc, &argv);
if (!gtpm_ui_build(&gmgr))
{
llib_print_f(2, "[gtpm-mgr] FATAL: unable to build graphical "
"interface, aborting\n");
}
else
{
if (!llib_tpm_init(&gmgr.tpm, devpath, 30, gmgr.tpm.debug))
llib_tpm_uio_error(&gmgr.args, "TPM initialization error");
else
{
gtk_widget_show_all(GTK_WIDGET(gmgr.ui.gWindow));
gtk_main();
retcode = EXIT_SUCCESS;
}
}
llib_mem_free(devpath);
gtpm_mgr_clean(&gmgr);
return retcode;
}
|
gpl-3.0
|
akraievoy/holonet
|
src/main/java/algores/holonet/core/events/EventNetLookup.java
|
3225
|
/*
Copyright 2011 Anton Kraievoy akraievoy@gmail.com
This file is part of Holonet.
Holonet 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.
Holonet is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty
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 Holonet. If not, see <http://www.gnu.org/licenses/>.
*/
package algores.holonet.core.events;
import algores.holonet.core.CommunicationException;
import algores.holonet.core.Network;
import algores.holonet.core.Node;
import algores.holonet.core.RequestPair;
import algores.holonet.core.api.Address;
import algores.holonet.core.api.Key;
import algores.holonet.core.api.tier1.delivery.LookupService;
import com.google.common.base.Optional;
import org.akraievoy.cnet.gen.vo.EntropySource;
import java.util.Collection;
/**
* Lookup entry event.
*/
public class EventNetLookup extends Event<EventNetLookup> {
protected int retries = 1;
public Result executeInternal(final Network network, final EntropySource eSource) {
Result aggregateResult = Result.PASSIVE;
for (int sequentialIndex = 0; sequentialIndex < retries; sequentialIndex++) {
Optional<RequestPair> optRequest =
network.generateRequestPair(eSource);
if (!optRequest.isPresent()) {
if (sequentialIndex > 0) {
throw new IllegalStateException(
"request model became empty amid request generation streak?"
);
}
break;
}
RequestPair request = optRequest.get();
Collection<Key> serverKeys =
request.server.getServices().getStorage().getKeys();
final Key mapping =
serverKeys.isEmpty() ?
// we may also pull other keys from the range, not only the greatest one
request.server.getServices().getRouting().ownRoute().getRange().getRKey().prev() :
eSource.randomElement(serverKeys);
final LookupService lookupSvc =
request.client.getServices().getLookup();
final Address address;
try {
address = lookupSvc.lookup(
mapping.getKey(), true, LookupService.Mode.GET,
Optional.of(request.server.getAddress())
);
} catch (CommunicationException e) {
if (!aggregateResult.equals(Result.FAILURE)) {
aggregateResult = handleEventFailure(e, null);
}
continue;
}
final Node lookupResult = network.getEnv().getNode(address);
if (
!lookupResult.equals(request.server)
) {
network.getInterceptor().reportInconsistentLookup(LookupService.Mode.GET);
}
aggregateResult = Result.SUCCESS;
}
return aggregateResult;
}
public void setRetries(int retryCount) {
this.retries = retryCount;
}
public EventNetLookup withRetries(int retryCount) {
setRetries(retryCount);
return this;
}
}
|
gpl-3.0
|
NishantDesai1306/lost-and-found
|
server/api/upload/upload.controller.js
|
1066
|
var path = require('path');
var Q = require('q');
var fs = require('fs');
var mv = require('mv');
var Upload = require('./upload.model');
exports.upload = function (req, res) {
var tmpPath = req.files[0].path;
var newFileName = Math.random().toString(36).substring(7)+path.extname(tmpPath);
var targetPath = path.resolve(process.env.UPLOAD_PATH, newFileName);
var defer = Q.defer();
mv(tmpPath, targetPath, function (err) {
if (err) {
return nextIteration.reject(err);
}
targetPath = targetPath.substring(targetPath.indexOf('upload'));
Upload.createUpload(targetPath).then(function(upload) {
defer.resolve(upload);
}, function(err) {
defer.reject(err);
});
});
defer.promise.then(function (upload) {
res.json({
status: true,
data: upload._id
});
}, function(err) {
console.log(err);
res.json({
status: false,
reason: err.toString()
});
});
};
|
gpl-3.0
|
elektroll/etaimp
|
libgimp/gimplayer_pdb.c
|
33949
|
/* LIBGIMP - The GIMP Library
* Copyright (C) 1995-2003 Peter Mattis and Spencer Kimball
*
* gimplayer_pdb.c
*
* This library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library. If not, see
* <http://www.gnu.org/licenses/>.
*/
/* NOTE: This file is auto-generated by pdbgen.pl */
#include "config.h"
#include "gimp.h"
/**
* SECTION: gimplayer
* @title: gimplayer
* @short_description: Operations on a single layer.
*
* Operations on a single layer.
**/
/**
* _gimp_layer_new:
* @image_ID: The image to which to add the layer.
* @width: The layer width.
* @height: The layer height.
* @type: The layer type.
* @name: The layer name.
* @opacity: The layer opacity.
* @mode: The layer combination mode.
*
* Create a new layer.
*
* This procedure creates a new layer with the specified width, height,
* and type. Name, opacity, and mode are also supplied parameters. The
* new layer still needs to be added to the image, as this is not
* automatic. Add the new layer with the gimp_image_insert_layer()
* command. Other attributes such as layer mask modes, and offsets
* should be set with explicit procedure calls.
*
* Returns: The newly created layer.
**/
gint32
_gimp_layer_new (gint32 image_ID,
gint width,
gint height,
GimpImageType type,
const gchar *name,
gdouble opacity,
GimpLayerModeEffects mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_INT32, width,
GIMP_PDB_INT32, height,
GIMP_PDB_INT32, type,
GIMP_PDB_STRING, name,
GIMP_PDB_FLOAT, opacity,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_new_from_visible:
* @image_ID: The source image from where the content is copied.
* @dest_image_ID: The destination image to which to add the layer.
* @name: The layer name.
*
* Create a new layer from what is visible in an image.
*
* This procedure creates a new layer from what is visible in the given
* image. The new layer still needs to be added to the destination
* image, as this is not automatic. Add the new layer with the
* gimp_image_insert_layer() command. Other attributes such as layer
* mask modes, and offsets should be set with explicit procedure calls.
*
* Returns: The newly created layer.
*
* Since: GIMP 2.6
**/
gint32
gimp_layer_new_from_visible (gint32 image_ID,
gint32 dest_image_ID,
const gchar *name)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new-from-visible",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_IMAGE, dest_image_ID,
GIMP_PDB_STRING, name,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_new_from_drawable:
* @drawable_ID: The source drawable from where the new layer is copied.
* @dest_image_ID: The destination image to which to add the layer.
*
* Create a new layer by copying an existing drawable.
*
* This procedure creates a new layer as a copy of the specified
* drawable. The new layer still needs to be added to the image, as
* this is not automatic. Add the new layer with the
* gimp_image_insert_layer() command. Other attributes such as layer
* mask modes, and offsets should be set with explicit procedure calls.
*
* Returns: The newly copied layer.
**/
gint32
gimp_layer_new_from_drawable (gint32 drawable_ID,
gint32 dest_image_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_copy_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-new-from-drawable",
&nreturn_vals,
GIMP_PDB_DRAWABLE, drawable_ID,
GIMP_PDB_IMAGE, dest_image_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_copy_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_copy_ID;
}
/**
* gimp_layer_group_new:
* @image_ID: The image to which to add the layer group.
*
* Create a new layer group.
*
* This procedure creates a new layer group. Attributes such as layer
* mode and opacity should be set with explicit procedure calls. Add
* the new layer group (which is a kind of layer) with the
* gimp_image_insert_layer() command.
*
* Returns: The newly created layer group.
*
* Since: GIMP 2.8
**/
gint32
gimp_layer_group_new (gint32 image_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_group_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-group-new",
&nreturn_vals,
GIMP_PDB_IMAGE, image_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_group_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_group_ID;
}
/**
* _gimp_layer_copy:
* @layer_ID: The layer to copy.
* @add_alpha: Add an alpha channel to the copied layer.
*
* Copy a layer.
*
* This procedure copies the specified layer and returns the copy. The
* newly copied layer is for use within the original layer's image. It
* should not be subsequently added to any other image. The copied
* layer can optionally have an added alpha channel. This is useful if
* the background layer in an image is being copied and added to the
* same image.
*
* Returns: The newly copied layer.
**/
gint32
_gimp_layer_copy (gint32 layer_ID,
gboolean add_alpha)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_copy_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-copy",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, add_alpha,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_copy_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_copy_ID;
}
/**
* gimp_layer_add_alpha:
* @layer_ID: The layer.
*
* Add an alpha channel to the layer if it doesn't already have one.
*
* This procedure adds an additional component to the specified layer
* if it does not already possess an alpha channel. An alpha channel
* makes it possible to clear and erase to transparency, instead of the
* background color. This transforms layers of type RGB to RGBA, GRAY
* to GRAYA, and INDEXED to INDEXEDA.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_add_alpha (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-add-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_flatten:
* @layer_ID: The layer.
*
* Remove the alpha channel from the layer if it has one.
*
* This procedure removes the alpha channel from a layer, blending all
* (partially) transparent pixels in the layer against the background
* color. This transforms layers of type RGBA to RGB, GRAYA to GRAY,
* and INDEXEDA to INDEXED.
*
* Returns: TRUE on success.
*
* Since: GIMP 2.4
**/
gboolean
gimp_layer_flatten (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-flatten",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_scale:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @local_origin: Use a local origin (as opposed to the image origin).
*
* Scale the layer using the default interpolation method.
*
* This procedure scales the layer so that its new width and height are
* equal to the supplied parameters. The 'local-origin' parameter
* specifies whether to scale from the center of the layer, or from the
* image origin. This operation only works if the layer has been added
* to an image. The interpolation method used can be set with
* gimp_context_set_interpolation().
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_scale (gint32 layer_ID,
gint new_width,
gint new_height,
gboolean local_origin)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-scale",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, local_origin,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_scale_full:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @local_origin: Use a local origin (as opposed to the image origin).
* @interpolation: Type of interpolation.
*
* Deprecated: Use gimp_layer_scale() instead.
*
* Returns: TRUE on success.
*
* Since: GIMP 2.6
**/
gboolean
gimp_layer_scale_full (gint32 layer_ID,
gint new_width,
gint new_height,
gboolean local_origin,
GimpInterpolationType interpolation)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-scale-full",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, local_origin,
GIMP_PDB_INT32, interpolation,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_resize:
* @layer_ID: The layer.
* @new_width: New layer width.
* @new_height: New layer height.
* @offx: x offset between upper left corner of old and new layers: (old - new).
* @offy: y offset between upper left corner of old and new layers: (old - new).
*
* Resize the layer to the specified extents.
*
* This procedure resizes the layer so that its new width and height
* are equal to the supplied parameters. Offsets are also provided
* which describe the position of the previous layer's content. This
* operation only works if the layer has been added to an image.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_resize (gint32 layer_ID,
gint new_width,
gint new_height,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-resize",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, new_width,
GIMP_PDB_INT32, new_height,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_resize_to_image_size:
* @layer_ID: The layer to resize.
*
* Resize a layer to the image size.
*
* This procedure resizes the layer so that it's new width and height
* are equal to the width and height of its image container.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_resize_to_image_size (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-resize-to-image-size",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_translate:
* @layer_ID: The layer.
* @offx: Offset in x direction.
* @offy: Offset in y direction.
*
* Translate the layer by the specified offsets.
*
* This procedure translates the layer by the amounts specified in the
* x and y arguments. These can be negative, and are considered offsets
* from the current position. This command only works if the layer has
* been added to an image. All additional layers contained in the image
* which have the linked flag set to TRUE w ill also be translated by
* the specified offsets.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_translate (gint32 layer_ID,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-translate",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_set_offsets:
* @layer_ID: The layer.
* @offx: Offset in x direction.
* @offy: Offset in y direction.
*
* Set the layer offsets.
*
* This procedure sets the offsets for the specified layer. The offsets
* are relative to the image origin and can be any values. This
* operation is valid only on layers which have been added to an image.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_offsets (gint32 layer_ID,
gint offx,
gint offy)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-offsets",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, offx,
GIMP_PDB_INT32, offy,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_create_mask:
* @layer_ID: The layer to which to add the mask.
* @mask_type: The type of mask.
*
* Create a layer mask for the specified layer.
*
* This procedure creates a layer mask for the specified layer. Layer
* masks serve as an additional alpha channel for a layer. A number of
* different types of masks are allowed for initialisation: completely
* white masks (which will leave the layer fully visible), completely
* black masks (which will give the layer complete transparency, the
* layer's already existing alpha channel (which will leave the layer
* fully visible, but which may be more useful than a white mask), the
* current selection or a grayscale copy of the layer. The layer mask
* still needs to be added to the layer. This can be done with a call
* to gimp_layer_add_mask().
*
* Returns: The newly created mask.
**/
gint32
gimp_layer_create_mask (gint32 layer_ID,
GimpAddMaskType mask_type)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 mask_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-create-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mask_type,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mask_ID = return_vals[1].data.d_layer_mask;
gimp_destroy_params (return_vals, nreturn_vals);
return mask_ID;
}
/**
* gimp_layer_get_mask:
* @layer_ID: The layer.
*
* Get the specified layer's mask if it exists.
*
* This procedure returns the specified layer's mask, or -1 if none
* exists.
*
* Returns: The layer mask.
**/
gint32
gimp_layer_get_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 mask_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-get-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mask_ID = return_vals[1].data.d_layer_mask;
gimp_destroy_params (return_vals, nreturn_vals);
return mask_ID;
}
/**
* gimp_layer_from_mask:
* @mask_ID: Mask for which to return the layer.
*
* Get the specified mask's layer.
*
* This procedure returns the specified mask's layer , or -1 if none
* exists.
*
* Returns: The mask's layer.
*
* Since: GIMP 2.2
**/
gint32
gimp_layer_from_mask (gint32 mask_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gint32 layer_ID = -1;
return_vals = gimp_run_procedure ("gimp-layer-from-mask",
&nreturn_vals,
GIMP_PDB_CHANNEL, mask_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
layer_ID = return_vals[1].data.d_layer;
gimp_destroy_params (return_vals, nreturn_vals);
return layer_ID;
}
/**
* gimp_layer_add_mask:
* @layer_ID: The layer to receive the mask.
* @mask_ID: The mask to add to the layer.
*
* Add a layer mask to the specified layer.
*
* This procedure adds a layer mask to the specified layer. Layer masks
* serve as an additional alpha channel for a layer. This procedure
* will fail if a number of prerequisites aren't met. The layer cannot
* already have a layer mask. The specified mask must exist and have
* the same dimensions as the layer. The layer must have been created
* for use with the specified image and the mask must have been created
* with the procedure 'gimp-layer-create-mask'.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_add_mask (gint32 layer_ID,
gint32 mask_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-add-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_CHANNEL, mask_ID,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_remove_mask:
* @layer_ID: The layer from which to remove mask.
* @mode: Removal mode.
*
* Remove the specified layer mask from the layer.
*
* This procedure removes the specified layer mask from the layer. If
* the mask doesn't exist, an error is returned.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_remove_mask (gint32 layer_ID,
GimpMaskApplyMode mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-remove-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_is_floating_sel:
* @layer_ID: The layer.
*
* Is the specified layer a floating selection?
*
* This procedure returns whether the layer is a floating selection.
* Floating selections are special cases of layers which are attached
* to a specific drawable.
*
* Returns: TRUE if the layer is a floating selection.
**/
gboolean
gimp_layer_is_floating_sel (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean is_floating_sel = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-is-floating-sel",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
is_floating_sel = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return is_floating_sel;
}
/**
* gimp_layer_get_lock_alpha:
* @layer_ID: The layer.
*
* Get the lock alpha channel setting of the specified layer.
*
* This procedure returns the specified layer's lock alpha channel
* setting.
*
* Returns: The layer's lock alpha channel setting.
**/
gboolean
gimp_layer_get_lock_alpha (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean lock_alpha = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-lock-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
lock_alpha = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return lock_alpha;
}
/**
* gimp_layer_set_lock_alpha:
* @layer_ID: The layer.
* @lock_alpha: The new layer's lock alpha channel setting.
*
* Set the lock alpha channel setting of the specified layer.
*
* This procedure sets the specified layer's lock alpha channel
* setting.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_lock_alpha (gint32 layer_ID,
gboolean lock_alpha)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-lock-alpha",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, lock_alpha,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_apply_mask:
* @layer_ID: The layer.
*
* Get the apply mask setting of the specified layer.
*
* This procedure returns the specified layer's apply mask setting. If
* the value is TRUE, then the layer mask for this layer is currently
* being composited with the layer's alpha channel.
*
* Returns: The layer's apply mask setting.
**/
gboolean
gimp_layer_get_apply_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean apply_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-apply-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
apply_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return apply_mask;
}
/**
* gimp_layer_set_apply_mask:
* @layer_ID: The layer.
* @apply_mask: The new layer's apply mask setting.
*
* Set the apply mask setting of the specified layer.
*
* This procedure sets the specified layer's apply mask setting. This
* controls whether the layer's mask is currently affecting the alpha
* channel. If there is no layer mask, this function will return an
* error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_apply_mask (gint32 layer_ID,
gboolean apply_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-apply-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, apply_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_show_mask:
* @layer_ID: The layer.
*
* Get the show mask setting of the specified layer.
*
* This procedure returns the specified layer's show mask setting. This
* controls whether the layer or its mask is visible. TRUE indicates
* that the mask should be visible. If the layer has no mask, then this
* function returns an error.
*
* Returns: The layer's show mask setting.
**/
gboolean
gimp_layer_get_show_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean show_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-show-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
show_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return show_mask;
}
/**
* gimp_layer_set_show_mask:
* @layer_ID: The layer.
* @show_mask: The new layer's show mask setting.
*
* Set the show mask setting of the specified layer.
*
* This procedure sets the specified layer's show mask setting. This
* controls whether the layer or its mask is visible. TRUE indicates
* that the mask should be visible. If there is no layer mask, this
* function will return an error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_show_mask (gint32 layer_ID,
gboolean show_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-show-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, show_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_edit_mask:
* @layer_ID: The layer.
*
* Get the edit mask setting of the specified layer.
*
* This procedure returns the specified layer's edit mask setting. If
* the value is TRUE, then the layer mask for this layer is currently
* active, and not the layer.
*
* Returns: The layer's edit mask setting.
**/
gboolean
gimp_layer_get_edit_mask (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean edit_mask = FALSE;
return_vals = gimp_run_procedure ("gimp-layer-get-edit-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
edit_mask = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return edit_mask;
}
/**
* gimp_layer_set_edit_mask:
* @layer_ID: The layer.
* @edit_mask: The new layer's edit mask setting.
*
* Set the edit mask setting of the specified layer.
*
* This procedure sets the specified layer's edit mask setting. This
* controls whether the layer or it's mask is currently active for
* editing. If the specified layer has no layer mask, then this
* procedure will return an error.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_edit_mask (gint32 layer_ID,
gboolean edit_mask)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-edit-mask",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, edit_mask,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_opacity:
* @layer_ID: The layer.
*
* Get the opacity of the specified layer.
*
* This procedure returns the specified layer's opacity.
*
* Returns: The layer opacity.
**/
gdouble
gimp_layer_get_opacity (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
gdouble opacity = 0.0;
return_vals = gimp_run_procedure ("gimp-layer-get-opacity",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
opacity = return_vals[1].data.d_float;
gimp_destroy_params (return_vals, nreturn_vals);
return opacity;
}
/**
* gimp_layer_set_opacity:
* @layer_ID: The layer.
* @opacity: The new layer opacity.
*
* Set the opacity of the specified layer.
*
* This procedure sets the specified layer's opacity.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_opacity (gint32 layer_ID,
gdouble opacity)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-opacity",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_FLOAT, opacity,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
/**
* gimp_layer_get_mode:
* @layer_ID: The layer.
*
* Get the combination mode of the specified layer.
*
* This procedure returns the specified layer's combination mode.
*
* Returns: The layer combination mode.
**/
GimpLayerModeEffects
gimp_layer_get_mode (gint32 layer_ID)
{
GimpParam *return_vals;
gint nreturn_vals;
GimpLayerModeEffects mode = 0;
return_vals = gimp_run_procedure ("gimp-layer-get-mode",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_END);
if (return_vals[0].data.d_status == GIMP_PDB_SUCCESS)
mode = return_vals[1].data.d_int32;
gimp_destroy_params (return_vals, nreturn_vals);
return mode;
}
/**
* gimp_layer_set_mode:
* @layer_ID: The layer.
* @mode: The new layer combination mode.
*
* Set the combination mode of the specified layer.
*
* This procedure sets the specified layer's combination mode.
*
* Returns: TRUE on success.
**/
gboolean
gimp_layer_set_mode (gint32 layer_ID,
GimpLayerModeEffects mode)
{
GimpParam *return_vals;
gint nreturn_vals;
gboolean success = TRUE;
return_vals = gimp_run_procedure ("gimp-layer-set-mode",
&nreturn_vals,
GIMP_PDB_LAYER, layer_ID,
GIMP_PDB_INT32, mode,
GIMP_PDB_END);
success = return_vals[0].data.d_status == GIMP_PDB_SUCCESS;
gimp_destroy_params (return_vals, nreturn_vals);
return success;
}
|
gpl-3.0
|
bthaase/DDWarden
|
html/lib/angular-abortable-requests/karma.conf.js
|
1741
|
// Karma configuration
// Generated on Thu Jul 24 2014 18:11:41 GMT-0700 (PDT)
module.exports = function(config) {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'bower_components/angular-resource/angular-resource.js',
'src/*.js',
'test/*.js'
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['progress'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: [],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false
});
};
|
gpl-3.0
|
hayssac/MeuTCC_Grupo1
|
MeuTCCApp/src/br/ifrn/meutcc/visao/ViewAlunoCandidatou.java
|
1286
|
package br.ifrn.meutcc.visao;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.ifrn.meutcc.modelo.Aluno;
import br.ifrn.meutcc.modelo.Orientador;
@WebServlet("/ViewAlunoCandidatou")
public class ViewAlunoCandidatou extends HttpServlet {
private static final long serialVersionUID = 1L;
public ViewAlunoCandidatou() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
int idCandidato = 2;
int idTema = -1;
try {
idTema = Integer.parseInt(id);
} catch (NumberFormatException nfex) {
nfex.printStackTrace();
}
Orientador a = new Orientador();
Orientador orientador = a.getOrientadorPorTema(idTema);
Aluno logic = new Aluno();
logic.registraObserver(orientador);
boolean aluno = logic.addCandidato(idTema, idCandidato);
request.setAttribute("candidatou", logic.getStatus());
request.setAttribute("aluno", aluno);
request.getRequestDispatcher("viewAluno.jsp").forward(request, response);
}
}
|
gpl-3.0
|
xil3f/podofo_iOS_sample
|
headers/include/podofo/base/podofo_config.h
|
1355
|
/* Template filled out by CMake */
/*
* *** THIS HEADER IS INCLUDED BY PdfCompilerCompat.h ***
* *** DO NOT INCLUDE DIRECTLY ***
*/
#ifndef _PDF_COMPILERCOMPAT_H
#error Please include PdfDefines.h instead
#endif
#define PODOFO_VERSION_MAJOR 0
#define PODOFO_VERSION_MINOR 9
#define PODOFO_VERSION_PATCH 0
/* PoDoFo configuration options */
#define PODOFO_MULTI_THREAD
/* somewhat platform-specific headers */
#define PODOFO_HAVE_STRINGS_H 1
#define PODOFO_HAVE_ARPA_INET_H 1
/* #undef PODOFO_HAVE_WINSOCK2_H */
/* #undef PODOFO_HAVE_MEM_H */
/* #undef PODOFO_HAVE_CTYPE_H */
/* Integer types - headers */
#define PODOFO_HAVE_STDINT_H 1
/* #undef PODOFO_HAVE_BASETSD_H */
#define PODOFO_HAVE_SYS_TYPES_H 1
/* Integer types - type names */
#define PDF_INT8_TYPENAME int8_t
#define PDF_INT16_TYPENAME int16_t
#define PDF_INT32_TYPENAME int32_t
#define PDF_INT64_TYPENAME int64_t
#define PDF_UINT8_TYPENAME uint8_t
#define PDF_UINT16_TYPENAME uint16_t
#define PDF_UINT32_TYPENAME uint32_t
#define PDF_UINT64_TYPENAME uint64_t
/* Endianness */
/* #undef TEST_BIG */
/* Libraries */
#define PODOFO_HAVE_JPEG_LIB
#define PODOFO_HAVE_PNG_LIB
#define PODOFO_HAVE_TIFF_LIB
#define PODOFO_HAVE_FONTCONFIG
#define PODOFO_HAVE_LUA
/* #undef PODOFO_HAVE_BOOST */
#define PODOFO_HAVE_CPPUNIT
/* Platform quirks */
#define PODOFO_JPEG_RUNTIME_COMPATIBLE
|
gpl-3.0
|
dmelian/imywa
|
source/test/frmx/concepto/form/frame1.php
|
4601
|
<?php
class test_frmx_concepto_form_frame1 extends bas_frmx_cardframe{
public function __construct($id, $tabs='', $grid=array('width'=>4,'height'=>4)) {
parent::__construct($id,$tabs,$grid);
//addComponent($tab, $x, $y, $width, $height, $field);
//construct FIELD ($id,$type,$name, $caption, $editable, $value,$visible). ##Nota: el campo type deberia quitarse.
$width=2;
$height = 1;
$this->SetMode("edit");
$this->tabs = array("Primera","Segunda","Tercera","Cuarta");
$this->query = new bas_sqlx_querydef();
$this->query->add("concepto","test");
$this->query->setkey(array('idconcepto'));
$this->query->order= array("idconcepto"=>"asc");
/*
idconcepto varchar(20) NOT NULL,
descripcion varchar(200) DEFAULT NULL,
caption varchar(30) NOT NULL, ## Nota: ¿Para que se usa este campo?
tipo enum('editable','fijo','calculado') NOT NULL DEFAULT 'editable',
*/
$this->query->addcol("idconcepto", "Concepto","concepto" ,true,'test');
$this->query->addcol("descripcion", "Descripción","concepto" ,false,'test',"upload");
$this->query->addcol("caption", "Caption","concepto" ,false,'test');
$this->query->addcol("tipo", "Tipo:","concepto" ,false,'test',"enum");
$this->setAttr("tipo","enum",array('editable'=>'editable','fijo'=>'fijo','calculado'=>'calculado'));
$this->setAttr('idconcepto','lookup','frmx_cardframe_form');
$this->addComponent("Primera", 1, 1, $width, $height,"idconcepto",'test');
$this->addComponent("Primera", 1, 2, $width, $height, "descripcion",'test');
$this->addComponent("Primera", 1, 3, $width, $height,"caption",'test');
$this->addComponent("Primera", 1, 4, $width, $height,"tipo",'test');
/*
formato enum('numérico','moneda','booleano','opción') NOT NULL DEFAULT 'numérico',
opcionstring varchar(250) DEFAULT NULL,
imagenstring varchar(80) DEFAULT NULL,
datomultiple int(11) NOT NULL DEFAULT '0',
*/
$this->query->addcol("formato", "Tipo:","concepto" ,false,'test',"enum");
$this->query->addcol("opcionstring", "Opciones","concepto" ,false,'test');
$this->query->addcol("imagenstring", "Nombre de la imagen","concepto" ,false,'test');
$this->query->addcol("datomultiple", "Dato multiple ","concepto" ,false,'test');
$this->setAttr("formato","enum",array('numérico'=>'numérico','moneda'=>'moneda','booleano'=>'booleano','opción'=>'opción'));
$this->addComponent("Segunda", 2, 1, $width, $height,"formato");
$this->addComponent("Segunda", 2, 2, $width, $height,"opcionstring");
$this->addComponent("Segunda", 3, 3, $width, $height,"imagenstring");
$this->addComponent("Segunda", 3, 4, $width, $height,"datomultiple");
/*
valor double DEFAULT NULL,
calcorden int(11) DEFAULT NULL,
distribuirvalor int(11) DEFAULT NULL,
sumarizeoper enum('media','suma','mínimo','máximo','moda') DEFAULT NULL,
*/
$this->query->addcol("valor", "Valor","concepto" ,false,'test');
$this->query->addcol("calcorden", "Cálculo del orden","concepto" ,false,'test');
$this->query->addcol("distribuirvalor", "Valor del distibuidor","concepto" ,false,'test');
$this->query->addcol("sumarizeoper", "aritmética","concepto" ,false,'test',"enum");
$this->setAttr("sumarizeoper","enum",array('media'=>'media','suma'=>'suma','mínimo'=>'mínimo','máximo'=>'máximo','moda'=>'moda'));
$this->addComponent("Tercera", 1, 1, 1, $height, "valor");
$this->addComponent("Tercera", 1, 2, $width, $height,"calcorden");
$this->addComponent("Tercera", 3, 1, $width, $height,"distribuirvalor");
$this->addComponent("Tercera", 3, 2, $width, $height,"sumarizeoper");
/*
fechavalor enum('fecha inicio periodo','fecha factura') DEFAULT NULL,
alerta int(11) NOT NULL DEFAULT '0',
alertimage int(11) NOT NULL DEFAULT '0',
alertmincount int(11) NOT NULL DEFAULT '1',
*/
$this->query->addcol("fechavalor", "Fecha","concepto" ,false,'test');
$this->query->addcol("alerta", "alerta","concepto" ,false,'test');
$this->query->addcol("alertimage", "alertimage","concepto" ,false,'test');
$this->query->addcol("alertmincount", "alertmincount","concepto" ,false,'test',"enum");
$this->setAttr("alertmincount","enum",array('fecha inicio periodo'=>'fecha inicio periodo','fecha factura'=>'fecha factura'));
$this->addComponent("Cuarta", 1, 1, 1, $height, "fechavalor");
$this->addComponent("Cuarta", 2, 1, $width, $height, "alerta");
$this->addComponent("Cuarta", 3, 1, $width, $height,"alertimage");
$this->addComponent("Cuarta", 1, 2, $width, $height,"alertmincount");
$this->setRecord();
}
}
/*
alertrepe int(11) DEFAULT NULL,
dynclass varchar(20) DEFAULT NULL,
*/
?>
|
gpl-3.0
|
idega/platform2
|
src/com/idega/development/presentation/IWDeveloper.java
|
5611
|
package com.idega.development.presentation;
import com.idega.idegaweb.IWBundle;
import com.idega.idegaweb.IWMainApplication;
import com.idega.presentation.IWContext;
import com.idega.presentation.Image;
import com.idega.presentation.Layer;
import com.idega.presentation.PresentationObject;
import com.idega.presentation.Table;
import com.idega.presentation.text.HorizontalRule;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.IFrame;
import com.idega.repository.data.RefactorClassRegistry;
/**
* Title: idega Framework
* Description:
* Copyright: Copyright (c) 2001
* Company: idega
* @author <a href=mailto:"tryggvi@idega.is">Tryggvi Larusson</a>
* @version 1.0
*/
public class IWDeveloper extends com.idega.presentation.app.IWApplication {
private static final String localizerParameter = "iw_localizer";
private static final String localeswitcherParameter = "iw_localeswitcher";
private static final String bundleCreatorParameter = "iw_bundlecreator";
private static final String bundleComponentManagerParameter = "iw_bundlecompmanager";
private static final String applicationPropertiesParameter = "iw_application_properties_setter";
private static final String bundlesPropertiesParameter = "iw_bundle_properties_setter";
public static final String actionParameter = "iw_developer_action";
public static final String dbPoolStatusViewerParameter = "iw_poolstatus_viewer";
public static final String updateManagerParameter = "iw_update_manager";
public static final String frameName = "iwdv_rightFrame";
public static final String PARAMETER_CLASS_NAME = "iwdv_class_name";
public IWDeveloper() {
super("idegaWeb Developer");
add(IWDeveloper.IWDevPage.class);
super.setResizable(true);
super.setScrollbar(true);
super.setScrolling(1, true);
super.setWidth(800);
super.setHeight(600);
//super.setOnLoad("moveTo(0,0);");
}
public static class IWDevPage extends com.idega.presentation.ui.Window {
public IWDevPage() {
this.setStatus(true);
}
private Table mainTable;
private Table objectTable;
private IFrame rightFrame;
private int count = 1;
public void main(IWContext iwc) throws Exception {
IWBundle iwbCore = getBundle(iwc);
if (iwc.isIE()) {
getParentPage().setBackgroundColor("#B0B29D");
}
Layer topLayer = new Layer(Layer.DIV);
topLayer.setZIndex(3);
topLayer.setPositionType(Layer.FIXED);
topLayer.setTopPosition(0);
topLayer.setLeftPosition(0);
topLayer.setBackgroundColor("#0E2456");
topLayer.setWidth(Table.HUNDRED_PERCENT);
topLayer.setHeight(25);
add(topLayer);
Table headerTable = new Table();
headerTable.setCellpadding(0);
headerTable.setCellspacing(0);
headerTable.setWidth(Table.HUNDRED_PERCENT);
headerTable.setAlignment(2,1,Table.HORIZONTAL_ALIGN_RIGHT);
topLayer.add(headerTable);
Image idegaweb = iwbCore.getImage("/editorwindow/idegaweb.gif","idegaWeb");
headerTable.add(idegaweb,1,1);
Text adminTitle = new Text("idegaWeb Developer");
adminTitle.setStyleAttribute("color:#FFFFFF;font-family:Arial,Helvetica,sans-serif;font-size:12px;font-weight:bold;margin-right:5px;");
headerTable.add(adminTitle,2,1);
Layer leftLayer = new Layer(Layer.DIV);
leftLayer.setZIndex(2);
leftLayer.setPositionType(Layer.FIXED);
leftLayer.setTopPosition(25);
leftLayer.setLeftPosition(0);
leftLayer.setPadding(5);
leftLayer.setBackgroundColor("#B0B29D");
leftLayer.setWidth(180);
leftLayer.setHeight(Table.HUNDRED_PERCENT);
add(leftLayer);
DeveloperList list = new DeveloperList();
leftLayer.add(list);
Layer rightLayer = new Layer(Layer.DIV);
rightLayer.setZIndex(1);
rightLayer.setPositionType(Layer.ABSOLUTE);
rightLayer.setTopPosition(25);
rightLayer.setPadding(5);
if (iwc.isIE()) {
rightLayer.setBackgroundColor("#FFFFFF");
rightLayer.setWidth(Table.HUNDRED_PERCENT);
rightLayer.setHeight(Table.HUNDRED_PERCENT);
rightLayer.setLeftPosition(180);
}
else {
rightLayer.setLeftPosition(190);
}
add(rightLayer);
if (iwc.isParameterSet(PARAMETER_CLASS_NAME)) {
String className = IWMainApplication.decryptClassName(iwc.getParameter(PARAMETER_CLASS_NAME));
PresentationObject obj = (PresentationObject) RefactorClassRegistry.getInstance().newInstance(className, this.getClass());
rightLayer.add(obj);
}
else {
rightLayer.add(new Localizer());
}
}
}
public static Table getTitleTable(String displayString, Image image) {
Table titleTable = new Table(1, 2);
titleTable.setCellpadding(0);
titleTable.setCellspacing(0);
titleTable.setWidth("100%");
Text headline = getText(displayString);
headline.setFontSize(Text.FONT_SIZE_14_HTML_4);
headline.setFontColor("#0E2456");
if (image != null) {
image.setHorizontalSpacing(5);
titleTable.add(image, 1, 1);
}
titleTable.add(headline, 1, 1);
titleTable.add(new HorizontalRule("100%", 2, "color: #FF9310", true), 1, 2);
return titleTable;
}
public static Table getTitleTable(String displayString) {
return getTitleTable(displayString, null);
}
public static Table getTitleTable(Class classToUse, Image image) {
return getTitleTable(classToUse.getName().substring(classToUse.getName().lastIndexOf(".") + 1), image);
}
public static Table getTitleTable(Class classToUse) {
return getTitleTable(classToUse, null);
}
public static Text getText(String text) {
Text T = new Text(text);
T.setBold();
T.setFontFace(Text.FONT_FACE_VERDANA);
T.setFontSize(Text.FONT_SIZE_10_HTML_2);
return T;
}
}
|
gpl-3.0
|
zpxocivuby/freetong_mobile_server
|
itaf-aggregator/itaf-ws-simulator/src/test/java/itaf/WsCartItemService/BzCollectionOrderDto.java
|
3557
|
package itaf.WsCartItemService;
import java.math.BigDecimal;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>bzCollectionOrderDto complex typeµÄ Java Àà¡£
*
* <p>ÒÔÏÂģʽƬ¶ÎÖ¸¶¨°üº¬ÔÚ´ËÀàÖеÄÔ¤ÆÚÄÚÈÝ¡£
*
* <pre>
* <complexType name="bzCollectionOrderDto">
* <complexContent>
* <extension base="{itaf.framework.ws.server.cart}operateDto">
* <sequence>
* <element name="bzDistributionOrderDto" type="{itaf.framework.ws.server.cart}bzDistributionOrderDto" minOccurs="0"/>
* <element name="receivableAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="actualAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* <element name="distributionAmount" type="{http://www.w3.org/2001/XMLSchema}decimal" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "bzCollectionOrderDto", propOrder = {
"bzDistributionOrderDto",
"receivableAmount",
"actualAmount",
"distributionAmount"
})
public class BzCollectionOrderDto
extends OperateDto
{
protected BzDistributionOrderDto bzDistributionOrderDto;
protected BigDecimal receivableAmount;
protected BigDecimal actualAmount;
protected BigDecimal distributionAmount;
/**
* »ñÈ¡bzDistributionOrderDtoÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BzDistributionOrderDto }
*
*/
public BzDistributionOrderDto getBzDistributionOrderDto() {
return bzDistributionOrderDto;
}
/**
* ÉèÖÃbzDistributionOrderDtoÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BzDistributionOrderDto }
*
*/
public void setBzDistributionOrderDto(BzDistributionOrderDto value) {
this.bzDistributionOrderDto = value;
}
/**
* »ñÈ¡receivableAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getReceivableAmount() {
return receivableAmount;
}
/**
* ÉèÖÃreceivableAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setReceivableAmount(BigDecimal value) {
this.receivableAmount = value;
}
/**
* »ñÈ¡actualAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getActualAmount() {
return actualAmount;
}
/**
* ÉèÖÃactualAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setActualAmount(BigDecimal value) {
this.actualAmount = value;
}
/**
* »ñÈ¡distributionAmountÊôÐÔµÄÖµ¡£
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getDistributionAmount() {
return distributionAmount;
}
/**
* ÉèÖÃdistributionAmountÊôÐÔµÄÖµ¡£
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setDistributionAmount(BigDecimal value) {
this.distributionAmount = value;
}
}
|
gpl-3.0
|
ffsdmad/af-web
|
cgi-bin/plugins2/doc_view_list.py
|
444
|
# -*- coding: utf8 -*-
SQL = """select SQL_CALC_FOUND_ROWS * FROM doc_view order by `name` asc limit %(offset)d,%(limit)d ;"""
FOUND_ROWS = True
ROOT = "doc_view_list"
ROOT_PREFIX = "<doc_view_edit />"
ROOT_POSTFIX= None
XSL_TEMPLATE = "data/af-web.xsl"
EVENT = None
WHERE = ()
PARAM = None
TITLE="Список видов документов"
MESSAGE="ошибка получения списка видов документов"
ORDER = None
|
gpl-3.0
|
philipstaffordwood/fabrica
|
analysis/bodyparts3d/db/README.md
|
139
|
Trying to figure out:
* Why two hierarchies?
* How do they differ?
* Do they share any entities?
Approach:
Make a XE db and have a look.
|
gpl-3.0
|
theScrabi/NewPipe
|
app/src/main/java/org/schabi/newpipe/util/AnimationUtils.java
|
20120
|
/*
* Copyright 2018 Mauricio Colli <mauriciocolli@outlook.com>
* AnimationUtils.java is part of NewPipe
*
* License: GPL-3.0+
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.schabi.newpipe.util;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ArgbEvaluator;
import android.animation.ValueAnimator;
import android.content.res.ColorStateList;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import androidx.annotation.ColorInt;
import androidx.annotation.FloatRange;
import androidx.core.view.ViewCompat;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import org.schabi.newpipe.MainActivity;
public final class AnimationUtils {
private static final String TAG = "AnimationUtils";
private static final boolean DEBUG = MainActivity.DEBUG;
private AnimationUtils() { }
public static void animateView(final View view, final boolean enterOrExit,
final long duration) {
animateView(view, Type.ALPHA, enterOrExit, duration, 0, null);
}
public static void animateView(final View view, final boolean enterOrExit,
final long duration, final long delay) {
animateView(view, Type.ALPHA, enterOrExit, duration, delay, null);
}
public static void animateView(final View view, final boolean enterOrExit, final long duration,
final long delay, final Runnable execOnEnd) {
animateView(view, Type.ALPHA, enterOrExit, duration, delay, execOnEnd);
}
public static void animateView(final View view, final Type animationType,
final boolean enterOrExit, final long duration) {
animateView(view, animationType, enterOrExit, duration, 0, null);
}
public static void animateView(final View view, final Type animationType,
final boolean enterOrExit, final long duration,
final long delay) {
animateView(view, animationType, enterOrExit, duration, delay, null);
}
/**
* Animate the view.
*
* @param view view that will be animated
* @param animationType {@link Type} of the animation
* @param enterOrExit true to enter, false to exit
* @param duration how long the animation will take, in milliseconds
* @param delay how long the animation will wait to start, in milliseconds
* @param execOnEnd runnable that will be executed when the animation ends
*/
public static void animateView(final View view, final Type animationType,
final boolean enterOrExit, final long duration,
final long delay, final Runnable execOnEnd) {
if (DEBUG) {
String id;
try {
id = view.getResources().getResourceEntryName(view.getId());
} catch (final Exception e) {
id = view.getId() + "";
}
final String msg = String.format("%8s → [%s:%s] [%s %s:%s] execOnEnd=%s", enterOrExit,
view.getClass().getSimpleName(), id, animationType, duration, delay, execOnEnd);
Log.d(TAG, "animateView()" + msg);
}
if (view.getVisibility() == View.VISIBLE && enterOrExit) {
if (DEBUG) {
Log.d(TAG, "animateView() view was already visible > view = [" + view + "]");
}
view.animate().setListener(null).cancel();
view.setVisibility(View.VISIBLE);
view.setAlpha(1f);
if (execOnEnd != null) {
execOnEnd.run();
}
return;
} else if ((view.getVisibility() == View.GONE || view.getVisibility() == View.INVISIBLE)
&& !enterOrExit) {
if (DEBUG) {
Log.d(TAG, "animateView() view was already gone > view = [" + view + "]");
}
view.animate().setListener(null).cancel();
view.setVisibility(View.GONE);
view.setAlpha(0f);
if (execOnEnd != null) {
execOnEnd.run();
}
return;
}
view.animate().setListener(null).cancel();
view.setVisibility(View.VISIBLE);
switch (animationType) {
case ALPHA:
animateAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case SCALE_AND_ALPHA:
animateScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case LIGHT_SCALE_AND_ALPHA:
animateLightScaleAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case SLIDE_AND_ALPHA:
animateSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
case LIGHT_SLIDE_AND_ALPHA:
animateLightSlideAndAlpha(view, enterOrExit, duration, delay, execOnEnd);
break;
}
}
/**
* Animate the background color of a view.
*
* @param view the view to animate
* @param duration the duration of the animation
* @param colorStart the background color to start with
* @param colorEnd the background color to end with
*/
public static void animateBackgroundColor(final View view, final long duration,
@ColorInt final int colorStart,
@ColorInt final int colorEnd) {
if (DEBUG) {
Log.d(TAG, "animateBackgroundColor() called with: "
+ "view = [" + view + "], duration = [" + duration + "], "
+ "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]");
}
final int[][] empty = {new int[0]};
final ValueAnimator viewPropertyAnimator = ValueAnimator
.ofObject(new ArgbEvaluator(), colorStart, colorEnd);
viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator());
viewPropertyAnimator.setDuration(duration);
viewPropertyAnimator.addUpdateListener(animation ->
ViewCompat.setBackgroundTintList(view,
new ColorStateList(empty, new int[]{(int) animation.getAnimatedValue()})));
viewPropertyAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
ViewCompat.setBackgroundTintList(view,
new ColorStateList(empty, new int[]{colorEnd}));
}
@Override
public void onAnimationCancel(final Animator animation) {
onAnimationEnd(animation);
}
});
viewPropertyAnimator.start();
}
/**
* Animate the text color of any view that extends {@link TextView} (Buttons, EditText...).
*
* @param view the text view to animate
* @param duration the duration of the animation
* @param colorStart the text color to start with
* @param colorEnd the text color to end with
*/
public static void animateTextColor(final TextView view, final long duration,
@ColorInt final int colorStart,
@ColorInt final int colorEnd) {
if (DEBUG) {
Log.d(TAG, "animateTextColor() called with: "
+ "view = [" + view + "], duration = [" + duration + "], "
+ "colorStart = [" + colorStart + "], colorEnd = [" + colorEnd + "]");
}
final ValueAnimator viewPropertyAnimator = ValueAnimator
.ofObject(new ArgbEvaluator(), colorStart, colorEnd);
viewPropertyAnimator.setInterpolator(new FastOutSlowInInterpolator());
viewPropertyAnimator.setDuration(duration);
viewPropertyAnimator.addUpdateListener(animation ->
view.setTextColor((int) animation.getAnimatedValue()));
viewPropertyAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setTextColor(colorEnd);
}
@Override
public void onAnimationCancel(final Animator animation) {
view.setTextColor(colorEnd);
}
});
viewPropertyAnimator.start();
}
public static ValueAnimator animateHeight(final View view, final long duration,
final int targetHeight) {
final int height = view.getHeight();
if (DEBUG) {
Log.d(TAG, "animateHeight: duration = [" + duration + "], "
+ "from " + height + " to → " + targetHeight + " in: " + view);
}
final ValueAnimator animator = ValueAnimator.ofFloat(height, targetHeight);
animator.setInterpolator(new FastOutSlowInInterpolator());
animator.setDuration(duration);
animator.addUpdateListener(animation -> {
final float value = (float) animation.getAnimatedValue();
view.getLayoutParams().height = (int) value;
view.requestLayout();
});
animator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.getLayoutParams().height = targetHeight;
view.requestLayout();
}
@Override
public void onAnimationCancel(final Animator animation) {
view.getLayoutParams().height = targetHeight;
view.requestLayout();
}
});
animator.start();
return animator;
}
public static void animateRotation(final View view, final long duration,
final int targetRotation) {
if (DEBUG) {
Log.d(TAG, "animateRotation: duration = [" + duration + "], "
+ "from " + view.getRotation() + " to → " + targetRotation + " in: " + view);
}
view.animate().setListener(null).cancel();
view.animate()
.rotation(targetRotation).setDuration(duration)
.setInterpolator(new FastOutSlowInInterpolator())
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(final Animator animation) {
view.setRotation(targetRotation);
}
@Override
public void onAnimationEnd(final Animator animation) {
view.setRotation(targetRotation);
}
}).start();
}
private static void animateAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(1f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.animate().setInterpolator(new FastOutSlowInInterpolator()).alpha(0f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
/*//////////////////////////////////////////////////////////////////////////
// Internals
//////////////////////////////////////////////////////////////////////////*/
private static void animateScaleAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setScaleX(.8f);
view.setScaleY(.8f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(1f).scaleX(1f).scaleY(1f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.setScaleX(1f);
view.setScaleY(1f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).scaleX(.8f).scaleY(.8f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
private static void animateLightScaleAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setAlpha(.5f);
view.setScaleX(.95f);
view.setScaleY(.95f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(1f).scaleX(1f).scaleY(1f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.setAlpha(1f);
view.setScaleX(1f);
view.setScaleY(1f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).scaleX(.95f).scaleY(.95f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
private static void animateSlideAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setTranslationY(-view.getHeight());
view.setAlpha(0f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.animate()
.setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).translationY(-view.getHeight())
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
private static void animateLightSlideAndAlpha(final View view, final boolean enterOrExit,
final long duration, final long delay,
final Runnable execOnEnd) {
if (enterOrExit) {
view.setTranslationY(-view.getHeight() / 2.0f);
view.setAlpha(0f);
view.animate()
.setInterpolator(new FastOutSlowInInterpolator()).alpha(1f).translationY(0)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
} else {
view.animate().setInterpolator(new FastOutSlowInInterpolator())
.alpha(0f).translationY(-view.getHeight() / 2.0f)
.setDuration(duration).setStartDelay(delay)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(final Animator animation) {
view.setVisibility(View.GONE);
if (execOnEnd != null) {
execOnEnd.run();
}
}
}).start();
}
}
public static void slideUp(final View view, final long duration, final long delay,
@FloatRange(from = 0.0f, to = 1.0f)
final float translationPercent) {
final int translationY = (int) (view.getResources().getDisplayMetrics().heightPixels
* (translationPercent));
view.animate().setListener(null).cancel();
view.setAlpha(0f);
view.setTranslationY(translationY);
view.setVisibility(View.VISIBLE);
view.animate()
.alpha(1f)
.translationY(0)
.setStartDelay(delay)
.setDuration(duration)
.setInterpolator(new FastOutSlowInInterpolator())
.start();
}
public enum Type {
ALPHA,
SCALE_AND_ALPHA, LIGHT_SCALE_AND_ALPHA,
SLIDE_AND_ALPHA, LIGHT_SLIDE_AND_ALPHA
}
}
|
gpl-3.0
|
Habu-Kagumba/dotfiles
|
README.markdown
|
119
|
My Dotfiles - Lasciate ogne speranza, voi ch'intrate
========
## TODO
- [ ] Improve `setup.sh` for easy installation.
|
gpl-3.0
|
david-0/disg
|
src/app/evaluation/evaluation.component.ts
|
638
|
import {Component, OnInit} from '@angular/core';
import {EvaluationService} from '../service/evaluation.service';
@Component({
selector: 'app-evaluation',
templateUrl: './evaluation.component.html',
styleUrls: ['./evaluation.component.css']
})
export class EvaluationComponent implements OnInit {
public result: number[];
private quadrantWith = 200;
constructor(public evaluationService: EvaluationService) {
}
ngOnInit() {
this.result = this.evaluationService.evaluate();
}
calc(points: number): number {
const value = 1 / 30 * (points - 10) * this.quadrantWith
return (value < 0) ? 0 : value;
}
}
|
gpl-3.0
|
jegoyalu/jariscms
|
modules/control_menu/styles/style.css
|
3639
|
#control-menu
{
position: fixed;
background-color: #E9F2F5;
border: solid 1px #d3d3d3;
display: flex;
justify-content: space-between;
align-items: center;
z-index: 100000
}
#control-menu *
{
font-size: 13px;
font-weight: bold;
}
#control-menu .user
{
display: block;
margin: 0 8px 0 0;
padding: 8px;
background-color: #235c96;
color: #fff;
}
#control-menu .right
{
display: flex;
justify-content: flex-end;
}
#control-menu .right a
{
width: 20px;
height: 18px;
display: block;
padding: 8px;
}
#control-menu .right a:hover
{
background-color: #D5E7ED;
}
#control-menu .about
{
background: transparent url(about.png) no-repeat center center;
}
#control-menu .help
{
background: transparent url(help.png) no-repeat center center;
}
#control-menu .logout
{
background: transparent url(logout.png) no-repeat center center;
}
#control-menu ul
{
display: flex;
justify-content: flex-start;
flex-grow: 1;
margin: 0;
padding: 0;
}
#control-menu ul li
{
display: block;
list-style: none;
margin: 0;
position: relative;
}
#control-menu ul li a
{
display: block;
padding: 8px;
cursor: pointer;
color: #00576d;
text-decoration: none;
}
#control-menu ul li a:hover
{
background-color: #D5E7ED;
}
#control-menu ul li ul
{
position: absolute;
left: 0;
bottom: 32px;
display: none;
background-color: #E9F2F5;
padding: 5px;
width: 200px;
border-top: solid 1px #d3d3d3;
border-left: solid 1px #d3d3d3;
border-right: solid 1px #d3d3d3;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
}
#control-menu ul li ul li
{
display: block;
margin: 0;
padding: 0;
}
#control-menu ul li ul li a
{
display: block;
border-bottom: dotted 1px #d3d3d3;
color: #00576d;
text-decoration: none;
}
#control-menu ul li ul li a:hover
{
background-color: #df7500;
color: #fff;
}
#control-menu .view
{
display: none;
}
#control-menu .view a
{
display: inline-block;
cursor: pointer;
width: 20px;
height: 20px;
padding: 5px 8px 5px 8px;
background: transparent url(options.png) no-repeat center center;
}
#control-menu-mobile
{
display: none;
position: fixed;
background-color: #E9F2F5;
z-index: 100000;
overflow: scroll;
padding: 10px;
box-sizing: border-box;
opacity: 0.9;
}
#control-menu-mobile a
{
color: #00576d;
}
#control-menu-mobile .close
{
text-align: right;
}
#control-menu-mobile .close a
{
font-weight: bold;
display: inline-block;
padding: 10px 10px 0 10px;
font-size: 24px;
cursor: pointer;
}
#control-menu-mobile ul
{
margin: 0;
padding: 0;
}
#control-menu-mobile ul li
{
list-style: none;
}
#control-menu-mobile > ul > li
{
margin-bottom: 15px;
}
#control-menu-mobile > ul > li > a
{
font-size: 24px;
margin-bottom: 10px;
}
#control-menu-mobile ul li a
{
display: block;
}
#control-menu-mobile ul ul li a
{
padding-left: 20px;
display: block;
padding: 7px;
border-bottom: dotted 1px #d3d3d3;
}
#control-menu-mobile ul ul li a:hover
{
background-color: #df7500;
color: #fff;
}
@media all and (max-width: 800px)
{
#control-menu ul
{
display: none;
}
#control-menu .view
{
display: block;
flex-grow: 1;
text-align: left;
}
}
|
gpl-3.0
|
imr/Electric8
|
com/sun/electric/tool/generator/layout/fill/FillGeneratorTool.java
|
32233
|
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: FillGeneratorTool.java
*
* Copyright (c) 2006 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.generator.layout.fill;
import com.sun.electric.database.geometry.EPoint;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Library;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.tool.Job;
import com.sun.electric.tool.JobException;
import com.sun.electric.tool.Tool;
import com.sun.electric.tool.generator.layout.Gallery;
import com.sun.electric.tool.generator.layout.LayoutLib;
import com.sun.electric.tool.generator.layout.TechType;
import java.lang.reflect.Constructor;
import java.util.*;
abstract class MetalFloorplanBase extends Floorplan
{
/** width Vdd wires */ public double vddWidth;
/** width Gnd wires */ public double gndWidth;
MetalFloorplanBase(double cellWidth, double cellHeight, boolean horiz)
{
super(cellWidth, cellHeight, horiz);
vddWidth = gndWidth = 0;
}
}
// ------------------------------ MetalFloorplanFlex ------------------------------
// Similar to Metalfloor but number of power/gnd lines is determined by cell size
class MetalFloorplanFlex extends MetalFloorplanBase {
public final double minWidth, space, vddReserve, gndReserve;
MetalFloorplanFlex(double cellWidth, double cellHeight,
double vddReserve, double gndReserve, double space,
double vddW, double gndW,
boolean horiz)
{
super(cellWidth, cellHeight, horiz);
this.vddWidth = vddW; //27;
this.gndWidth = gndW; //20;
this.space = space;
this.vddReserve = vddReserve;
this.gndReserve = gndReserve;
minWidth = vddReserve + gndReserve + 2*space + 2*gndWidth + 2*vddWidth;
}
}
// ------------------------------ MetalFloorplan ------------------------------
// Floor plan:
//
// half of Gnd reserved
// gggggggggggggggggggg
// wide space
// vvvvvvvvvvvvvvvvvvvv
// Vdd reserved
// vvvvvvvvvvvvvvvvvvvv
// wide space
// gggggggggggggggggggg
// half of Gnd reserved
class MetalFloorplan extends MetalFloorplanBase {
/** no gap between Vdd wires */ public final boolean mergedVdd;
/** if horizontal then y coordinate of top Vdd wire
* if vertical then x coordinate of right Vdd wire */
public final double vddCenter;
/** if horizontal then y coordinate of top Gnd wire
* if vertical then x coordinate of right Gnd wire */
public final double gndCenter;
public final double coverage;
private double roundDownOneLambda(double x) {
return Math.floor(x);
}
// Round metal widths down to multiples of 1 lambda resolution.
// Then metal center can be on 1/2 lambda grid without problems.
MetalFloorplan(double cellWidth, double cellHeight,
double vddReserve, double gndReserve,
double space, boolean horiz) {
super(cellWidth, cellHeight, horiz);
mergedVdd = vddReserve==0;
double cellSpace = horiz ? cellHeight : cellWidth;
double metalSpace = cellSpace - 2*space - vddReserve - gndReserve;
// gnd is always in two pieces
gndWidth = roundDownOneLambda(metalSpace / 4);
gndCenter = cellSpace/2 - gndReserve/2 - gndWidth/2;
// vdd may be one or two pieces
if (mergedVdd) {
vddWidth = gndWidth*2;
vddCenter = 0;
} else {
vddWidth = gndWidth;
vddCenter = vddReserve/2 + vddWidth/2;
}
// compute coverage statistics
double cellArea = cellWidth * cellHeight;
double strapLength = horiz ? cellWidth : cellHeight;
double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength;
double gndArea = 2 * gndWidth * strapLength;
coverage = (vddArea + gndArea)/cellArea;
}
// Save this code in case I need to replicate LoCo FillCell exactly
// MetalFloorplan(double cellWidth, double cellHeight,
// double vddReserve, double gndReserve,
// double space, boolean horiz) {
// super(cellWidth, cellHeight, horiz);
// mergedVdd = vddReserve==0;
// double cellSpace = horiz ? cellHeight : cellWidth;
// if (mergedVdd) {
// double w = cellSpace/2 - space - vddReserve;
// vddWidth = roundDownOneLambda(w);
// vddCenter = 0;
// } else {
// double w = (cellSpace/2 - space - vddReserve) / 2;
// vddWidth = roundDownOneLambda(w);
// vddCenter = vddReserve/2 + vddWidth/2;
// }
// double vddEdge = vddCenter + vddWidth/2;
// double w = cellSpace/2 - vddEdge - space - gndReserve/2;
// gndWidth = roundDownOneLambda(w);
// gndCenter = vddEdge + space + gndWidth/2;
//
// // compute coverage statistics
// double cellArea = cellWidth * cellHeight;
// double strapLength = horiz ? cellWidth : cellHeight;
// double vddArea = (mergedVdd ? 1 : 2) * vddWidth * strapLength;
// double gndArea = 2 * gndWidth * strapLength;
// coverage = (vddArea + gndArea)/cellArea;
// }
}
// ------------------------------- ExportBars ---------------------------------
class ExportBar
{
PortInst[] ports = null;
Double center = null;
ExportBar(PortInst p1, PortInst p2, double c)
{
ports = new PortInst[2];
ports[0] = p1;
ports[1] = p2;
center = (c); // autoboxing
}
}
class MetalLayer extends VddGndStraps {
protected MetalFloorplanBase plan;
protected int layerNum;
protected PrimitiveNode pin;
protected ArcProto metal;
protected ArrayList<ExportBar> vddBars = new ArrayList<ExportBar>();
protected ArrayList<ExportBar> gndBars = new ArrayList<ExportBar>();
public boolean addExtraArc() { return true; }
private void buildGnd(Cell cell) {
double pinX, pinY;
MetalFloorplan plan = (MetalFloorplan)this.plan;
if (plan.horizontal) {
pinX = plan.cellWidth/2; // - plan.gndWidth/2;
pinY = plan.gndCenter;
} else {
pinX = plan.gndCenter;
pinY = plan.cellHeight/2; // - plan.gndWidth/2;
}
PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
if (plan.horizontal) {
G.noExtendArc(metal, plan.gndWidth, tl, tr);
G.noExtendArc(metal, plan.gndWidth, bl, br);
gndBars.add(new ExportBar(bl, br, -plan.gndCenter));
gndBars.add(new ExportBar(tl, tr, plan.gndCenter));
} else {
G.noExtendArc(metal, plan.gndWidth, bl, tl);
G.noExtendArc(metal, plan.gndWidth, br, tr);
gndBars.add(new ExportBar(bl, tl, -plan.gndCenter));
gndBars.add(new ExportBar(br, tr, plan.gndCenter));
}
}
private void buildVdd(Cell cell) {
double pinX, pinY;
MetalFloorplan plan = (MetalFloorplan)this.plan;
if (plan.horizontal) {
pinX = plan.cellWidth/2; // - plan.vddWidth/2;
pinY = plan.vddCenter;
} else {
pinX = plan.vddCenter;
pinY = plan.cellHeight/2; // - plan.vddWidth/2;
}
if (plan.mergedVdd) {
PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
G.noExtendArc(metal, plan.vddWidth, bl, tr);
vddBars.add(new ExportBar(bl, tr, plan.vddCenter));
} else {
PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
if (plan.horizontal) {
G.noExtendArc(metal, plan.vddWidth, tl, tr);
G.noExtendArc(metal, plan.vddWidth, bl, br);
vddBars.add(new ExportBar(bl, br, -plan.vddCenter));
vddBars.add(new ExportBar(tl, tr, plan.vddCenter));
} else {
G.noExtendArc(metal, plan.vddWidth, bl, tl);
G.noExtendArc(metal, plan.vddWidth, br, tr);
vddBars.add(new ExportBar(bl, tl, -plan.vddCenter));
vddBars.add(new ExportBar(br, tr, plan.vddCenter));
}
}
}
/** It has to be protected to be overwritten by sub classes */
protected void buildGndAndVdd(Cell cell)
{
buildGnd(cell);
buildVdd(cell);
}
public MetalLayer(TechType t, int layerNum, Floorplan plan, Cell cell)
{
super(t);
this.plan = (MetalFloorplanBase)plan;
this.layerNum = layerNum;
metal = METALS[layerNum];
pin = PINS[layerNum];
buildGndAndVdd(cell);
}
public boolean isHorizontal() {return plan.horizontal;}
public int numVdd() {return vddBars.size();}
public double getVddCenter(int n) {
return (vddBars.get(n).center); // autoboxing
}
public PortInst getVdd(int n, int pos)
{return vddBars.get(n).ports[pos];}
public double getVddWidth(int n) {return plan.vddWidth;}
public int numGnd() {return gndBars.size();}
public double getGndCenter(int n) {
return (gndBars.get(n).center); // autoboxing
}
public PortInst getGnd(int n, int pos) {return gndBars.get(n).ports[pos];}
public double getGndWidth(int n) {return (plan).gndWidth;}
public PrimitiveNode getPinType() {return pin;}
public ArcProto getMetalType() {return metal;}
public double getCellWidth() {return plan.cellWidth;}
public double getCellHeight() {return plan.cellHeight;}
public int getLayerNumber() {return layerNum;}
}
// ------------------------------- MetalLayerFlex -----------------------------
class MetalLayerFlex extends MetalLayer {
public MetalLayerFlex(TechType t, int layerNum, Floorplan plan, Cell cell) {
super(t, layerNum, plan, cell);
}
public boolean addExtraArc() { return false; } // For automatic fill generator no extra arcs are wanted.
protected void buildGndAndVdd(Cell cell) {
double pinX, pinY;
double limit = 0;
MetalFloorplanFlex plan = (MetalFloorplanFlex)this.plan;
if (plan.horizontal)
{
limit = plan.cellHeight/2;
}
else
{
limit = plan.cellWidth/2;
}
double position = 0;
int i = 0;
while (position < limit)
{
boolean even = (i%2==0);
double maxDelta = 0, pos = 0;
if (even)
{
maxDelta = plan.vddReserve/2 + plan.vddWidth;
pos = plan.vddReserve/2 + plan.vddWidth/2 + position;
}
else
{
maxDelta = plan.gndReserve/2 + plan.gndWidth;
pos = plan.gndReserve/2 + plan.gndWidth/2 + position;
}
if (position + maxDelta > limit) return; // border was reached
if (plan.horizontal)
{
pinY = pos;
pinX = plan.cellWidth/2;
}
else
{
pinX = pos;
pinY = plan.cellHeight/2;
}
// Vdd if even, gnd if odd
if (!even)
addBars(cell, pinX, pinY, plan.gndWidth, gndBars);
else
addBars(cell, pinX, pinY, plan.vddWidth, vddBars);
if (even)
{
maxDelta = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth;
pos = plan.vddReserve/2 + plan.vddWidth + plan.space + plan.gndWidth/2 + position;
}
else
{
maxDelta = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth;
pos = plan.gndReserve/2 + plan.gndWidth + plan.space + plan.vddWidth/2 + position;
}
if (position + maxDelta > limit) return; // border was reached
if (plan.horizontal)
pinY = pos;
else
pinX = pos;
// Gnd if even, vdd if odd
if (!even)
{
addBars(cell, pinX, pinY, plan.vddWidth, vddBars);
position = ((plan.horizontal)?pinY:pinX) + plan.vddWidth/2 + plan.vddReserve/2;
}
else
{
addBars(cell, pinX, pinY, plan.gndWidth, gndBars);
position = ((plan.horizontal)?pinY:pinX) + plan.gndWidth/2 + plan.gndReserve/2;
}
i++;
}
}
private void addBars(Cell cell, double pinX, double pinY, double width, ArrayList<ExportBar> bars)
{
PortInst tl = LayoutLib.newNodeInst(pin, -pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst tr = LayoutLib.newNodeInst(pin, pinX, pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst bl = LayoutLib.newNodeInst(pin, -pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
PortInst br = LayoutLib.newNodeInst(pin, pinX, -pinY, G.DEF_SIZE,
G.DEF_SIZE, 0, cell
).getOnlyPortInst();
double center = 0;
if (plan.horizontal) {
G.noExtendArc(metal, width, tl, tr);
G.noExtendArc(metal, width, bl, br);
center = pinY;
bars.add(new ExportBar(bl, br, -center));
bars.add(new ExportBar(tl, tr, center));
} else {
G.noExtendArc(metal, width, bl, tl);
G.noExtendArc(metal, width, br, tr);
center = pinX;
bars.add(new ExportBar(bl, tl, -center));
bars.add(new ExportBar(br, tr, center));
}
}
}
//---------------------------------- CapLayer ---------------------------------
class CapLayer extends VddGndStraps {
private CapCell capCell;
private NodeInst capCellInst;
private CapFloorplan plan;
public boolean addExtraArc() { return true; }
public CapLayer(TechType t, CapFloorplan plan, CapCell capCell, Cell cell)
{
super(t);
this.plan = plan;
this.capCell = capCell;
double angle = plan.horizontal ? 0 : 90;
if (capCell != null)
capCellInst = LayoutLib.newNodeInst(capCell.getCell(), 0, 0, G.DEF_SIZE,
G.DEF_SIZE, angle, cell);
}
public boolean isHorizontal() {return plan.horizontal;}
public int numVdd() {return (capCell != null) ? capCell.numVdd() : 0;}
public PortInst getVdd(int n, int pos) {
return capCellInst.findPortInst(FillCell.VDD_NAME+"_"+n);
}
public double getVddCenter(int n) {
EPoint center = getVdd(n, 0).getCenter();
return plan.horizontal ? center.getY() : center.getX();
}
public double getVddWidth(int n) {return capCell.getVddWidth();}
public int numGnd() {return (capCell != null) ? capCell.numGnd() : 0;}
public PortInst getGnd(int n, int pos) {
return capCellInst.findPortInst(FillCell.GND_NAME+"_"+n);
}
public double getGndCenter(int n) {
EPoint center = getGnd(n, 0).getCenter();
return plan.horizontal ? center.getY() : center.getX();
}
public double getGndWidth(int n) {return capCell.getGndWidth();}
public PrimitiveNode getPinType() {return tech.m1pin();}
public ArcProto getMetalType() {return tech.m1();}
public double getCellWidth() {return plan.cellWidth;}
public double getCellHeight() {return plan.cellHeight;}
public int getLayerNumber() {return 1;}
}
class FillRouter {
private HashMap<String,List<PortInst>> portMap = new HashMap<String,List<PortInst>>();
private TechType tech;
private String makeKey(PortInst pi) {
EPoint center = pi.getCenter();
String x = ""+center.getX(); // LayoutLib.roundCenterX(pi);
String y = ""+center.getY(); // LayoutLib.roundCenterY(pi);
return x+"x"+y;
}
// private boolean bothConnect(ArcProto a, PortProto pp1, PortProto pp2) {
// return pp1.connectsTo(a) && pp2.connectsTo(a);
// }
private ArcProto findCommonArc(PortInst p1, PortInst p2) {
ArcProto[] metals = {tech.m6(), tech.m5(), tech.m4(), tech.m3(), tech.m2(), tech.m1()};
PortProto pp1 = p1.getPortProto();
PortProto pp2 = p2.getPortProto();
for (int i=0; i<metals.length; i++) {
if (pp1.connectsTo(metals[i]) && pp2.connectsTo(metals[i])) {
return metals[i];
}
}
return null;
}
private void connectPorts(List<PortInst> ports) {
for (Iterator<PortInst> it=ports.iterator(); it.hasNext(); ) {
PortInst first = it.next();
double width = LayoutLib.widestWireWidth(first);
it.remove();
for (PortInst pi : ports) {
ArcProto a = findCommonArc(first, pi);
if (a!=null) LayoutLib.newArcInst(a, width, first, pi);
}
}
}
private FillRouter(TechType t, ArrayList<PortInst> ports)
{
tech = t;
for (PortInst pi : ports) {
String key = makeKey(pi);
List<PortInst> l = portMap.get(key);
if (l==null) {
l = new LinkedList<PortInst>();
portMap.put(key, l);
}
l.add(pi);
}
// to guarantee deterministic results
List<String> keys = new ArrayList<String>();
keys.addAll(portMap.keySet());
Collections.sort(keys);
for (String str : keys) {
connectPorts(portMap.get(str));
}
}
public static void connectCoincident(TechType t, ArrayList<PortInst> ports) {
new FillRouter(t, ports);
}
}
/**
* Object for building fill libraries
*/
public class FillGeneratorTool extends Tool {
public FillGenConfig config;
protected Library lib;
private boolean libInitialized;
public List<Cell> masters;
protected CapCell capCell;
protected Floorplan[] plans;
/** the fill generator tool. */ private static FillGeneratorTool tool = getTool();
// Depending on generator plugin available
public static FillGeneratorTool getTool()
{
if (tool != null) return tool;
FillGeneratorTool tool;
try
{
Class<?> extraClass = Class.forName("com.sun.electric.plugins.generator.FillCellTool");
Constructor instance = extraClass.getDeclaredConstructor(); // varags
Object obj = instance.newInstance(); // varargs;
tool = (FillGeneratorTool)obj;
} catch (Exception e)
{
if (Job.getDebug())
System.out.println("GNU Release can't find Fill Cell Generator plugin");
tool = new FillGeneratorTool();
}
return tool;
}
public FillGeneratorTool() {
super("Fill Generator");
}
public void setConfig(FillGenConfig config)
{
this.config = config;
this.libInitialized = false;
}
public enum Units {NONE, LAMBDA, TRACKS}
protected boolean getOrientation() {return plans[plans.length-1].horizontal;}
/** Reserve space in the middle of the Vdd and ground straps for signals.
* @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer
* number 1 is reserved to mean "capacitor between Vdd and ground".
* @param reserved space to reserve in the middle of the central
* strap in case of Vdd. The value 0 makes the Vdd strap one large strap instead of two smaller
* adjacent straps.
* Space to reserve between the ground strap of this
* cell and the ground strap of the adjacent fill cell. The value 0 means
* that these two ground straps should abut to form a single large strap
* instead of two smaller adjacent straps.
* */
private double reservedToLambda(int layer, double reserved, Units units) {
if (units==LAMBDA) return reserved;
double nbTracks = reserved;
if (nbTracks==0) return 0;
return config.getTechType().reservedToLambda(layer, nbTracks);
}
private Floorplan[] makeFloorplans(boolean metalFlex, boolean hierFlex) {
Job.error(config.width==Double.NaN,
"width hasn't been specified. use setWidth()");
Job.error(config.height==Double.NaN,
"height hasn't been specified. use setHeight()");
double w = config.width;
double h = config.height;
int numLayers = config.getTechType().getNumMetals() + 1; // one extra for the cap
double[] vddRes = new double[numLayers]; //{0,0,0,0,0,0,0};
double[] gndRes = new double[numLayers]; //{0,0,0,0,0,0,0};
double[] vddW = new double[numLayers]; //{0,0,0,0,0,0,0};
double[] gndW = new double[numLayers]; //{0,0,0,0,0,0,0};
// set given values
for (FillGenConfig.ReserveConfig c : config.reserves)
{
vddRes[c.layer] = reservedToLambda(c.layer, c.vddReserved, c.vddUnits);
gndRes[c.layer] = reservedToLambda(c.layer, c.gndReserved, c.gndUnits);
if (c.vddWUnits != Units.NONE)
vddW[c.layer] = reservedToLambda(c.layer, c.vddWidth, c.vddWUnits);
if (c.gndWUnits != Units.NONE)
gndW[c.layer] = reservedToLambda(c.layer, c.gndWidth, c.gndWUnits);
}
boolean evenHor = config.evenLayersHorizontal;
boolean alignedMetals = true;
double[] spacing = new double[numLayers];
for (int i = 0; i < numLayers; i++) spacing[i] = config.drcSpacingRule;
// {config.drcSpacingRule,config.drcSpacingRule,
// config.drcSpacingRule,config.drcSpacingRule,
// config.drcSpacingRule,config.drcSpacingRule,config.drcSpacingRule};
if (alignedMetals)
{
double maxVddRes = 0, maxGndRes = 0, maxSpacing = 0, maxVddW = 0, maxGndW = 0;
for (int i = 0; i < vddRes.length; i++)
{
boolean vddOK = false, gndOK = false;
if (vddRes[i] > 0)
{
vddOK = true;
if (maxVddRes < vddRes[i]) maxVddRes = vddRes[i];
}
if (gndRes[i] > 0)
{
gndOK = true;
if (maxGndRes < gndRes[i]) maxGndRes = gndRes[i];
}
if (gndOK || vddOK) // checking max spacing rule
{
if (maxSpacing < config.drcSpacingRule) maxSpacing = config.drcSpacingRule; //drcRules[i];
}
if (maxVddW < vddW[i])
maxVddW = vddW[i];
if (maxGndW < gndW[i])
maxGndW = gndW[i];
}
// correct the values
for (int i = 0; i < vddRes.length; i++)
{
vddRes[i] = maxVddRes;
gndRes[i] = maxGndRes;
spacing[i] = maxSpacing;
vddW[i] = maxVddW;
gndW[i] = maxGndW;
}
}
Floorplan[] thePlans = new Floorplan[numLayers];
// 0 is always null
thePlans[1] = new CapFloorplan(w, h, !evenHor);
if (metalFlex)
{
if (!hierFlex)
{
for (int i = 2; i < numLayers; i++)
{
boolean horiz = (i%2==0);
thePlans[i] = new MetalFloorplanFlex(w, h, vddRes[i], gndRes[i], spacing[i], vddW[i], gndW[i], horiz);
}
return thePlans;
}
w = config.width = config.minTileSizeX;
h = config.height = config.minTileSizeY;
}
for (int i = 2; i < numLayers; i++)
{
boolean horiz = (i%2==0);
thePlans[i] = new MetalFloorplan(w, h, vddRes[i], gndRes[i], spacing[i], horiz);
}
return thePlans;
}
private void printCoverage(Floorplan[] plans) {
for (int i=2; i<plans.length; i++) {
System.out.println("metal-"+i+" coverage: "+
((MetalFloorplan)plans[i]).coverage);
}
}
private static CapCell getCMOS90CapCell(Library lib, CapFloorplan plan)
{
CapCell c = null;
try
{
Class<?> cmos90Class = Class.forName("com.sun.electric.plugins.tsmc.fill90nm.CapCellCMOS90");
Constructor capCellC = cmos90Class.getDeclaredConstructor(Library.class, CapFloorplan.class); // varargs
Object cell = capCellC.newInstance(lib, plan);
c = (CapCell)cell;
} catch (Exception e)
{
assert(false); // runtime error
}
return c;
}
protected void initFillParameters(boolean metalFlex, boolean hierFlex) {
if (libInitialized) return;
Job.error(config.fillLibName==null, "no library specified. Use setFillLibrary()");
Job.error((config.width==Double.NaN || config.width<=0), "no width specified. Use setFillCellWidth()");
Job.error((config.height==Double.NaN || config.height<=0), "no height specified. Use setFillCellHeight()");
plans = makeFloorplans(metalFlex, hierFlex);
if (!metalFlex) printCoverage(plans);
lib = LayoutLib.openLibForWrite(config.fillLibName);
if (!metalFlex) // don't do transistors
{
if (config.is180Tech())
{
capCell = new CapCellMosis(lib, (CapFloorplan) plans[1], config.getTechType());
}
else
{
capCell = getCMOS90CapCell(lib, (CapFloorplan) plans[1]);
}
}
libInitialized = true;
}
private void makeTiledCells(Cell cell, Floorplan[] plans, Library lib,
int[] tiledSizes) {
if (tiledSizes==null) return;
for (int num : tiledSizes)
{
TiledCell.makeTiledCell(num, num, cell, plans, lib);
}
}
public static Cell makeFillCell(Library lib, Floorplan[] plans,
int botLayer, int topLayer, CapCell capCell,
TechType tech,
ExportConfig expCfg, boolean metalFlex, boolean hierFlex) {
FillCell fc = new FillCell(tech);
return fc.makeFillCell1(lib, plans, botLayer, topLayer, capCell,
expCfg, metalFlex, hierFlex);
}
/**
* Method to create standard set of tiled cells.
*/
private Cell standardMakeAndTileCell(Library lib, Floorplan[] plans, int lowLay,
int hiLay, CapCell capCell,
TechType tech,
ExportConfig expCfg,
int[] tiledSizes, boolean metalFlex)
{
Cell master = makeFillCell(lib, plans, lowLay, hiLay, capCell,
tech, expCfg, metalFlex, false);
masters = new ArrayList<Cell>();
masters.add(master);
makeTiledCells(master, plans, lib, tiledSizes);
return master;
}
public static final Units LAMBDA = Units.LAMBDA;
public static final Units TRACKS = Units.TRACKS;
//public static final PowerType POWER = PowerType.POWER;
//public static final PowerType VDD = PowerType.VDD;
public static final ExportConfig PERIMETER = ExportConfig.PERIMETER;
public static final ExportConfig PERIMETER_AND_INTERNAL = ExportConfig.PERIMETER_AND_INTERNAL;
/** Reserve space in the middle of the Vdd and ground straps for signals.
* @param layer the layer number. This may be 2, 3, 4, 5, or 6. The layer
* number 1 is reserved to mean "capacitor between Vdd and ground".
* @param vddReserved space to reserve in the middle of the central Vdd
* strap.
* The value 0 makes the Vdd strap one large strap instead of two smaller
* adjacent straps.
* @param vddUnits LAMBDA or TRACKS
* @param gndReserved space to reserve between the ground strap of this
* cell and the ground strap of the adjacent fill cell. The value 0 means
* that these two ground straps should abut to form a single large strap
* instead of two smaller adjacent straps.
* @param gndUnits LAMBDA or TRACKS
* param tiledSizes an array of sizes. The default value is null. The
* value null means don't generate anything. */
// public void reserveSpaceOnLayer(int layer,
// double vddReserved, Units vddUnits,
// double gndReserved, Units gndUnits) {
// LayoutLib.error(layer<2 || layer>6,
// "Bad layer. Layers must be between 2 and 6 inclusive: "+
// layer);
// this.vddReserved[layer] = reservedToLambda(layer, vddReserved, vddUnits);
// this.gndReserved[layer] = reservedToLambda(layer, gndReserved, gndUnits);
// }
/** Create a fill cell using the current library, fill cell width, fill cell
* height, layer orientation, and reserved spaces for each layer. Then
* generate larger fill cells by tiling that fill cell according to the
* current tiled cell sizes.
* @param loLayer the lower layer. This may be 1 through 6. Layer 1 means
* build a capacitor using MOS transistors between Vdd and ground.
* @param hiLayer the upper layer. This may be 2 through 6. Note that hiLayer
* must be >= loLayer.
* @param exportConfig may be PERIMETER in which case exports are
* placed along the perimeter of the cell for the top two layers. Otherwise
* exportConfig must be PERIMETER_AND_INTERNAL in which case exports are
* placed inside the perimeter of the cell for the bottom layer.
* @param tiledSizes Array specifying composite Cells we should build by
* concatonating fill cells. For example int[] {2, 4, 7} means we should
* */
public Cell standardMakeFillCell(int loLayer, int hiLayer,
TechType tech,
ExportConfig exportConfig,
int[] tiledSizes, boolean metalFlex) {
initFillParameters(metalFlex, false);
Job.error(loLayer<1, "loLayer must be >=1");
int maxNumMetals = config.getTechType().getNumMetals();
Job.error(hiLayer>maxNumMetals, "hiLayer must be <=" + maxNumMetals);
Job.error(loLayer>hiLayer, "loLayer must be <= hiLayer");
Cell cell = null;
cell = standardMakeAndTileCell(lib, plans, loLayer, hiLayer, capCell,
tech, exportConfig,
tiledSizes, metalFlex);
return cell;
}
public void makeGallery() {
Gallery.makeGallery(lib);
}
public void writeLibrary(int backupScheme) throws JobException {
LayoutLib.writeLibrary(lib, backupScheme);
}
public enum FillTypeEnum {INVALID,TEMPLATE,CELL}
}
|
gpl-3.0
|
slspeek/FSpotCloudSite
|
xref/fspotcloud/shared/admin/MetaDataInfo.html
|
9268
|
<!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>MetaDataInfo xref</title>
<link type="text/css" rel="stylesheet" href="../../../stylesheet.css" />
</head>
<body>
<div id="overview"><a href="../../../../apidocs/fspotcloud/shared/admin/MetaDataInfo.html">View Javadoc</a></div><pre>
<a class="jxr_linenumber" name="1" href="#1">1</a> <strong class="jxr_keyword">package</strong> fspotcloud.shared.admin;
<a class="jxr_linenumber" name="2" href="#2">2</a>
<a class="jxr_linenumber" name="3" href="#3">3</a> <strong class="jxr_keyword">import</strong> java.util.Date;
<a class="jxr_linenumber" name="4" href="#4">4</a>
<a class="jxr_linenumber" name="5" href="#5">5</a> <strong class="jxr_keyword">import</strong> com.google.gwt.user.client.rpc.IsSerializable;
<a class="jxr_linenumber" name="6" href="#6">6</a>
<a class="jxr_linenumber" name="7" href="#7">7</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">class</strong> <a href="../../../fspotcloud/shared/admin/MetaDataInfo.html">MetaDataInfo</a> <strong class="jxr_keyword">implements</strong> IsSerializable {
<a class="jxr_linenumber" name="8" href="#8">8</a>
<a class="jxr_linenumber" name="9" href="#9">9</a> <strong class="jxr_keyword">private</strong> Date created;
<a class="jxr_linenumber" name="10" href="#10">10</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> peerPhotoCount;
<a class="jxr_linenumber" name="11" href="#11">11</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> tagCount;
<a class="jxr_linenumber" name="12" href="#12">12</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">int</strong> pendingCommandCount;
<a class="jxr_linenumber" name="13" href="#13">13</a> <strong class="jxr_keyword">private</strong> Date peerLastSeen;
<a class="jxr_linenumber" name="14" href="#14">14</a> <strong class="jxr_keyword">private</strong> String instanceName;
<a class="jxr_linenumber" name="15" href="#15">15</a> <strong class="jxr_keyword">private</strong> <strong class="jxr_keyword">long</strong> photoCount;
<a class="jxr_linenumber" name="16" href="#16">16</a> <strong class="jxr_keyword">private</strong> Date photosLastCounted;
<a class="jxr_linenumber" name="17" href="#17">17</a>
<a class="jxr_linenumber" name="18" href="#18">18</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">long</strong> getPhotoCount() {
<a class="jxr_linenumber" name="19" href="#19">19</a> <strong class="jxr_keyword">return</strong> photoCount;
<a class="jxr_linenumber" name="20" href="#20">20</a> }
<a class="jxr_linenumber" name="21" href="#21">21</a>
<a class="jxr_linenumber" name="22" href="#22">22</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPhotoCount(<strong class="jxr_keyword">long</strong> photoCount) {
<a class="jxr_linenumber" name="23" href="#23">23</a> <strong class="jxr_keyword">this</strong>.photoCount = photoCount;
<a class="jxr_linenumber" name="24" href="#24">24</a> }
<a class="jxr_linenumber" name="25" href="#25">25</a>
<a class="jxr_linenumber" name="26" href="#26">26</a> <strong class="jxr_keyword">public</strong> Date getPhotosLastCounted() {
<a class="jxr_linenumber" name="27" href="#27">27</a> <strong class="jxr_keyword">return</strong> photosLastCounted;
<a class="jxr_linenumber" name="28" href="#28">28</a> }
<a class="jxr_linenumber" name="29" href="#29">29</a>
<a class="jxr_linenumber" name="30" href="#30">30</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPhotosLastCounted(Date photosLastCounted) {
<a class="jxr_linenumber" name="31" href="#31">31</a> <strong class="jxr_keyword">this</strong>.photosLastCounted = photosLastCounted;
<a class="jxr_linenumber" name="32" href="#32">32</a> }
<a class="jxr_linenumber" name="33" href="#33">33</a>
<a class="jxr_linenumber" name="34" href="#34">34</a> <strong class="jxr_keyword">public</strong> <a href="../../../fspotcloud/shared/admin/MetaDataInfo.html">MetaDataInfo</a>() {
<a class="jxr_linenumber" name="35" href="#35">35</a> created = <strong class="jxr_keyword">new</strong> Date();
<a class="jxr_linenumber" name="36" href="#36">36</a> }
<a class="jxr_linenumber" name="37" href="#37">37</a>
<a class="jxr_linenumber" name="38" href="#38">38</a> <strong class="jxr_keyword">public</strong> Date getCreated() {
<a class="jxr_linenumber" name="39" href="#39">39</a> <strong class="jxr_keyword">return</strong> created;
<a class="jxr_linenumber" name="40" href="#40">40</a> }
<a class="jxr_linenumber" name="41" href="#41">41</a>
<a class="jxr_linenumber" name="42" href="#42">42</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getPeerPhotoCount() {
<a class="jxr_linenumber" name="43" href="#43">43</a> <strong class="jxr_keyword">return</strong> peerPhotoCount;
<a class="jxr_linenumber" name="44" href="#44">44</a> }
<a class="jxr_linenumber" name="45" href="#45">45</a>
<a class="jxr_linenumber" name="46" href="#46">46</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPeerPhotoCount(<strong class="jxr_keyword">int</strong> peerPhotoCount) {
<a class="jxr_linenumber" name="47" href="#47">47</a> <strong class="jxr_keyword">this</strong>.peerPhotoCount = peerPhotoCount;
<a class="jxr_linenumber" name="48" href="#48">48</a> }
<a class="jxr_linenumber" name="49" href="#49">49</a>
<a class="jxr_linenumber" name="50" href="#50">50</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getTagCount() {
<a class="jxr_linenumber" name="51" href="#51">51</a> <strong class="jxr_keyword">return</strong> tagCount;
<a class="jxr_linenumber" name="52" href="#52">52</a> }
<a class="jxr_linenumber" name="53" href="#53">53</a>
<a class="jxr_linenumber" name="54" href="#54">54</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setTagCount(<strong class="jxr_keyword">int</strong> tagCount) {
<a class="jxr_linenumber" name="55" href="#55">55</a> <strong class="jxr_keyword">this</strong>.tagCount = tagCount;
<a class="jxr_linenumber" name="56" href="#56">56</a> }
<a class="jxr_linenumber" name="57" href="#57">57</a>
<a class="jxr_linenumber" name="58" href="#58">58</a> <strong class="jxr_keyword">public</strong> Date getPeerLastSeen() {
<a class="jxr_linenumber" name="59" href="#59">59</a> <strong class="jxr_keyword">return</strong> peerLastSeen;
<a class="jxr_linenumber" name="60" href="#60">60</a> }
<a class="jxr_linenumber" name="61" href="#61">61</a>
<a class="jxr_linenumber" name="62" href="#62">62</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPeerLastSeen(Date peerLastSeen) {
<a class="jxr_linenumber" name="63" href="#63">63</a> <strong class="jxr_keyword">this</strong>.peerLastSeen = peerLastSeen;
<a class="jxr_linenumber" name="64" href="#64">64</a> }
<a class="jxr_linenumber" name="65" href="#65">65</a>
<a class="jxr_linenumber" name="66" href="#66">66</a> <strong class="jxr_keyword">public</strong> String getInstanceName() {
<a class="jxr_linenumber" name="67" href="#67">67</a> <strong class="jxr_keyword">return</strong> instanceName;
<a class="jxr_linenumber" name="68" href="#68">68</a> }
<a class="jxr_linenumber" name="69" href="#69">69</a>
<a class="jxr_linenumber" name="70" href="#70">70</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setInstanceName(String instanceName) {
<a class="jxr_linenumber" name="71" href="#71">71</a> <strong class="jxr_keyword">this</strong>.instanceName = instanceName;
<a class="jxr_linenumber" name="72" href="#72">72</a> }
<a class="jxr_linenumber" name="73" href="#73">73</a>
<a class="jxr_linenumber" name="74" href="#74">74</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">void</strong> setPendingCommandCount(<strong class="jxr_keyword">int</strong> pendingCommandCount) {
<a class="jxr_linenumber" name="75" href="#75">75</a> <strong class="jxr_keyword">this</strong>.pendingCommandCount = pendingCommandCount;
<a class="jxr_linenumber" name="76" href="#76">76</a> }
<a class="jxr_linenumber" name="77" href="#77">77</a>
<a class="jxr_linenumber" name="78" href="#78">78</a> <strong class="jxr_keyword">public</strong> <strong class="jxr_keyword">int</strong> getPendingCommandCount() {
<a class="jxr_linenumber" name="79" href="#79">79</a> <strong class="jxr_keyword">return</strong> pendingCommandCount;
<a class="jxr_linenumber" name="80" href="#80">80</a> }
<a class="jxr_linenumber" name="81" href="#81">81</a>
<a class="jxr_linenumber" name="82" href="#82">82</a> }
</pre>
<hr/><div id="footer">This page was automatically generated by <a href="http://maven.apache.org/">Maven</a></div></body>
</html>
|
gpl-3.0
|
Zi-i/MCI_Host
|
src/session.cpp
|
23063
|
#include "session.h"
// This file is part of MCI_Host.
// MCI_Host 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.
// MCI_Host 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 MCI_Host under the LICENSE.md file. If not, see
// <http://www.gnu.org/licenses/>.
Session::Session(uint sesId, qintptr newPtr, QObject *parent) : QTcpSocket(0)
{
timer = new QTimer();
bits = 0;
flags = 0;
dSize = 0;
sessionId = 0;
slotId = 0;
baseSlot = 0;
rdHash = 0;
wrHash = 0;
cmdListMode = 0;
cmdListCaseSensitive = false;
cmdListenabled = false;
keyOk = false;
verOk = false;
onBaseSlot = false;
timer->setSingleShot(true);
timer->setInterval(6000);
// the timer object provides a 6sec timeout for the client to send the
// header before the session is forced closed.
connect(this, SIGNAL(readyRead()), this, SLOT(dataFromClient()));
connect(this, SIGNAL(destroyed()), timer, SLOT(deleteLater()));
connect(timer, SIGNAL(timeout()), this, SLOT(sessionTimeout()));
connect(parent, SIGNAL(destroyed()), this, SLOT(deleteLater()));
setSocketDescriptor(newPtr);
if (inBanList(peerAddress().toString()))
{
// any session that still has a session id of zero after running the
// contructor is considered a blocked ip so the session will get killed
// externally at Server::incomingConnection().
sessionEnding = true;
addIpAction(tr("IP address blocked"), peerAddress().toString());
}
else
{
// Session represents the TCP connection with the client. it provides the
// xOR encryption, version negotiation and an interface for CmdHub objects.
// it starts in it's own thread from within the contructor and kills
// itself when the client disconnects but does not kill the CmdHub it's
// currently connected to.
addIpAction(tr("Connected, assigned session id: ") + QString::number(sesId), peerAddress().toString());
sessionEnding = false;
sessionId = sesId;
QThread *thr = new QThread();
connect(thr, SIGNAL(finished()), thr, SLOT(deleteLater()));
connect(thr, SIGNAL(started()), timer, SLOT(start()));
connect(this, SIGNAL(destroyed()), thr, SLOT(quit()));
connect(this, SIGNAL(disconnected()), this, SLOT(clientDisconnected()));
timer->moveToThread(thr);
moveToThread(thr);
thr->start();
}
}
bool Session::loadProfile(const QString &proName, QByteArray &key)
{
// this function runs 3 database queries to read the following profile
// data:
// keyHash - this is used in the Hash object to setup encryption.
// groupName - this indicates what group the profile belongs to.
// the group can contain host privileges that profile
// is allowed to do.
// cmdListCaseSensitive - indicates if the profileCmdList is casesSensitive.
// cmdListenabled - indicates if the profileCmdList is enabled.
// cmdListMode - indicates what the profileCmdList does when the
// sent in command line is matched.
// baseSlot - this indicates the fallback slot in cases when the
// the slot the session is currently connected is
// killed.
// profileCmdList - this is the group command line list that is used
// allowed or disallow certain commands depending
// on what is loaded into cmdListMode or
// cmdListCaseSensitive.
bool ret = false;
Query db(this);
db.setType(Query::PULL, TABLE_PROFILES);
db.addColumn(COLUMN_PRONAME);
db.addColumn(COLUMN_PROKEY);
db.addColumn(COLUMN_GRNAME);
db.addCondition(COLUMN_PRONAME, proName);
db.exec();
if (db.rows())
{
ret = true;
profileName = db.getData(COLUMN_PRONAME).toString();
groupName = db.getData(COLUMN_GRNAME).toString();
key = db.getData(COLUMN_PROKEY).toByteArray();
db.setType(Query::PULL, TABLE_GROUPS);
db.addColumn(COLUMN_CS);
db.addColumn(COLUMN_LS_MODE);
db.addColumn(COLUMN_LS_STATE);
db.addColumn(COLUMN_BASE_SL);
db.addCondition(COLUMN_GRNAME, groupName);
db.exec();
cmdListCaseSensitive = db.getData(COLUMN_CS).toBool();
cmdListenabled = db.getData(COLUMN_LS_STATE).toBool();
cmdListMode = db.getData(COLUMN_LS_MODE).toUInt();
baseSlot = db.getData(COLUMN_BASE_SL).toUInt();
profileCmdList.clear();
db.setType(Query::PULL, TABLE_CMD_LIST);
db.addColumn(COLUMN_CMD_LINE);
db.addCondition(COLUMN_GRNAME, groupName);
db.exec();
for (int i = 0; i < db.rows(); ++i)
{
profileCmdList.append(db.getData(COLUMN_CMD_LINE, i).toString());
}
}
return ret;
}
bool Session::inBanList(const QString &ip)
{
// simple database select query with the provided ip address in the where
// clause. if a row is found, that indicates that the ip address is in
// the ban list.
Query db(this);
db.setType(Query::PULL, TABLE_IPBANS);
db.addColumn(COLUMN_IPADDR);
db.addCondition(COLUMN_IPADDR, ip);
db.exec();
return db.rows();
}
void Session::addIpAction(const QString &action, const QString &ip)
{
// insert database query for the ip address action log (ip_hist).
Query db(this);
db.setType(Query::PUSH, TABLE_IPHIST);
db.addColumn(COLUMN_IPADDR, ip);
db.addColumn(COLUMN_LOGENTRY, action);
db.exec();
}
uint Session::id()
{
return sessionId;
}
void Session::slotClosed()
{
// this function is connected to CmdHub::destroyed() as a way to catch if the currently
// connected command interperter has been killed. command interperters (CmdHub) running in the
// background are considered slots in this application so when a command interperter dies, its
// the same as a slot getting closed so the session will attempt to re-create or re-attach to
// the base slot defined in the profile when this happens. this behavior should not be allowed
// if the session is closing so sessionEnding is checked.
if (!sessionEnding)
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<300> Slot id: ") + QString::number(slotId) + tr(" was killed. falling back to slot id: ") + QString::number(baseSlot) + tr("."));
emit createSlot(sessionId, 0, baseSlot);
}
}
void Session::groupBaseSlotChanged(const QString &grpName, uint id)
{
if (grpName.toLower() == groupName.toLower())
{
if (onBaseSlot)
{
// force the session to create or attach to the new base slot if currently connected
// to the old base slot.
emit createSlot(sessionId, baseSlot, id);
}
baseSlot = id;
}
}
void Session::groupCmdListChanged(const QString &grpName, const QStringList &ls)
{
if (grpName.toLower() == groupName.toLower())
{
profileCmdList = ls;
}
}
void Session::groupCSListChanged(const QString &grpName, bool cs)
{
if (grpName.toLower() == groupName.toLower())
{
cmdListCaseSensitive = cs;
}
}
void Session::groupEnabledListChanged(const QString &grpName, bool state)
{
if (grpName.toLower() == groupName.toLower())
{
cmdListenabled = state;
}
}
void Session::groupCmdLsModeChanged(const QString &grpName, uint mode)
{
if (grpName.toLower() == groupName.toLower())
{
cmdListMode = mode;
}
}
void Session::profileGroupChanged(const QString &proName)
{
if (profileName.toLower() == proName.toLower())
{
QByteArray unused;
loadProfile(profileName, unused);
groupBaseSlotChanged(groupName, baseSlot);
}
}
void Session::profileNameChanged(const QString &oldName, const QString &newName)
{
if (profileName.toLower() == oldName.toLower())
{
profileName = newName;
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<301> Your current profile name was changed to: ") + newName);
}
}
void Session::groupRenamed(const QString &oldName, const QString &newName)
{
if (groupName.toLower() == oldName.toLower())
{
groupName = newName;
}
}
void Session::profileDeleted(const QString &proName)
{
if (profileName.toLower() == proName.toLower())
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<302> Your current profile got deleted, ending this session."));
sessionEnding = true;
emit deleteSession(sessionId);
}
}
void Session::sessionSlotChanged(uint sesId, uint slId)
{
// this should be connected to the Server object's sessionSlotChanged() signal to help this
// object keep track of the slotId it is currently connected to.
if (sesId == sessionId)
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<201> Connected to slot id: ") + QString::number(slId) + tr("."));
slotId = slId;
onBaseSlot = (slotId == baseSlot);
}
}
void Session::clientDisconnected()
{
addIpAction(tr("Disconnected"), peerAddress().toString());
if (!sessionEnding)
{
sessionEnding = true;
emit deleteSession(sessionId);
}
}
void Session::sessionTimeout()
{
sessionEnding = true;
emit deleteSession(sessionId);
}
void Session::requestedToClose(uint sesId)
{
if (sesId == 0)
{
sessionEnding = true;
emit deleteSession(sessionId);
}
else if (sesId == sessionId)
{
emit okToDelete(sesId);
close();
}
}
void Session::dataToClient(const QByteArray &data, uint exclude, uchar flgs)
{
if (keyOk && (exclude != sessionId))
{
// data format: [num_of_bits][flags][data_size][data]
// it's very important that the data is sent in this format and encrypted to avoid
// undefined behavior.
QByteArray lenBa = wrInt(data.size());
QByteArray flagsBa = QByteArray(1, flgs);
QByteArray bitsBa = QByteArray(1, (uchar) lenBa.size() * 8);
write(wrHash->xOR(Hash::ENCODE, bitsBa + flagsBa + lenBa + data));
}
}
void Session::textFromCmd(uint sesId, bool cr, const QString &line)
{
QTextCodec *codec = QTextCodec::codecForName("UTF-16LE");
if (cr) dataToClient(codec->fromUnicode(line), 0, TEXT_CH);
else dataToClient(codec->fromUnicode(line), sesId, TEXT_CH);
}
void Session::textFromServer(uint sesId, const QString &line)
{
if ((sesId == sessionId) || (sesId == 0))
{
textFromCmd(sessionId, true, line);
}
}
void Session::binFromCmd(uint sesId, bool cr, bool priv, const QByteArray &bin)
{
if (priv)
{
if (sesId == sessionId)
{
dataToClient(bin, 0, BIN_CH);
}
}
else
{
if (cr) dataToClient(bin, 0, BIN_CH);
else dataToClient(bin, sesId, BIN_CH);
}
}
void Session::dataFilter(const QByteArray &data, uchar flgs)
{
// this take the decrypted data from dataFromClient() and converts it to a
// QString if the flgs TEXT_CH is present or reads the command name from
// the raw data if BIN_CH is present. the the command name or full command
// line is then checked with profileAllowedCmd() at this point.
QString line;
if (flgs & TEXT_CH)
{
line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data);
if (profileAllowedCmd(line))
{
emit textToCmd(sessionId, &profileName, line);
}
}
else if (flgs & BIN_CH)
{
if (activeHook)
{
emit binToCmd(sessionId, &profileName, data);
}
else
{
bool found = false;
for (int i = 0; i < data.size(); i += 2)
{
QByteArray chrPair(data.mid(i, 2));
if (chrPair.size() == 2)
{
if ((chrPair[0] == (char) 0) && (chrPair[1] == (char) 0))
{
line = QTextCodec::codecForName("UTF-16LE")->toUnicode(data.left(i));
if (profileAllowedCmd(line))
{
emit binToCmd(sessionId, &profileName, data);
}
found = true;
break;
}
}
}
if (!found)
{
textFromCmd(sessionId, true, tr("<105> Call to binary command has no terminator."));
}
}
}
}
void Session::setHookState(bool state)
{
// this is used in Server::attach() to make this class aware of the
// hook state of the currently connected CmdHub.
activeHook = state;
}
bool Session::profileAllowedCmd(const QString &line)
{
// this take in the sent in command line from the client and attempts
// the match it with the patterns defined in the profileCmdList if the
// list is enabled. empty lines are allowed no matter what.
bool ret = true;
// command filtering need to be completely bypassed if there is an
// active hook on the currently attached CmdHub.
if (!activeHook)
{
if (cmdListenabled && !line.isEmpty())
{
bool matched = false;
for (int i = 0; (i < profileCmdList.size()) && !matched; ++i)
{
QRegExp regEx(profileCmdList[i]);
regEx.setPatternSyntax(QRegExp::Wildcard);
if (cmdListCaseSensitive) regEx.setCaseSensitivity(Qt::CaseSensitive);
else regEx.setCaseSensitivity(Qt::CaseInsensitive);
matched = regEx.exactMatch(line);
}
// matched == true at this point indicate that a pattern was found
// of cmdListMode is checked to determine if the command should be
// allowed to run or not.
if (matched && (cmdListMode == CMD_LINES_DISALLOWED_TO_RUN))
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<108> Command rejected by the host."));
ret = false;
}
else if (!matched && (cmdListMode == CMD_LINES_ALLOWED_TO_RUN))
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<108> Command rejected by the host."));
ret = false;
}
else if (matched && (cmdListMode != CMD_LINES_ALLOWED_TO_RUN))
{
textFromCmd(sessionId, true, tr(" "));
textFromCmd(sessionId, true, tr("<108> host bug! - command list mode not recognized. mode: ") + QString::number(cmdListMode));
ret = false;
}
}
}
return ret;
}
void Session::dataFromClient()
{
if (keyOk && !sessionEnding)
{
if (dSize) //stage 5
{
if (bytesAvailable() >= dSize)
{
dataFilter(rdHash->xOR(Hash::DECODE, read(dSize)), flags);
dSize = 0;
bits = 0;
flags = 0;
dataFromClient();
}
}
else if (bits) //stage 4
{
if (bytesAvailable() >= bits / 8)
{
dSize = rdInt(rdHash->xOR(Hash::DECODE, read(bits / 8)));
if (dSize)
{
dataFromClient();
}
else if (flags & TEXT_CH)
{
// 0 on dSize at this point assumes empty text was sent to the
// host so this code will actually locally create empty text
// and send it through dataFilter().
dataFilter(QTextCodec::codecForName("UTF-16LE")->fromUnicode(tr("")), flags);
flags = 0;
bits = 0;
}
else
{
// just like above, this will locally create an empty QByteArray()
// to send through dataFilter().
dataFilter(QByteArray(), flags);
flags = 0;
bits = 0;
}
}
}
else if (bytesAvailable() >= 2) //stage 3
{
QByteArray data = rdHash->xOR(Hash::DECODE, read(2));
bits = (uchar) data[0];
flags = (uchar) data[1];
if ((bits > MAX_BITS) || (bits < 8))
{
bits = 0;
flags = 0;
addIpAction(tr("Out-of-sync event (int bits over maximum or < 8)"), peerAddress().toString());
// the client will must likely end up de-synced with the server
// at this point. the best way to recover will be to re-start
// a new session. (disconnect-reconnect)
}
else
{
dataFromClient();
}
}
}
else if (verOk) //stage 2
{
// SHA3-512 == 64 bytes.
if (bytesAvailable() >= 64)
{
if (rdHash->passHash() == rdHash->xOR(Hash::DECODE, read(64)))
{
// numeric value 1 indicates that the passHash matches with
// the host and will unlock stage 3-5 until the session closes.
// a successful match also resets the ban increment.
keyOk = true;
write(wrInt(1, 8));
waitForBytesWritten();
emit createSlot(sessionId, 0, baseSlot);
emit clearIPBanCount(peerAddress().toString());
}
else
{
// numeric value 2 indicates that the passHash sent in from the
// client is invalid. clients are free to make more attempts at this
// stage but keep in mind that the ban increment will only grow with
// each failed attempt.
addIpAction(tr("Client passHash missmatch"), peerAddress().toString());
write(wrInt(2, 8));
emit incrementIPBan(sessionId, peerAddress().toString());
}
}
}
else
{
if ((bytesAvailable() >= CLIENT_HEADER_LEN) && !sessionEnding) //stage 1
{
// client header format: [3bytes(tag)][2bytes(major)][2bytes(minor)][2bytes(patch)][58bytes(profile)]
// tag = 0x4D, 0x43, 0x49 (MCI)
// major = 16bit little endian int
// minor = 16bit little endian int
// patch = 16bit little endian int
// profile = UTF-16LE string (padded with white spaces to fill 29 max chars)
// note: profile names in this app are case insensitive.
timer->stop();
if (read(3) == QByteArray(SERVER_HEADER_TAG))
{
clientMajor = rdInt(read(2));
clientMinor = rdInt(read(2));
clientPatch = rdInt(read(2));
QByteArray servHeader;
QByteArray reply;
QByteArray key;
QByteArray proName = read(60);
addIpAction(tr("Client version: ") + QString::number(clientMajor) + "."
+ QString::number(clientMinor) + "."
+ QString::number(clientPatch), peerAddress().toString());
if ((clientMajor >= 1) && (clientMinor > 0))
{
QString proStr = QTextCodec::codecForName("UTF-16LE")->toUnicode(proName).trimmed();
addIpAction(tr("Profile name: ") + proStr, peerAddress().toString());
if (loadProfile(proStr, key))
{
reply = wrInt(1, 8);
verOk = true;
addIpAction(tr("Client version and profile ok"), peerAddress().toString());
}
else
{
reply = wrInt(2, 8);
addIpAction(tr("Profile not found"), peerAddress().toString());
}
}
else
{
reply = wrInt(3, 8);
addIpAction(tr("Client version rejected"), peerAddress().toString());
}
QStringList ver = QApplication::applicationVersion().split('.');
servHeader.append(reply);
servHeader.append(wrInt(ver[0].toShort(), 16));
servHeader.append(wrInt(ver[1].toShort(), 16));
servHeader.append(wrInt(ver[2].toShort(), 16));
if (verOk)
{
rdHash = new Hash(key + TO_SERV_SALT, sessionId, this);
wrHash = new Hash(key + FROM_SERV_SALT, sessionId, this);
servHeader.append(rdHash->seqBytes());
servHeader.append(wrHash->seqBytes());
servHeader.append(rdHash->sessionIdBytes());
if (servHeader.size() != SERVER_HEADER_LEN)
{
addIpAction(tr("Host bug! - header len != ") + QString::number(SERVER_HEADER_LEN), peerAddress().toString());
}
write(servHeader);
}
else
{
servHeader.append(QByteArray(NUM_OF_SEQ + 4, 0));
write(servHeader);
waitForBytesWritten();
sessionEnding = true;
emit deleteSession(sessionId);
}
}
else
{
addIpAction(tr("Invalid tag"), peerAddress().toString());
sessionEnding = true;
emit deleteSession(sessionId);
}
}
}
}
|
gpl-3.0
|
ShawnTe/daily-planner-rails-api
|
app/controllers/users_controller.rb
|
112
|
class UsersController < ApplicationController
def index
users = User.all
render json: users
end
end
|
gpl-3.0
|
olimungo/planning-poker
|
src/pages/common/handlers/results-handler/index.ts
|
35
|
export * from './results.handler';
|
gpl-3.0
|
IcySon55/Kuriimu
|
src/Kontract/Compression/LZSSVLE.cs
|
2086
|
using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Kontract.IO;
namespace Kontract.Compression
{
public class LZSSVLE
{
public static byte[] Decompress(Stream input, bool leaveOpen = false)
{
using (var br = new BinaryReader(input, Encoding.Default, leaveOpen))
{
Tuple<int, int> GetNibbles(byte b) => new Tuple<int, int>(b >> 4, b & 0xF);
int ReadVLC(int seed = 0)
{
while (true)
{
var b = br.ReadByte();
seed = (seed << 7) | (b / 2);
if (b % 2 != 0) return seed;
}
}
var filesize = ReadVLC();
var unk1 = ReadVLC(); // filetype maybe???
var unk2 = ReadVLC(); // compression type = 1 (LZSS?)
var buffer = new List<byte>();
while (buffer.Count < filesize)
{
// literal
var copiesSize = GetNibbles(br.ReadByte());
var copies = copiesSize.Item1;
var size = copiesSize.Item2;
if (size == 0) size = ReadVLC();
if (copies == 0) copies = ReadVLC();
buffer.AddRange(br.ReadBytes(size));
// copy stuff
while (copies-- > 0)
{
var lengthOffset = GetNibbles(br.ReadByte());
var length = lengthOffset.Item1;
var offset = lengthOffset.Item2;
if (offset % 2 == 0) offset = ReadVLC(offset / 2) * 2;
else offset >>= 1;
if (length == 0) length = ReadVLC(length);
while (length-- >= 0) buffer.Add(buffer[buffer.Count - offset / 2 - 1]);
}
}
return buffer.ToArray();
}
}
}
}
|
gpl-3.0
|
bema2004sw/pyrocms
|
application/modules/users/views/admin/form.php
|
1262
|
<? if($this->uri->segment(3,'add') == 'add'): ?>
<h2>Create user</h2>
<? else: ?>
<h2>Edit user "<?= $member->full_name; ?>"</h2>
<? endif; ?>
<?=form_open($this->uri->uri_string()); ?>
<fieldset>
<legend>Details</legend>
<div class="field">
<label for="first_name">First Name</label>
<?= form_input('first_name', $member->first_name, 'class="text"'); ?>
</div>
<div class="field">
<label for="first_name">Surname</label>
<?= form_input('last_name', $member->last_name, 'class="text"'); ?>
</div>
<div class="field">
<label for="email">E-mail</label>
<?= form_input('email', $member->email, 'class="text"'); ?>
</div>
<div class="field">
<label for="active">Activate</label>
<?= form_checkbox('is_active', 1, $member->is_active == 1); ?>
</div>
</fieldset>
<fieldset>
<legend>Password</legend>
<div class="field">
<label for="password">Password</label>
<?= form_password('password', '', 'class="text"'); ?>
</div>
<div class="field">
<label for="confirm_password">Confirm Password</label>
<?= form_password('confirm_password', '', 'class="text"'); ?>
</div>
</fieldset>
<? $this->load->view('admin/layout_fragments/table_buttons', array('buttons' => array('save', 'cancel') )); ?>
<?=form_close(); ?>
|
gpl-3.0
|
jkonecny12/ShaderMan
|
uniform/dialogs/uniformvariableeditor.h
|
1132
|
#ifndef UNIFORMVARIABLEEDITOR_H
#define UNIFORMVARIABLEEDITOR_H
#include <QDialog>
#include <QDebug>
#include <QComboBox>
#include <QLineEdit>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollBar>
#include <QWidget>
#include "setvariablewidget.h"
namespace Ui {
class UniformVariableEditor;
}
class UniformVariableEditor : public QDialog
{
Q_OBJECT
public:
struct UniformAttachment {
QString uniformName;
QString programName;
QString variableName;
};
public:
explicit UniformVariableEditor(QWidget *parent = 0);
~UniformVariableEditor();
void setUniformSettings(QList<UniformAttachment> list);
QList<UniformAttachment> getUniformSettings();
QList<UniformAttachment> getRemovedSettings();
private:
void customConnect();
private:
Ui::UniformVariableEditor *ui;
const int layerIncY;
int layerY;
QVBoxLayout* vbox;
QList<SetVariableWidget*> lines;
QList<UniformAttachment> removed;
private slots:
void addNewUniformWidgetLine();
void removeUniformWidgetLine(QWidget* widget);
};
#endif // UNIFORMVARIABLEEDITOR_H
|
gpl-3.0
|
team-vigir/vigir_footstep_planning_basics
|
vigir_footstep_planning_plugins/src/plugin_aggregators/world_model.cpp
|
2257
|
#include <vigir_footstep_planning_plugins/plugin_aggregators/world_model.h>
namespace vigir_footstep_planning
{
WorldModel::WorldModel()
: ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>("WorldModel")
{
}
void WorldModel::loadPlugins(bool print_warning)
{
ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::loadPlugins(print_warning);
// get terrain model
vigir_pluginlib::PluginManager::getPlugin(terrain_model_);
if (terrain_model_)
{
ROS_INFO("[WorldModel] Found terrain model:");
ROS_INFO(" %s (%s)", terrain_model_->getName().c_str(), terrain_model_->getTypeClass().c_str());
}
}
bool WorldModel::loadParams(const vigir_generic_params::ParameterSet& params)
{
bool result = ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::loadParams(params);
if (terrain_model_)
result &= terrain_model_->loadParams(params);
return result;
}
void WorldModel::resetPlugins()
{
ExtendedPluginAggregator<WorldModel, CollisionCheckPlugin>::resetPlugins();
if (terrain_model_)
terrain_model_->reset();
}
bool WorldModel::isAccessible(const State& s) const
{
for (CollisionCheckPlugin::Ptr plugin : getPlugins())
{
if (plugin && plugin->isCollisionCheckAvailable() && !plugin->isAccessible(s))
return false;
}
return true;
}
bool WorldModel::isAccessible(const State& next, const State& current) const
{
for (CollisionCheckPlugin::Ptr plugin : getPlugins())
{
if (plugin && plugin->isCollisionCheckAvailable() && !plugin->isAccessible(next, current))
return false;
}
return true;
}
void WorldModel::useTerrainModel(bool enabled)
{
use_terrain_model_ = enabled;
}
bool WorldModel::isTerrainModelAvailable() const
{
return terrain_model_ && terrain_model_->isTerrainModelAvailable();
}
TerrainModelPlugin::ConstPtr WorldModel::getTerrainModel() const
{
return terrain_model_;
}
bool WorldModel::getHeight(double x, double y, double& height) const
{
if (!use_terrain_model_ || !isTerrainModelAvailable())
return true;
return terrain_model_->getHeight(x, y, height);
}
bool WorldModel::update3DData(State& s) const
{
if (!use_terrain_model_ || !isTerrainModelAvailable())
return true;
return terrain_model_->update3DData(s);
}
}
|
gpl-3.0
|
Xprima-ERP/odoo_addons
|
xpr_xis_connector/res_users.py
|
1160
|
# -*- encoding: utf-8 -*-
#
# OpenERP, Open Source Management Solution
# This module copyright (C) 2014 Savoir-faire Linux
# (<http://www.savoirfairelinux.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
import logging
from openerp.osv import osv, fields
_logger = logging.getLogger(__name__)
class res_users(osv.osv):
_inherit = "res.users"
_columns = {
'xis_user_external_id': fields.integer('XIS external user',
required=True),
}
|
gpl-3.0
|
IserveU/IserveU
|
tests/unit/Community/Interface/DeleteCommunityApiTest.php
|
729
|
<?php
include_once 'CommunityApi.php';
use Illuminate\Foundation\Testing\DatabaseTransactions;
class DeleteCommunityApiTest extends CommunityApi
{
use DatabaseTransactions;
public function setUp()
{
parent::setUp();
}
/////////////////////////////////////////////////////////// CORRECT RESPONSES
/** @test ******************/
public function delete_community_correct_response()
{
$this->signInAsRole('administrator');
$community = factory(App\Community::class)->create();
$this->delete('/api/community/'.$community->slug)
->assertResponseStatus(200);
}
/////////////////////////////////////////////////////////// INCORRECT RESPONSES
}
|
gpl-3.0
|
gios/angular-modular-seed
|
app/app.modules.js
|
542
|
/*global require,module,console,angular */
require("angular/angular");
require("angular-route/angular-route");
angular.module("RegistrationApp", ["ngRoute"]);
angular.module("RegistrationApp").controller("RegistrationCtrl", require("./components/registration/controller"));
angular.module("RegistrationApp").directive("myRegistration", require("./components/registration/directive"));
angular.module("MainApp", [
"RegistrationApp"
]);
angular.module("MainApp").config(["$routeProvider", "$locationProvider", require("./app.routes")]);
|
gpl-3.0
|
DJVUpp/Desktop
|
djuvpp-djvureader-_linux-f9cd57d25c2f/DjVuReader++/src/com/lizardtech/djvubean/outline/ImageListCellRenderer.java
|
2058
|
package com.lizardtech.djvubean.outline;
import java.awt.Color;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
public class ImageListCellRenderer implements ListCellRenderer
{
/**
* From <a href="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:" title="http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:">http://java.sun.com/javase/6/docs/api/javax/swing/ListCellRenderer.html:</a>
*
* Return a component that has been configured to display the specified value.
* That component's paint method is then called to "render" the cell.
* If it is necessary to compute the dimensions of a list because the list cells do not have a fixed size,
* this method is called to generate a component on which getPreferredSize can be invoked.
*
* jlist - the jlist we're painting
* value - the value returned by list.getModel().getElementAt(index).
* cellIndex - the cell index
* isSelected - true if the specified cell is currently selected
* cellHasFocus - true if the cell has focus
*/
public Component getListCellRendererComponent(JList jlist,
Object value,
int cellIndex,
boolean isSelected,
boolean cellHasFocus)
{
if (value instanceof JPanel)
{
Component component = (Component) value;
component.setForeground (Color.white);
component.setBackground (isSelected ? UIManager.getColor("Table.focusCellForeground") : Color.white);
return component;
}
else
{
// TODO - I get one String here when the JList is first rendered; proper way to deal with this?
//System.out.println("Got something besides a JPanel: " + value.getClass().getCanonicalName());
return new JLabel("???");
}
}}
|
gpl-3.0
|
hgtonight/Plugin-DiscussionMessages
|
README.md
|
410
|
Discussion Inserts
===================
A Vanilla Forums plugin that attaches an insert to a specific discussion.
It is released under the GPLv3 and may be released under a different license with permission.
A special thanks the phreak @ VanillaSkins.com for sponsorship.
Install
=======
1. Drop the DiscussionInserts folder into your vanilla/plugins folder.
2. Enable the plugin in your dashboard
3. Enjoy!
|
gpl-3.0
|
cgwalters/texinfo-git-mirror
|
texi2html/test/singular_manual/res/singular_httex/newtonpoly.html
|
7795
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Created by texi2html, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Singular 2-0-4 Manual: D.5.5.15 newtonpoly</title>
<meta name="description" content="Singular 2-0-4 Manual: D.5.5.15 newtonpoly">
<meta name="keywords" content="Singular 2-0-4 Manual: D.5.5.15 newtonpoly">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="texi2html">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
@import "sing_tex4ht_tex.css";
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smalllisp {margin-left: 3.2em}
pre.display {font-family: serif}
pre.format {font-family: serif}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: serif; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: serif; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:pre}
span.nolinebreak {white-space:pre}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" background="../singular_images/Mybg.png">
<a name="newtonpoly"></a>
<table border="0" cellpadding="0" cellspacing="0">
<tr valign="top">
<td align="left">
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr valign="top" align="left">
<td valign="middle" align="left"> <a href="index.htm"><img
src="../singular_images/singular-icon-transparent.png" width="50"
border="0" alt="Top"></a>
</td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="delta.html#delta" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.5.14 delta" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="is_005fNND.html#is_005fNND" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.5.16 is_NND" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="hnoether_005flib.html#hnoether_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.5 hnoether_lib" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td>
</tr>
<tr valign="top" align="left">
<td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td>
</tr>
</table>
</td>
<td align="left">
<a name="newtonpoly-1"></a>
<h4 class="subsubsection">D.5.5.15 newtonpoly</h4>
<a name="index-newtonpoly"></a>
<p>Procedure from library <code>hnoether.lib</code> (see <a href="hnoether_005flib.html#hnoether_005flib">hnoether_lib</a>).
</p>
<dl compact="compact">
<dt><strong>Usage:</strong></dt>
<dd><p>newtonpoly(f); f poly
</p>
</dd>
<dt><strong>Assume:</strong></dt>
<dd><p>basering has exactly two variables; <br>
f is convenient, that is, f(x,0) != 0 != f(0,y).
</p>
</dd>
<dt><strong>Return:</strong></dt>
<dd><p>list of intvecs (= coordinates x,y of the Newton polygon of f).
</p>
</dd>
<dt><strong>Note:</strong></dt>
<dd><p>Procedure uses <code>execute</code>; this can be avoided by calling
<code>newtonpoly(f,1)</code> if the ordering of the basering is <code>ls</code>.
</p>
<a name="index-Newton-polygon"></a>
</dd>
</dl>
<p><strong>Example:</strong>
</p><div class="smallexample">
<pre class="smallexample">LIB "hnoether.lib";
ring r=0,(x,y),ls;
poly f=x5+2x3y-x2y2+3xy5+y6-y7;
newtonpoly(f);
→ [1]:
→ 0,6
→ [2]:
→ 2,2
→ [3]:
→ 3,1
→ [4]:
→ 5,0
</pre></div>
</td>
</tr>
</table>
<hr>
<table class="header" cellpadding="1" cellspacing="1" border="0">
<tr><td valign="middle" align="left"> <a href="index.htm"><img
src="../singular_images/singular-icon-transparent.png" width="50"
border="0" alt="Top"></a>
</td>
<td valign="middle" align="left"><a href="delta.html#delta" title="Previous section in reading order"><img src="../singular_images/a_left.png" border="0" alt="Back: D.5.5.14 delta" align="middle"></a></td>
<td valign="middle" align="left"><a href="is_005fNND.html#is_005fNND" title="Next section in reading order"><img src="../singular_images/a_right.png" border="0" alt="Forward: D.5.5.16 is_NND" align="middle"></a></td>
<td valign="middle" align="left"><a href="SINGULAR-libraries.html#SINGULAR-libraries" title="Beginning of this chapter or previous chapter"><img src="../singular_images/a_leftdouble.png" border="0" alt="FastBack: Appendix D SINGULAR libraries" align="middle"></a></td>
<td valign="middle" align="left"><a href="Release-Notes.html#Release-Notes" title="Next chapter"><img src="../singular_images/a_rightdouble.png" border="0" alt="FastForward: E Release Notes" align="middle"></a></td>
<td valign="middle" align="left"><a href="hnoether_005flib.html#hnoether_005flib" title="Up section"><img src="../singular_images/a_up.png" border="0" alt="Up: D.5.5 hnoether_lib" align="middle"></a></td>
<td valign="middle" align="left"><a href="index.htm#Preface" title="Cover (top) of document"><img src="../singular_images/a_top.png" border="0" alt="Top: 1 Preface" align="middle"></a></td>
<td valign="middle" align="left"><a href="sing_toc.htm#SEC_Contents" title="Table of contents"><img src="../singular_images/a_tableofcon.png" border="0" alt="Contents: Table of Contents" align="middle"></a></td>
<td valign="middle" align="left"><a href="Index.html#Index" title="Index"><img src="../singular_images/a_index.png" border="0" alt="Index: F Index" align="middle"></a></td>
<td valign="middle" align="left"><a href="sing_abt.htm#SEC_About" title="About (help)"><img src="../singular_images/a_help.png" border="0" alt="About: About This Document" align="middle"></a></td>
</tr></table>
<font size="-1">
User manual for <a href="http://www.singular.uni-kl.de/"><i>Singular</i></a> version 2-0-4, October 2002,
generated by <a href="http://www.gnu.org/software/texinfo/"><i>texi2html</i></a>.
</font>
</body>
</html>
|
gpl-3.0
|
pizza2004/OpenRCT2
|
src/openrct2/rct12/RCT12.h
|
25235
|
/*****************************************************************************
* Copyright (c) 2014-2020 OpenRCT2 developers
*
* For a complete list of all authors, please refer to contributors.md
* Interested in contributing? Visit https://github.com/OpenRCT2/OpenRCT2
*
* OpenRCT2 is licensed under the GNU General Public License version 3.
*****************************************************************************/
#pragma once
// Structures shared between both RCT1 and RCT2.
#include "../common.h"
#include "../object/Object.h"
#include <string>
#include <string_view>
constexpr const uint8_t RCT12_MAX_RIDES_IN_PARK = 255;
constexpr const uint8_t RCT12_MAX_AWARDS = 4;
constexpr const uint8_t RCT12_MAX_NEWS_ITEMS = 61;
constexpr const uint8_t RCT12_MAX_STATIONS_PER_RIDE = 4;
constexpr const uint8_t RCT12_MAX_PEEP_SPAWNS = 2;
constexpr const uint8_t RCT12_MAX_PARK_ENTRANCES = 4;
// The number of elements in the patrol_areas array per staff member. Every bit in the array represents a 4x4 square.
// In RCT1, that's an 8-bit array. 8 * 128 = 1024 bits, which is also the number of 4x4 squares on a 128x128 map.
// For RCT2, it's a 32-bit array. 32 * 128 = 4096 bits, which is also the number of 4x4 squares on a 256x256 map.
constexpr const uint8_t RCT12_PATROL_AREA_SIZE = 128;
constexpr const uint8_t RCT12_STAFF_TYPE_COUNT = 4;
constexpr const uint8_t RCT12_NUM_COLOUR_SCHEMES = 4;
constexpr const uint8_t RCT12_MAX_VEHICLE_COLOURS = 32;
constexpr const uint8_t RCT12_SOUND_ID_NULL = 0xFF;
constexpr const uint8_t RCT12_EXPENDITURE_TABLE_MONTH_COUNT = 16;
constexpr const uint8_t RCT12_EXPENDITURE_TYPE_COUNT = 14;
constexpr const uint8_t RCT12_FINANCE_GRAPH_SIZE = 128;
constexpr const uint16_t RCT12_MAX_USER_STRINGS = 1024;
constexpr const uint8_t RCT12_USER_STRING_MAX_LENGTH = 32;
constexpr const uint8_t RCT12_PEEP_MAX_THOUGHTS = 5;
constexpr const uint8_t RCT12_RIDE_ID_NULL = 255;
constexpr const uint16_t RCT12_RIDE_MEASUREMENT_MAX_ITEMS = 4800;
constexpr uint16_t const RCT12_MAX_INVERSIONS = 31;
constexpr uint16_t const RCT12_MAX_GOLF_HOLES = 31;
constexpr uint16_t const RCT12_MAX_HELICES = 31;
constexpr uint8_t RCT12_BANNER_INDEX_NULL = std::numeric_limits<uint8_t>::max();
constexpr const uint8_t RCT12_TILE_ELEMENT_SURFACE_EDGE_STYLE_MASK = 0xE0; // in RCT12TileElement.properties.surface.slope
constexpr const uint8_t RCT12_TILE_ELEMENT_SURFACE_WATER_HEIGHT_MASK = 0x1F; // in RCT12TileElement.properties.surface.terrain
constexpr const uint8_t RCT12_TILE_ELEMENT_SURFACE_TERRAIN_MASK = 0xE0; // in RCT12TileElement.properties.surface.terrain
constexpr const uint16_t RCT12_TILE_ELEMENT_LARGE_TYPE_MASK = 0x3FF;
constexpr uint16_t const RCT12_XY8_UNDEFINED = 0xFFFF;
using RCT12ObjectEntryIndex = uint8_t;
constexpr const RCT12ObjectEntryIndex RCT12_OBJECT_ENTRY_INDEX_NULL = 255;
// Everything before this point has been researched
constexpr const uint32_t RCT12_RESEARCHED_ITEMS_SEPARATOR = 0xFFFFFFFF;
// Everything before this point and after separator still requires research
constexpr const uint32_t RCT12_RESEARCHED_ITEMS_END = 0xFFFFFFFE;
// Extra end of list entry. Leftover from RCT1.
constexpr const uint32_t RCT12_RESEARCHED_ITEMS_END_2 = 0xFFFFFFFD;
constexpr const uint8_t RCT12_MAX_ELEMENT_HEIGHT = 255;
constexpr const uint16_t RCT12_PEEP_SPAWN_UNDEFINED = 0xFFFF;
enum class RCT12TrackDesignVersion : uint8_t
{
TD4,
TD4_AA,
TD6,
unknown
};
enum
{
RCT12_TILE_ELEMENT_FLAG_GHOST = (1 << 4),
RCT12_TILE_ELEMENT_FLAG_BROKEN = (1 << 5),
RCT12_TILE_ELEMENT_FLAG_BLOCK_BRAKE_CLOSED = (1 << 5),
RCT12_TILE_ELEMENT_FLAG_INDESTRUCTIBLE_TRACK_PIECE = (1 << 6),
RCT12_TILE_ELEMENT_FLAG_BLOCKED_BY_VEHICLE = (1 << 6),
RCT12_TILE_ELEMENT_FLAG_LARGE_SCENERY_ACCOUNTED = (1 << 6),
RCT12_TILE_ELEMENT_FLAG_LAST_TILE = (1 << 7)
};
enum
{
RCT12_TRACK_ELEMENT_TYPE_FLAG_CHAIN_LIFT = 1 << 7,
};
enum
{
RCT12_TRACK_ELEMENT_SEQUENCE_STATION_INDEX_MASK = 0b01110000,
RCT12_TRACK_ELEMENT_SEQUENCE_SEQUENCE_MASK = 0b00001111,
RCT12_TRACK_ELEMENT_SEQUENCE_TAKING_PHOTO_MASK = 0b11110000,
};
enum
{
// Not anything to do with colour but uses
// that field in the tile element
// Used for multi-dimension coaster
RCT12_TRACK_ELEMENT_COLOUR_FLAG_INVERTED = (1 << 2),
// Used for giga coaster
RCT12_TRACK_ELEMENT_COLOUR_FLAG_CABLE_LIFT = (1 << 3),
RCT12_TRACK_ELEMENT_DOOR_A_MASK = 0b00011100,
RCT12_TRACK_ELEMENT_DOOR_B_MASK = 0b11100000,
};
// Masks and flags for values stored in TileElement.properties.path.type
enum
{
RCT12_FOOTPATH_PROPERTIES_SLOPE_DIRECTION_MASK = (1 << 0) | (1 << 1),
RCT12_FOOTPATH_PROPERTIES_FLAG_IS_SLOPED = (1 << 2),
RCT12_FOOTPATH_PROPERTIES_FLAG_HAS_QUEUE_BANNER = (1 << 3),
RCT12_FOOTPATH_PROPERTIES_TYPE_MASK = (1 << 4) | (1 << 5) | (1 << 6) | (1 << 7),
};
// Masks and flags for values stored in in RCT12TileElement.properties.path.additions
enum
{
RCT12_FOOTPATH_PROPERTIES_ADDITIONS_TYPE_MASK = (1 << 0) | (1 << 1) | (1 << 2) | (1 << 3),
// The most significant bit in this mask will always be zero, since rides can only have 4 stations
RCT12_FOOTPATH_PROPERTIES_ADDITIONS_STATION_INDEX_MASK = (1 << 4) | (1 << 5) | (1 << 6),
RCT12_FOOTPATH_PROPERTIES_ADDITIONS_FLAG_GHOST = (1 << 7),
};
enum
{
RCT12_STATION_STYLE_PLAIN,
RCT12_STATION_STYLE_WOODEN,
RCT12_STATION_STYLE_CANVAS_TENT,
RCT12_STATION_STYLE_CASTLE_GREY,
RCT12_STATION_STYLE_CASTLE_BROWN,
RCT12_STATION_STYLE_JUNGLE,
RCT12_STATION_STYLE_LOG_CABIN,
RCT12_STATION_STYLE_CLASSICAL,
RCT12_STATION_STYLE_ABSTRACT,
RCT12_STATION_STYLE_SNOW,
RCT12_STATION_STYLE_PAGODA,
RCT12_STATION_STYLE_SPACE,
RCT12_STATION_STYLE_INVISIBLE, // Added by OpenRCT2
};
#pragma pack(push, 1)
struct RCT12xy8
{
union
{
struct
{
uint8_t x, y;
};
uint16_t xy;
};
bool isNull() const
{
return xy == RCT12_XY8_UNDEFINED;
}
void setNull()
{
xy = RCT12_XY8_UNDEFINED;
}
};
assert_struct_size(RCT12xy8, 2);
/* Maze Element entry size: 0x04 */
struct rct_td46_maze_element
{
union
{
uint32_t all;
struct
{
int8_t x;
int8_t y;
union
{
uint16_t maze_entry;
struct
{
uint8_t direction;
uint8_t type;
};
};
};
};
};
assert_struct_size(rct_td46_maze_element, 0x04);
/* Track Element entry size: 0x02 */
struct rct_td46_track_element
{
uint8_t type; // 0x00
uint8_t flags; // 0x01
};
assert_struct_size(rct_td46_track_element, 0x02);
struct rct12_award
{
uint16_t time;
uint16_t type;
};
assert_struct_size(rct12_award, 4);
/**
* A single news item / message.
* size: 0x10C
*/
struct rct12_news_item
{
uint8_t Type;
uint8_t Flags;
uint32_t Assoc;
uint16_t Ticks;
uint16_t MonthYear;
uint8_t Day;
uint8_t pad_0B;
char Text[256];
};
assert_struct_size(rct12_news_item, 0x10C);
struct rct12_xyzd8
{
uint8_t x, y, z, direction;
};
assert_struct_size(rct12_xyzd8, 4);
struct rct12_peep_spawn
{
uint16_t x;
uint16_t y;
uint8_t z;
uint8_t direction;
};
assert_struct_size(rct12_peep_spawn, 6);
enum class RCT12TileElementType : uint8_t
{
Surface = (0 << 2),
Path = (1 << 2),
Track = (2 << 2),
SmallScenery = (3 << 2),
Entrance = (4 << 2),
Wall = (5 << 2),
LargeScenery = (6 << 2),
Banner = (7 << 2),
Corrupt = (8 << 2),
EightCarsCorrupt14 = (14 << 2),
EightCarsCorrupt15 = (15 << 2),
};
struct RCT12SurfaceElement;
struct RCT12PathElement;
struct RCT12TrackElement;
struct RCT12SmallSceneryElement;
struct RCT12LargeSceneryElement;
struct RCT12WallElement;
struct RCT12EntranceElement;
struct RCT12BannerElement;
struct RCT12CorruptElement;
struct RCT12EightCarsCorruptElement14;
struct RCT12EightCarsCorruptElement15;
struct RCT12TileElementBase
{
uint8_t type; // 0
uint8_t flags; // 1. Upper nibble: flags. Lower nibble: occupied quadrants (one bit per quadrant).
uint8_t base_height; // 2
uint8_t clearance_height; // 3
uint8_t GetType() const;
uint8_t GetDirection() const;
void SetDirection(uint8_t direction);
uint8_t GetOccupiedQuadrants() const;
void SetOccupiedQuadrants(uint8_t quadrants);
bool IsLastForTile() const;
void SetLastForTile(bool on);
bool IsGhost() const;
void SetGhost(bool isGhost);
};
/**
* Map element structure
* size: 0x08
*/
struct RCT12TileElement : public RCT12TileElementBase
{
uint8_t pad_04[4];
template<typename TType, RCT12TileElementType TClass> TType* as() const
{
return static_cast<RCT12TileElementType>(GetType()) == TClass
? reinterpret_cast<TType*>(const_cast<RCT12TileElement*>(this))
: nullptr;
}
RCT12SurfaceElement* AsSurface() const
{
return as<RCT12SurfaceElement, RCT12TileElementType::Surface>();
}
RCT12PathElement* AsPath() const
{
return as<RCT12PathElement, RCT12TileElementType::Path>();
}
RCT12TrackElement* AsTrack() const
{
return as<RCT12TrackElement, RCT12TileElementType::Track>();
}
RCT12SmallSceneryElement* AsSmallScenery() const
{
return as<RCT12SmallSceneryElement, RCT12TileElementType::SmallScenery>();
}
RCT12LargeSceneryElement* AsLargeScenery() const
{
return as<RCT12LargeSceneryElement, RCT12TileElementType::LargeScenery>();
}
RCT12WallElement* AsWall() const
{
return as<RCT12WallElement, RCT12TileElementType::Wall>();
}
RCT12EntranceElement* AsEntrance() const
{
return as<RCT12EntranceElement, RCT12TileElementType::Entrance>();
}
RCT12BannerElement* AsBanner() const
{
return as<RCT12BannerElement, RCT12TileElementType::Banner>();
}
void ClearAs(uint8_t newType);
uint8_t GetBannerIndex();
};
assert_struct_size(RCT12TileElement, 8);
struct RCT12SurfaceElement : RCT12TileElementBase
{
private:
uint8_t slope; // 4 0xE0 Edge Style, 0x1F Slope
uint8_t terrain; // 5 0xE0 Terrain Style, 0x1F Water height
uint8_t grass_length; // 6
uint8_t ownership; // 7
public:
uint8_t GetSlope() const;
uint32_t GetSurfaceStyle() const;
uint32_t GetEdgeStyle() const;
uint8_t GetGrassLength() const;
uint8_t GetOwnership() const;
uint32_t GetWaterHeight() const;
uint8_t GetParkFences() const;
bool HasTrackThatNeedsWater() const;
void SetSlope(uint8_t newSlope);
void SetSurfaceStyle(uint32_t newStyle);
void SetEdgeStyle(uint32_t newStyle);
void SetGrassLength(uint8_t newLength);
void SetOwnership(uint8_t newOwnership);
void SetWaterHeight(uint32_t newWaterHeight);
void SetParkFences(uint8_t newParkFences);
void SetHasTrackThatNeedsWater(bool on);
};
assert_struct_size(RCT12SurfaceElement, 8);
struct RCT12PathElement : RCT12TileElementBase
{
private:
uint8_t entryIndex; // 4, 0xF0 Path type, 0x08 Ride sign, 0x04 Set when path is sloped, 0x03 Rotation
uint8_t additions; // 5, 0bGSSSAAAA: G = Ghost, S = station index, A = addition (0 means no addition)
uint8_t edges; // 6
union
{
uint8_t additionStatus; // 7
uint8_t rideIndex;
};
public:
RCT12ObjectEntryIndex GetEntryIndex() const;
uint8_t GetQueueBannerDirection() const;
bool IsSloped() const;
uint8_t GetSlopeDirection() const;
uint8_t GetRideIndex() const;
uint8_t GetStationIndex() const;
bool IsWide() const;
bool IsQueue() const;
bool HasQueueBanner() const;
uint8_t GetEdges() const;
uint8_t GetCorners() const;
uint8_t GetAddition() const;
bool AdditionIsGhost() const;
uint8_t GetAdditionStatus() const;
uint8_t GetRCT1PathType() const;
uint8_t GetRCT1SupportType() const;
void SetPathEntryIndex(RCT12ObjectEntryIndex newIndex);
void SetQueueBannerDirection(uint8_t direction);
void SetSloped(bool isSloped);
void SetSlopeDirection(uint8_t newSlope);
void SetRideIndex(uint8_t newRideIndex);
void SetStationIndex(uint8_t newStationIndex);
void SetWide(bool isWide);
void SetIsQueue(bool isQueue);
void SetHasQueueBanner(bool hasQueueBanner);
void SetEdges(uint8_t newEdges);
void SetCorners(uint8_t newCorners);
void SetAddition(uint8_t newAddition);
void SetAdditionIsGhost(bool isGhost);
void SetAdditionStatus(uint8_t newStatus);
bool IsBroken() const;
void SetIsBroken(bool isBroken);
bool IsBlockedByVehicle() const;
void SetIsBlockedByVehicle(bool isBlocked);
};
assert_struct_size(RCT12PathElement, 8);
struct RCT12TrackElement : RCT12TileElementBase
{
private:
uint8_t trackType; // 4
union
{
struct
{
// The lower 4 bits are the track sequence.
// The upper 4 bits are either station bits or on-ride photo bits.
//
// Station bits:
// - Bit 8 marks green light
// - Bit 5-7 are station index.
//
// On-ride photo bits:
// - Bits 7 and 8 are never set
// - Bits 5 and 6 are set when a vehicle triggers the on-ride photo and act like a countdown from 3.
// - If any of the bits 5-8 are set, the game counts it as a photo being taken.
uint8_t sequence; // 5.
uint8_t colour; // 6
};
uint16_t mazeEntry; // 5
};
uint8_t rideIndex; // 7
public:
uint8_t GetTrackType() const;
uint8_t GetSequenceIndex() const;
uint8_t GetRideIndex() const;
uint8_t GetColourScheme() const;
uint8_t GetStationIndex() const;
bool HasChain() const;
bool HasCableLift() const;
bool IsInverted() const;
uint8_t GetBrakeBoosterSpeed() const;
bool HasGreenLight() const;
uint8_t GetSeatRotation() const;
uint16_t GetMazeEntry() const;
uint8_t GetPhotoTimeout() const;
// Used in RCT1, will be reintroduced at some point.
// (See https://github.com/OpenRCT2/OpenRCT2/issues/7059)
uint8_t GetDoorAState() const;
uint8_t GetDoorBState() const;
void SetTrackType(uint8_t newEntryIndex);
void SetSequenceIndex(uint8_t newSequenceIndex);
void SetRideIndex(uint8_t newRideIndex);
void SetColourScheme(uint8_t newColourScheme);
void SetStationIndex(uint8_t newStationIndex);
void SetHasChain(bool on);
void SetHasCableLift(bool on);
void SetInverted(bool inverted);
bool BlockBrakeClosed() const;
void SetBlockBrakeClosed(bool isClosed);
void SetBrakeBoosterSpeed(uint8_t speed);
void SetHasGreenLight(uint8_t greenLight);
void SetSeatRotation(uint8_t newSeatRotation);
void SetMazeEntry(uint16_t newMazeEntry);
void SetPhotoTimeout(uint8_t newValue);
bool IsIndestructible() const;
void SetIsIndestructible(bool isIndestructible);
};
assert_struct_size(RCT12TrackElement, 8);
struct RCT12SmallSceneryElement : RCT12TileElementBase
{
private:
uint8_t entryIndex; // 4
uint8_t age; // 5
uint8_t colour_1; // 6
uint8_t colour_2; // 7
public:
RCT12ObjectEntryIndex GetEntryIndex() const;
uint8_t GetAge() const;
uint8_t GetSceneryQuadrant() const;
colour_t GetPrimaryColour() const;
colour_t GetSecondaryColour() const;
bool NeedsSupports() const;
void SetEntryIndex(RCT12ObjectEntryIndex newIndex);
void SetAge(uint8_t newAge);
void SetSceneryQuadrant(uint8_t newQuadrant);
void SetPrimaryColour(colour_t colour);
void SetSecondaryColour(colour_t colour);
void SetNeedsSupports();
};
assert_struct_size(RCT12SmallSceneryElement, 8);
struct RCT12LargeSceneryElement : RCT12TileElementBase
{
private:
uint16_t entryIndex; // 4
uint8_t colour[2]; // 6
public:
uint32_t GetEntryIndex() const;
uint16_t GetSequenceIndex() const;
colour_t GetPrimaryColour() const;
colour_t GetSecondaryColour() const;
uint8_t GetBannerIndex() const;
void SetEntryIndex(uint32_t newIndex);
void SetSequenceIndex(uint16_t sequence);
void SetPrimaryColour(colour_t colour);
void SetSecondaryColour(colour_t colour);
void SetBannerIndex(uint8_t newIndex);
};
assert_struct_size(RCT12LargeSceneryElement, 8);
struct RCT12WallElement : RCT12TileElementBase
{
private:
uint8_t entryIndex; // 4
union
{
uint8_t colour_3; // 5
uint8_t banner_index; // 5
};
uint8_t colour_1; // 6 0b_2221_1111 2 = colour_2 (uses flags for rest of colour2), 1 = colour_1
uint8_t animation; // 7 0b_dfff_ft00 d = direction, f = frame num, t = across track flag (not used)
public:
RCT12ObjectEntryIndex GetEntryIndex() const;
uint8_t GetSlope() const;
colour_t GetPrimaryColour() const;
colour_t GetSecondaryColour() const;
colour_t GetTertiaryColour() const;
uint8_t GetAnimationFrame() const;
uint8_t GetBannerIndex() const;
bool IsAcrossTrack() const;
bool AnimationIsBackwards() const;
uint32_t GetRawRCT1WallTypeData() const;
int32_t GetRCT1WallType(int32_t edge) const;
colour_t GetRCT1WallColour() const;
void SetEntryIndex(RCT12ObjectEntryIndex newIndex);
void SetSlope(uint8_t newslope);
void SetPrimaryColour(colour_t newColour);
void SetSecondaryColour(colour_t newColour);
void SetTertiaryColour(colour_t newColour);
void SetAnimationFrame(uint8_t frameNum);
void SetBannerIndex(uint8_t newIndex);
void SetAcrossTrack(bool acrossTrack);
void SetAnimationIsBackwards(bool isBackwards);
};
assert_struct_size(RCT12WallElement, 8);
struct RCT12EntranceElement : RCT12TileElementBase
{
private:
uint8_t entranceType; // 4
uint8_t index; // 5. 0bUSSS????, S = station index.
uint8_t pathType; // 6
uint8_t rideIndex; // 7
public:
uint8_t GetEntranceType() const;
uint8_t GetRideIndex() const;
uint8_t GetStationIndex() const;
uint8_t GetSequenceIndex() const;
uint8_t GetPathType() const;
void SetEntranceType(uint8_t newType);
void SetRideIndex(uint8_t newRideIndex);
void SetStationIndex(uint8_t stationIndex);
void SetSequenceIndex(uint8_t newSequenceIndex);
void SetPathType(uint8_t newPathType);
};
assert_struct_size(RCT12EntranceElement, 8);
struct RCT12BannerElement : RCT12TileElementBase
{
private:
uint8_t index; // 4
uint8_t position; // 5
uint8_t flags; // 6
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-private-field"
uint8_t unused; // 7
#pragma clang diagnostic pop
public:
uint8_t GetIndex() const;
uint8_t GetPosition() const;
uint8_t GetAllowedEdges() const;
void SetIndex(uint8_t newIndex);
void SetPosition(uint8_t newPosition);
void SetAllowedEdges(uint8_t newEdges);
};
assert_struct_size(RCT12BannerElement, 8);
struct RCT12CorruptElement : RCT12TileElementBase
{
uint8_t pad[4];
};
assert_struct_size(RCT12CorruptElement, 8);
struct RCT12EightCarsCorruptElement14 : RCT12TileElementBase
{
uint8_t pad[4];
};
assert_struct_size(RCT12EightCarsCorruptElement14, 8);
struct RCT12EightCarsCorruptElement15 : RCT12TileElementBase
{
uint8_t pad[4];
};
assert_struct_size(RCT12EightCarsCorruptElement15, 8);
struct RCT12SpriteBase
{
uint8_t sprite_identifier; // 0x00
uint8_t type; // 0x01
uint16_t next_in_quadrant; // 0x02
uint16_t next; // 0x04
uint16_t previous; // 0x06
uint8_t linked_list_type_offset; // 0x08
uint8_t sprite_height_negative; // 0x09
uint16_t sprite_index; // 0x0A
uint16_t flags; // 0x0C
int16_t x; // 0x0E
int16_t y; // 0x10
int16_t z; // 0x12
uint8_t sprite_width; // 0x14
uint8_t sprite_height_positive; // 0x15
int16_t sprite_left; // 0x16
int16_t sprite_top; // 0x18
int16_t sprite_right; // 0x1A
int16_t sprite_bottom; // 0x1C
uint8_t sprite_direction; // 0x1E
};
assert_struct_size(RCT12SpriteBase, 0x1F);
struct RCT12SpriteBalloon : RCT12SpriteBase
{
uint8_t pad_1F[0x24 - 0x1F];
uint16_t popped; // 0x24
uint8_t time_to_move; // 0x26
uint8_t frame; // 0x27
uint8_t pad_28[4];
uint8_t colour; // 0x2C
};
assert_struct_size(RCT12SpriteBalloon, 0x2D);
struct RCT12SpriteDuck : RCT12SpriteBase
{
uint8_t pad_1F[0x26 - 0x1F];
uint16_t frame; // 0x26
uint8_t pad_28[0x30 - 0x28];
int16_t target_x; // 0x30
int16_t target_y; // 0x32
uint8_t pad_34[0x14];
uint8_t state; // 0x48
};
assert_struct_size(RCT12SpriteDuck, 0x49);
struct RCT12SpriteLitter : RCT12SpriteBase
{
uint8_t pad_1F[0x24 - 0x1F];
uint32_t creationTick; // 0x24
};
assert_struct_size(RCT12SpriteLitter, 0x28);
struct RCT12SpriteParticle : RCT12SpriteBase
{
uint8_t pad_1F[0x26 - 0x1F];
uint16_t frame; // 0x26
};
assert_struct_size(RCT12SpriteParticle, 0x28);
struct RCT12SpriteJumpingFountain : RCT12SpriteBase
{
uint8_t pad_1F[0x26 - 0x1F];
uint8_t num_ticks_alive; // 0x26
uint8_t frame; // 0x27
uint8_t pad_28[0x2F - 0x28];
uint8_t fountain_flags; // 0x2F
int16_t target_x; // 0x30
int16_t target_y; // 0x32
uint8_t pad_34[0x46 - 0x34];
uint16_t iteration; // 0x46
};
assert_struct_size(RCT12SpriteJumpingFountain, 0x48);
struct RCT12SpriteMoneyEffect : RCT12SpriteBase
{
uint8_t pad_1F[0x24 - 0x1F];
uint16_t move_delay; // 0x24
uint8_t num_movements; // 0x26
uint8_t vertical;
money32 value; // 0x28
uint8_t pad_2C[0x44 - 0x2C];
int16_t offset_x; // 0x44
uint16_t wiggle; // 0x46
};
assert_struct_size(RCT12SpriteMoneyEffect, 0x48);
struct RCT12SpriteCrashedVehicleParticle : RCT12SpriteBase
{
uint8_t pad_1F[0x24 - 0x1F];
uint16_t time_to_live; // 0x24
uint16_t frame; // 0x26
uint8_t pad_28[0x2C - 0x28];
uint8_t colour[2]; // 0x2C
uint16_t crashed_sprite_base; // 0x2E
int16_t velocity_x; // 0x30
int16_t velocity_y; // 0x32
int16_t velocity_z; // 0x34
uint8_t pad_36[0x38 - 0x36];
int32_t acceleration_x; // 0x38
int32_t acceleration_y; // 0x3C
int32_t acceleration_z; // 0x40
};
assert_struct_size(RCT12SpriteCrashedVehicleParticle, 0x44);
struct RCT12SpriteCrashSplash : RCT12SpriteBase
{
uint8_t pad_1F[0x26 - 0x1F];
uint16_t frame; // 0x26
};
assert_struct_size(RCT12SpriteCrashSplash, 0x28);
struct RCT12SpriteSteamParticle : RCT12SpriteBase
{
uint8_t pad_1F[0x24 - 0x1F];
uint16_t time_to_move; // 0x24
uint16_t frame; // 0x26
};
assert_struct_size(RCT12SpriteSteamParticle, 0x28);
struct RCT12PeepThought
{
uint8_t type;
uint8_t item;
uint8_t freshness;
uint8_t fresh_timeout;
};
assert_struct_size(RCT12PeepThought, 4);
struct RCT12RideMeasurement
{
uint8_t ride_index; // 0x0000
uint8_t flags; // 0x0001
uint32_t last_use_tick; // 0x0002
uint16_t num_items; // 0x0006
uint16_t current_item; // 0x0008
uint8_t vehicle_index; // 0x000A
uint8_t current_station; // 0x000B
int8_t vertical[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x000C
int8_t lateral[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x12CC
uint8_t velocity[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x258C
uint8_t altitude[RCT12_RIDE_MEASUREMENT_MAX_ITEMS]; // 0x384C
};
assert_struct_size(RCT12RideMeasurement, 0x4B0C);
struct RCT12Banner
{
RCT12ObjectEntryIndex type;
uint8_t flags; // 0x01
rct_string_id string_idx; // 0x02
union
{
uint8_t colour; // 0x04
uint8_t ride_index; // 0x04
};
uint8_t text_colour; // 0x05
uint8_t x; // 0x06
uint8_t y; // 0x07
};
assert_struct_size(RCT12Banner, 8);
struct RCT12MapAnimation
{
uint8_t baseZ;
uint8_t type;
uint16_t x;
uint16_t y;
};
assert_struct_size(RCT12MapAnimation, 6);
struct RCT12ResearchItem
{
// Bit 16 (0: scenery entry, 1: ride entry)
union
{
uint32_t rawValue;
struct
{
RCT12ObjectEntryIndex entryIndex;
uint8_t baseRideType;
uint8_t type; // 0: scenery entry, 1: ride entry
uint8_t flags;
};
};
uint8_t category;
bool IsInventedEndMarker() const;
bool IsRandomEndMarker() const;
bool IsUninventedEndMarker() const;
};
assert_struct_size(RCT12ResearchItem, 5);
#pragma pack(pop)
ObjectEntryIndex RCTEntryIndexToOpenRCT2EntryIndex(const RCT12ObjectEntryIndex index);
RCT12ObjectEntryIndex OpenRCT2EntryIndexToRCTEntryIndex(const ObjectEntryIndex index);
|
gpl-3.0
|
dzwiedziu-nkg/cyclo-bruxism
|
proof-of-concept/apk/app/src/main/java/pl/nkg/brq/android/ui/MainActivity.java
|
5333
|
/*
* Copyright (c) by Michał Niedźwiecki 2016
* Contact: nkg753 on gmail or via GitHub profile: dzwiedziu-nkg
*
* This file is part of Bike Road Quality.
*
* Bike Road Quality 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.
*
* Bike Road Quality 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 Foobar; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
package pl.nkg.brq.android.ui;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pl.nkg.brq.android.R;
import pl.nkg.brq.android.events.SensorsRecord;
import pl.nkg.brq.android.events.SensorsServiceState;
import pl.nkg.brq.android.services.SensorsService;
public class MainActivity extends AppCompatActivity {
private static final int MY_PERMISSION_RESPONSE = 29;
@Bind(R.id.button_on)
Button mButtonOn;
@Bind(R.id.button_off)
Button mButtonOff;
@Bind(R.id.speedTextView)
TextView mSpeedTextView;
@Bind(R.id.altitudeTextView)
TextView mAltitudeTextView;
@Bind(R.id.shakeTextView)
TextView mShakeTextView;
@Bind(R.id.noiseTextView)
TextView mNoiseTextView;
@Bind(R.id.distanceTextView)
TextView mDistanceTextView;
@Bind(R.id.warningTextView)
TextView mWarningTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Prompt for permissions
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)
!= PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Log.w("BleActivity", "Location access not granted!");
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.BLUETOOTH},
MY_PERMISSION_RESPONSE);
}
}
ButterKnife.bind(this);
}
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
protected void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
@OnClick(R.id.button_on)
public void onButtonOnClick() {
startService(new Intent(MainActivity.this, SensorsService.class));
}
@OnClick(R.id.button_off)
public void onButtonOffClick() {
stopService(new Intent(MainActivity.this, SensorsService.class));
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(SensorsServiceState state) {
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onEventMainThread(SensorsRecord record) {
mSpeedTextView.setText((int) (record.speed * 3.6) + " km/h");
mAltitudeTextView.setText((int) record.altitude + " m n.p.m.");
mShakeTextView.setText((int) (record.shake * 100) / 100.0 + " m/s²");
mNoiseTextView.setText((int) record.soundNoise + " db");
mDistanceTextView.setText((double) record.distance / 100.0 + " m");
if (record.distance < 120 && record.distance != 0) {
mWarningTextView.setVisibility(View.VISIBLE);
mWarningTextView.setText((double) record.distance / 100.0 + " m");
mWarningTextView.setTextSize(Math.min(5000 / record.distance, 100));
} else {
mWarningTextView.setVisibility(View.GONE);
}
}
}
|
gpl-3.0
|
xavarius/FlickrFeed
|
app/src/main/java/com/malak/yaim/model/FlickrFeed.java
|
1050
|
package com.malak.yaim.model;
import java.util.List;
public class FlickrFeed {
private String title;
private String link;
private String description;
private String modified;
private String generator;
private List<Item> items = null;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getModified() {
return modified;
}
public void setModified(String modified) {
this.modified = modified;
}
public String getGenerator() {
return generator;
}
public void setGenerator(String generator) {
this.generator = generator;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
|
gpl-3.0
|
RossGammon/the-gammons.net
|
RossFamilyTree/ppl/2/9/d15f603cbce7f07779628b52a92.html
|
16482
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - LAWSON, Adelaide Kate</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
<link href="../../../css/ancestortree.css" media="screen" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li class = "CurrentSection"><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="IndividualDetail">
<h3>LAWSON, Adelaide Kate<sup><small></small></sup></h3>
<div id="summaryarea">
<table class="infolist">
<tr>
<td class="ColumnAttribute">Birth Name</td>
<td class="ColumnValue">
LAWSON, Adelaide Kate <a href="#sref1a">1a</a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">I10791</td>
</tr>
<tr>
<td class="ColumnAttribute">Gender</td>
<td class="ColumnValue">female</td>
</tr>
<tr>
<td class="ColumnAttribute">Age at Death</td>
<td class="ColumnValue">60 years, 5 months, 12 days</td>
</tr>
</table>
</div>
<div class="subsection" id="events">
<h4>Events</h4>
<table class="infolist eventlist">
<thead>
<tr>
<th class="ColumnEvent">Event</th>
<th class="ColumnDate">Date</th>
<th class="ColumnPlace">Place</th>
<th class="ColumnDescription">Description</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/4/0/d15f603cbd747573e7f39951404.html" title="Birth">
Birth
<span class="grampsid"> [E11919]</span>
</a>
</td>
<td class="ColumnDate">1879-11-15</td>
<td class="ColumnPlace">
<a href="../../../plc/c/4/d15f5fb92e843882bcabe3e6e4c.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
<tr>
<td class="ColumnEvent">
<a href="../../../evt/3/1/d15f603cbe04c44437644607713.html" title="Death">
Death
<span class="grampsid"> [E11920]</span>
</a>
</td>
<td class="ColumnDate">1940-04-27</td>
<td class="ColumnPlace">
<a href="../../../plc/c/4/d15f5fb92e843882bcabe3e6e4c.html" title="">
</a>
</td>
<td class="ColumnDescription"> </td>
<td class="ColumnNotes">
<div>
</div>
</td>
<td class="ColumnSources">
</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="parents">
<h4>Parents</h4>
<table class="infolist">
<thead>
<tr>
<th class="ColumnAttribute">Relation to main person</th>
<th class="ColumnValue">Name</th>
<th class="ColumnValue">Relation within this family (if not by birth)</th>
</tr>
</thead>
<tbody>
</tbody>
<tr>
<td class="ColumnAttribute">Father</td>
<td class="ColumnValue">
<a href="../../../ppl/f/8/d15f603c9034e759c0ac890918f.html">LAWSON, William<span class="grampsid"> [I10779]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute">Mother</td>
<td class="ColumnValue">
<a href="../../../ppl/0/8/d15f603c8b74e5fed8b1ad5f80.html">LUCAS, Adelaide<span class="grampsid"> [I10778]</span></a>
</td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/8/3/d15f603c9312348dd5bc05c4d38.html">LAWSON, Alice Emily<span class="grampsid"> [I10780]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/1/7/d15f603c9a67c0aefb00341b271.html">LAWSON, George William<span class="grampsid"> [I10781]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/e/5/d15f603ca2c246079fb8eef625e.html">LAWSON, Bertha Beatrice<span class="grampsid"> [I10784]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/6/0/d15f603ca916c80619d7d9b7706.html">LAWSON, Harry Hatton<span class="grampsid"> [I10786]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/0/9/d15f603cad1cee2ac0f23a7490.html">LAWSON, Hubert Lucas<span class="grampsid"> [I10787]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/4/e/d15f603cb134d5bd1a0733a20e4.html">LAWSON, Ethel Henrietta<span class="grampsid"> [I10788]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Brother</td>
<td class="ColumnValue"> <a href="../../../ppl/e/d/d15f603cb6117449b9ad6b48de.html">LAWSON, Harold Athol<span class="grampsid"> [I10789]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> Sister</td>
<td class="ColumnValue"> <a href="../../../ppl/0/2/d15f603cb9f1a218c780d708720.html">LAWSON, Emily Lucas<span class="grampsid"> [I10790]</span></a></td>
<td class="ColumnValue"></td>
</tr>
<tr>
<td class="ColumnAttribute"> </td>
<td class="ColumnValue"> <a href="../../../ppl/2/9/d15f603cbce7f07779628b52a92.html">LAWSON, Adelaide Kate<span class="grampsid"> [I10791]</span></a></td>
<td class="ColumnValue"></td>
</tr>
</table>
</div>
<div class="subsection" id="attributes">
<h4>Attributes</h4>
<table class="infolist attrlist">
<thead>
<tr>
<th class="ColumnType">Type</th>
<th class="ColumnValue">Value</th>
<th class="ColumnNotes">Notes</th>
<th class="ColumnSources">Sources</th>
</tr>
</thead>
<tbody>
<tr>
<td class="ColumnType">_UID</td>
<td class="ColumnValue">A9B9DC830D9475458C1BF923EE4EE5FAFA15</td>
<td class="ColumnNotes"><div></div></td>
<td class="ColumnSources"> </td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="pedigree">
<h4>Pedigree</h4>
<ol class="pedigreegen">
<li>
<a href="../../../ppl/f/8/d15f603c9034e759c0ac890918f.html">LAWSON, William<span class="grampsid"> [I10779]</span></a>
<ol>
<li class="spouse">
<a href="../../../ppl/0/8/d15f603c8b74e5fed8b1ad5f80.html">LUCAS, Adelaide<span class="grampsid"> [I10778]</span></a>
<ol>
<li>
<a href="../../../ppl/8/3/d15f603c9312348dd5bc05c4d38.html">LAWSON, Alice Emily<span class="grampsid"> [I10780]</span></a>
</li>
<li>
<a href="../../../ppl/1/7/d15f603c9a67c0aefb00341b271.html">LAWSON, George William<span class="grampsid"> [I10781]</span></a>
</li>
<li>
<a href="../../../ppl/e/5/d15f603ca2c246079fb8eef625e.html">LAWSON, Bertha Beatrice<span class="grampsid"> [I10784]</span></a>
</li>
<li>
<a href="../../../ppl/6/0/d15f603ca916c80619d7d9b7706.html">LAWSON, Harry Hatton<span class="grampsid"> [I10786]</span></a>
</li>
<li>
<a href="../../../ppl/0/9/d15f603cad1cee2ac0f23a7490.html">LAWSON, Hubert Lucas<span class="grampsid"> [I10787]</span></a>
</li>
<li>
<a href="../../../ppl/4/e/d15f603cb134d5bd1a0733a20e4.html">LAWSON, Ethel Henrietta<span class="grampsid"> [I10788]</span></a>
</li>
<li>
<a href="../../../ppl/e/d/d15f603cb6117449b9ad6b48de.html">LAWSON, Harold Athol<span class="grampsid"> [I10789]</span></a>
</li>
<li>
<a href="../../../ppl/0/2/d15f603cb9f1a218c780d708720.html">LAWSON, Emily Lucas<span class="grampsid"> [I10790]</span></a>
</li>
<li class="thisperson">
LAWSON, Adelaide Kate
</li>
</ol>
</li>
</ol>
</li>
</ol>
</div>
<div class="subsection" id="tree">
<h4>Ancestors</h4>
<div id="treeContainer" style="width:735px; height:602px;">
<div class="boxbg female AncCol0" style="top: 269px; left: 6px;">
<a class="noThumb" href="../../../ppl/2/9/d15f603cbce7f07779628b52a92.html">
LAWSON, Adelaide Kate
</a>
</div>
<div class="shadow" style="top: 274px; left: 10px;"></div>
<div class="bvline" style="top: 301px; left: 165px; width: 15px"></div>
<div class="gvline" style="top: 306px; left: 165px; width: 20px"></div>
<div class="boxbg male AncCol1" style="top: 119px; left: 196px;">
<a class="noThumb" href="../../../ppl/f/8/d15f603c9034e759c0ac890918f.html">
LAWSON, William
</a>
</div>
<div class="shadow" style="top: 124px; left: 200px;"></div>
<div class="bvline" style="top: 151px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 156px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 151px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 156px; left: 185px; height: 150px;"></div>
<div class="boxbg female AncCol1" style="top: 419px; left: 196px;">
<a class="noThumb" href="../../../ppl/0/8/d15f603c8b74e5fed8b1ad5f80.html">
LUCAS, Adelaide
</a>
</div>
<div class="shadow" style="top: 424px; left: 200px;"></div>
<div class="bvline" style="top: 451px; left: 180px; width: 15px;"></div>
<div class="gvline" style="top: 456px; left: 185px; width: 20px;"></div>
<div class="bhline" style="top: 301px; left: 180px; height: 150px;"></div>
<div class="gvline" style="top: 306px; left: 185px; height: 150px;"></div>
<div class="bvline" style="top: 451px; left: 355px; width: 15px"></div>
<div class="gvline" style="top: 456px; left: 355px; width: 20px"></div>
<div class="boxbg male AncCol2" style="top: 344px; left: 386px;">
<a class="noThumb" href="../../../ppl/b/c/d15f60113e257f63df1048230cb.html">
LUCAS, George
</a>
</div>
<div class="shadow" style="top: 349px; left: 390px;"></div>
<div class="bvline" style="top: 376px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 381px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 376px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 381px; left: 375px; height: 75px;"></div>
<div class="bvline" style="top: 376px; left: 545px; width: 15px"></div>
<div class="gvline" style="top: 381px; left: 545px; width: 20px"></div>
<div class="boxbg male AncCol3" style="top: 307px; left: 576px;">
<a class="noThumb" href="../../../ppl/a/3/d15f5fb962f11f46775d411d23a.html">
LUCAS, Nathaniel
</a>
</div>
<div class="shadow" style="top: 312px; left: 580px;"></div>
<div class="bvline" style="top: 339px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 344px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 339px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 344px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol3" style="top: 381px; left: 576px;">
<a class="noThumb" href="../../../ppl/6/8/d15f5fb965a7bfcfae4d7c1e486.html">
GASCOYNE, Olivia
</a>
</div>
<div class="shadow" style="top: 386px; left: 580px;"></div>
<div class="bvline" style="top: 413px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 418px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 376px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 381px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol2" style="top: 494px; left: 386px;">
<a class="noThumb" href="../../../ppl/6/7/d15f5fe2e527676c66ae7aec176.html">
HODGETTS, Elizabeth
</a>
</div>
<div class="shadow" style="top: 499px; left: 390px;"></div>
<div class="bvline" style="top: 526px; left: 370px; width: 15px;"></div>
<div class="gvline" style="top: 531px; left: 375px; width: 20px;"></div>
<div class="bhline" style="top: 451px; left: 370px; height: 75px;"></div>
<div class="gvline" style="top: 456px; left: 375px; height: 75px;"></div>
<div class="bvline" style="top: 526px; left: 545px; width: 15px"></div>
<div class="gvline" style="top: 531px; left: 545px; width: 20px"></div>
<div class="boxbg male AncCol3" style="top: 457px; left: 576px;">
<a class="noThumb" href="../../../ppl/a/4/d15f5fb95dd145846dcccdda14a.html">
HODGETTS, Thomas
</a>
</div>
<div class="shadow" style="top: 462px; left: 580px;"></div>
<div class="bvline" style="top: 489px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 494px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 489px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 494px; left: 565px; height: 37px;"></div>
<div class="boxbg female AncCol3" style="top: 531px; left: 576px;">
<a class="noThumb" href="../../../ppl/e/5/d15f5fb960476abfb804452155e.html">
LUCE, Harriet
</a>
</div>
<div class="shadow" style="top: 536px; left: 580px;"></div>
<div class="bvline" style="top: 563px; left: 560px; width: 15px;"></div>
<div class="gvline" style="top: 568px; left: 565px; width: 20px;"></div>
<div class="bhline" style="top: 526px; left: 560px; height: 37px;"></div>
<div class="gvline" style="top: 531px; left: 565px; height: 37px;"></div>
</div>
</div>
<div class="subsection" id="sourcerefs">
<h4>Source References</h4>
<ol>
<li>
<a href="../../../src/8/d/d15f5fe05fb4f67e220976f79d8.html" title="Frank Lee: GEDCOM File : GeorgeLUCAS.ged" name ="sref1">
Frank Lee: GEDCOM File : GeorgeLUCAS.ged
<span class="grampsid"> [S0301]</span>
</a>
<ol>
<li id="sref1a">
<ul>
<li>
Confidence: Low
</li>
</ul>
</li>
</ol>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:54:51<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
gpl-3.0
|
GeoMop/GeoMop
|
src/gm_base/model_data/format.py
|
4784
|
"""
Contains format specification class and methods to parse it from JSON.
.. codeauthor:: Tomas Krizek <tomas.krizek1@tul.cz>
"""
import json
import re
def get_root_input_type_from_json(data):
"""Return the root input type from JSON formatted string."""
return parse_format(json.loads(data))
def parse_format(data):
"""Returns root input type from data."""
input_types = {}
data = data['ist_nodes']
root_id = data[0]['id'] # set root type
for item in data:
input_type = _get_input_type(item)
if input_type is not None:
input_types[input_type['id']] = input_type # register by id
_substitute_ids_with_references(input_types)
return input_types[root_id]
SCALAR = ['Integer', 'Double', 'Bool', 'String', 'Selection', 'FileName']
def is_scalar(input_type):
"""Returns True if input_type is scalar."""
return input_type['base_type'] in SCALAR
RE_PARAM = re.compile('^<([a-zA-Z][a-zA-Z0-9_]*)>$')
def is_param(value):
"""Determine whether given value is a parameter string."""
if not isinstance(value, str):
return False
return RE_PARAM.match(value)
def _substitute_ids_with_references(input_types):
"""Replaces ids or type names with python object references."""
input_type = {}
def _substitute_implementations():
"""Replaces implementation ids with input_types."""
impls = {}
for id_ in input_type['implementations']:
type_ = input_types[id_]
impls[type_['name']] = type_
input_type['implementations'] = impls
def _substitute_default_descendant():
"""Replaces default descendant id with input_type."""
id_ = input_type.get('default_descendant', None)
if id_ is not None:
input_type['default_descendant'] = input_types[id_]
def _substitute_key_type():
"""Replaces key type with input_type."""
# pylint: disable=unused-variable, invalid-name
for __, value in input_type['keys'].items():
value['type'] = input_types[value['type']]
# pylint: disable=unused-variable, invalid-name
for __, input_type in input_types.items():
if input_type['base_type'] == 'Array':
input_type['subtype'] = input_types[input_type['subtype']]
elif input_type['base_type'] == 'Abstract':
_substitute_implementations()
_substitute_default_descendant()
elif input_type['base_type'] == 'Record':
_substitute_key_type()
def _get_input_type(data):
"""Returns the input_type data structure that defines an input type
and its constraints for validation."""
if 'id' not in data or 'input_type' not in data:
return None
input_type = dict(
id=data['id'],
base_type=data['input_type']
)
input_type['name'] = data.get('name', '')
input_type['full_name'] = data.get('full_name', '')
input_type['description'] = data.get('description', '')
input_type['attributes'] = data.get('attributes', {})
if input_type['base_type'] in ['Double', 'Integer']:
input_type.update(_parse_range(data))
elif input_type['base_type'] == 'Array':
input_type.update(_parse_range(data))
if input_type['min'] < 0:
input_type['min'] = 0
input_type['subtype'] = data['subtype']
elif input_type['base_type'] == 'FileName':
input_type['file_mode'] = data['file_mode']
elif input_type['base_type'] == 'Selection':
input_type['values'] = _list_to_dict(data['values'], 'name')
elif input_type['base_type'] == 'Record':
input_type['keys'] = _list_to_dict(data['keys'])
input_type['implements'] = data.get('implements', [])
input_type['reducible_to_key'] = data.get('reducible_to_key', None)
elif input_type['base_type'] == 'Abstract':
input_type['implementations'] = data['implementations']
input_type['default_descendant'] = data.get('default_descendant', None)
return input_type
def _parse_range(data):
"""Parses the format range properties - min, max."""
input_type = {}
try:
input_type['min'] = data['range'][0]
except (KeyError, TypeError): # set default value
input_type['min'] = float('-inf')
try:
input_type['max'] = data['range'][1]
except (KeyError, TypeError): # set default value
input_type['max'] = float('inf')
return input_type
def _list_to_dict(list_, key_label='key'):
"""
Transforms a list of dictionaries into a dictionary of dictionaries.
Original dictionaries are assigned key specified in each of them
by key_label.
"""
dict_ = {}
for item in list_:
dict_[item[key_label]] = item
return dict_
|
gpl-3.0
|
ZepedaJake/2D-RPG-Unity
|
Terry's Tower/Assets/Scripts/Serializer.cs
|
27853
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEditor;
using System.IO;
public class Serializer : MonoBehaviour {
//save defaults are only used to set the data used when initializing that map the next time.
string saveFile;
string loadFile;
string fileName;
public string saveData;
public string defaults;
CharacterControllerScript player;
// Use this for initialization
void Start () {
player = Globals.playerScript;
//save on disc
saveData = Path.Combine(Application.persistentDataPath, "SaveData");
// defaults included in project
defaults = "Assets/Resources/Defaults/";
CreateDirectories();
}
// Update is called once per frame
void Update () {
}
void CreateDirectories()
{
if(!Directory.Exists(saveData))
{
Directory.CreateDirectory(saveData);
}
/*if(!Directory.Exists(defaults))
{
Directory.CreateDirectory(defaults);
}*/
}
public void SavePlayerData()
{
PlayerSaveData playerData = new PlayerSaveData()
{
level = player.level,
statPoints = player.statPoints,
skillPoints = player.skillPoints,
spentStatPoints = player.spentStatPoints,
spentSkillPoints = player.spentSkillPoints,
currentHealth = player.currentHealth,
maxHealth = player.maxHealth,
currentXP = player.currentXP,
xpToLevel = player.xpToLevel,
atk = player.atk,
atkItemBonus = player.atkItemBonus,
statAtk = player.statAtk,
def = player.def,
defItemBonus = player.defItemBonus,
statDef = player.statDef,
skill1Lvl = player.skills[0].level,
skill2Lvl = player.skills[1].level,
skill3Lvl = player.skills[2].level,
skill4Lvl = player.skills[3].level,
lookingX = (int)player.looking.x,
lookingY = (int)player.looking.y,
direction = player.direction,
bronzeKeys = player.bronzeKeys,
silverKeys = player.silverKeys,
goldKeys = player.goldKeys,
currentMap = Globals.currentMap,
redOrbState = player.redOrbState,
blueOrbState = player.blueOrbState,
storyProgress = player.storyProgress,
sideQuests = new List<PlayerSaveData.PlayerQuests>()
};
foreach(Quest q in player.quests)
{
PlayerSaveData.PlayerQuests quest = new PlayerSaveData.PlayerQuests();
quest.questName = q.questName;
quest.description = q.description;
quest.complete = q.complete;
quest.progress = q.progress;
playerData.sideQuests.Add(quest);
}
string json = JsonUtility.ToJson(playerData);
string fileName = Path.Combine(saveData, "player.json");
if(File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
SavePlayerInventory();
//Debug.Log(json);
Debug.Log(fileName);
}
public void SavePlayerInventory()
{
PlayerInventory playerInventory = new PlayerInventory();
try
{
foreach (InventoryItemBase i in player.inventory)
{
playerInventory.inventoryItems.Add(i);
}
}
catch
{
Debug.Log("Empty Inventory");
}
string json = JsonUtility.ToJson(playerInventory);
string fileName = Path.Combine(saveData, "inventory.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
public void LoadPlayerInventory()
{
try
{
fileName = Path.Combine(saveData, "inventory.json");
loadFile = File.ReadAllText(fileName);
PlayerInventory load = JsonUtility.FromJson<PlayerInventory>(loadFile);
if (load.inventoryItems.Count > 0)
{
player.inventory.Clear();
foreach (InventoryItemBase i in load.inventoryItems)
{
player.inventory.Add(i);
}
}
}
catch
{
Debug.Log("Problem loading inventory");
}
}
public void LoadPlayerData()
{
fileName = Path.Combine(saveData, "player.json");
loadFile = File.ReadAllText(fileName);
PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile);
//Debug.Log(load.level+ "" + load.statPoints+""+ load.skillPoints+ "" +load.currentMap);
player.level = load.level;
player.statPoints = load.statPoints;
player.skillPoints = load.skillPoints;
player.spentStatPoints = load.spentStatPoints;
player.spentSkillPoints = load.spentSkillPoints;
player.maxHealth = load.maxHealth;
player.currentHealth = load.currentHealth;
player.xpToLevel = load.xpToLevel;
player.currentXP = load.currentXP;
player.atk = load.atk;
player.statAtk = load.statAtk;
player.atkItemBonus = load.atkItemBonus;
player.def = load.def;
player.statDef = load.statDef;
player.defItemBonus = load.defItemBonus;
player.skills[0].level = load.skill1Lvl;
player.skills[1].level = load.skill2Lvl;
player.skills[2].level = load.skill3Lvl;
player.skills[3].level = load.skill4Lvl;
player.looking = new Vector2(load.lookingX, load.lookingY);
player.direction = load.direction;
player.bronzeKeys = load.bronzeKeys;
player.silverKeys = load.silverKeys;
player.goldKeys = load.goldKeys;
player.redOrbState = load.redOrbState;
player.blueOrbState = load.blueOrbState;
player.storyProgress = load.storyProgress;
//for (int x = 0; x < load.sideQuests.Count; x++)
// {
// Debug.Log(load.sideQuests[x].questName);
// Debug.Log(load.sideQuests[x].description);
// Debug.Log(load.sideQuests[x].complete);
// Debug.Log(load.sideQuests[x].progress);
// player.quests.Add(new Quest(load.sideQuests[x].questName, load.sideQuests[x].description, load.sideQuests[x].complete, load.sideQuests[0].progress));
//}
foreach (PlayerSaveData.PlayerQuests q in load.sideQuests)
{
//Debug.Log(q.questName);
//Debug.Log(q.description);
//Debug.Log(q.complete);
//Debug.Log(q.progress);
player.quests.Add(new Quest(q.questName, q.description, q.complete, q.progress));
//Debug.Log(player.quests[0].questName);
}
LoadPlayerInventory();
}
public string SavedFloor()
{
//used to load in saved floor
fileName = Path.Combine(saveData, "player.json");
loadFile = File.ReadAllText(fileName);
PlayerSaveData load = JsonUtility.FromJson<PlayerSaveData>(loadFile);
return load.currentMap;
}
//public void SaveMap(int x, int y)
//{
// MapSaveData mapData = new MapSaveData()
// {
// returnPointX = x,
// returnPointY = y
// };
// string json = JsonUtility.ToJson(mapData);
// string fileName = Path.Combine(saveData, SceneManager.GetActiveScene().name + ".json");
// if (File.Exists(fileName))
// {
// File.Delete(fileName);
// }
// File.WriteAllText(fileName, json);
//}
//public void LoadMap(string nextMap)
//{
// fileName = Path.Combine(saveData, nextMap + ".json");
// loadFile = File.ReadAllText(fileName);
// MapSaveData load = JsonUtility.FromJson<MapSaveData>(loadFile);
// player.gameObject.transform.position = new Vector2(load.returnPointX + .5f, load.returnPointY-.5f);
//}
/*public void SaveEnemies()
{
try
{
EnemiesOnMap mapEnemies = new EnemiesOnMap
{
mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>()
};
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapEnemies.mapEnemyInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapEnemies);
string fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Enemies here");
}
}
public void SaveEnemiesDefault()
{
try
{
EnemiesOnMap mapEnemies = new EnemiesOnMap
{
mapEnemyInfo = new List<EnemiesOnMap.EnemyInfo>()
};
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
EnemiesOnMap.EnemyInfo newInfo = new EnemiesOnMap.EnemyInfo();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapEnemies.mapEnemyInfo.Add(newInfo);
Destroy(enemy);
}
string json = JsonUtility.ToJson(mapEnemies);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Enemies here");
}
}
public void LoadEnemies()
{try
{
StartCoroutine(LoadEnemiesDelay());
}
catch
{
Debug.Log("No Enemies Loaded");
}
}
public IEnumerator LoadEnemiesDelay()
{
yield return new WaitForSeconds(.5f);
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "enemies.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "enemies.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultenemies.json");
}
Debug.Log("loading enemies from " + fileName);
loadFile = File.ReadAllText(fileName);
EnemiesOnMap load = JsonUtility.FromJson<EnemiesOnMap>(loadFile);
Container enemyContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (EnemiesOnMap.EnemyInfo info in load.mapEnemyInfo)
//{
// //load into a list.
// //enemyContainer.CreateEnemy(info.enemyName, info.posX, info.posY, info.alive);
//}
for(int x = load.mapEnemyInfo.Count -1; x>-1; x--)
{
//start new enemy
//set its info to load[x]
//create from container
//clear entry from list
EnemiesOnMap.EnemyInfo e = load.mapEnemyInfo[x];
enemyContainer.CreateEnemy(e.enemyName, e.posX, e.posY, e.alive,e.heldItem);
load.mapEnemyInfo.RemoveAt(x);
}
yield return null;
}
public void SaveItems()
{
try
{
ItemsOnMap mapItems = new ItemsOnMap
{
mapItemInfo = new List<ItemsOnMap.ItemInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapItems.mapItemInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapItems);
string fileName = Path.Combine(saveData, Globals.currentMap + "items.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Items Here");
}
}
public void SaveItemsDefault()
{
try
{
ItemsOnMap mapItems = new ItemsOnMap
{
mapItemInfo = new List<ItemsOnMap.ItemInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
ItemsOnMap.ItemInfo newInfo = new ItemsOnMap.ItemInfo();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapItems.mapItemInfo.Add(newInfo);
Destroy(item);
}
string json = JsonUtility.ToJson(mapItems);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Items Here");
}
}
public void LoadItems()
{
try
{
StartCoroutine(LoadItemsDelay());
}
catch
{
Debug.Log("No items loaded");
}
}
public IEnumerator LoadItemsDelay()
{
yield return new WaitForSeconds(.5f);
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "items.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "items.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultitems.json");
}
Debug.Log("loading items from " + fileName);
loadFile = File.ReadAllText(fileName);
ItemsOnMap load = JsonUtility.FromJson<ItemsOnMap>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (ItemsOnMap.ItemInfo info in load.mapItemInfo)
//{
// Debug.Log(info.itemName);
// itemContainer.CreateItem(info.itemName, info.value, info.posX, info.posY, info.active);
//}
for (int x = load.mapItemInfo.Count - 1; x > -1; x--)
{
ItemsOnMap.ItemInfo i = load.mapItemInfo[x];
itemContainer.CreateItem(i.itemName,i.value, i.posX, i.posY);
load.mapItemInfo.RemoveAt(x);
}
yield return null;
}
public void SaveDoors()
{
try
{
DoorsOnMap mapDoors = new DoorsOnMap
{
mapDoorInfo = new List<DoorsOnMap.DoorInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = item.GetComponent<DoorBase>();
DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo();
{
newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapDoors.mapDoorInfo.Add(newInfo);
}
string json = JsonUtility.ToJson(mapDoors);
string fileName = Path.Combine(saveData, Globals.currentMap + "doors.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Doors Here");
}
}
public void SaveDoorsDefault()
{
try
{
DoorsOnMap mapDoors = new DoorsOnMap
{
mapDoorInfo = new List<DoorsOnMap.DoorInfo>()
};
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = item.GetComponent<DoorBase>();
DoorsOnMap.DoorInfo newInfo = new DoorsOnMap.DoorInfo();
{
newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapDoors.mapDoorInfo.Add(newInfo);
Destroy(item);
}
string json = JsonUtility.ToJson(mapDoors);
string fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json");
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
}
catch
{
Debug.Log("No Doors Here");
}
}
public void LoadDoors()
{
StartCoroutine(LoadDoorsDelay());
}
public IEnumerator LoadDoorsDelay()
{
yield return new WaitForSeconds(.5f);
try
{
if (File.Exists(Path.Combine(saveData, Globals.currentMap + "doors.json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + "doors.json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + "defaultdoors.json");
}
Debug.Log("loading doors from " + fileName);
loadFile = File.ReadAllText(fileName);
DoorsOnMap load = JsonUtility.FromJson<DoorsOnMap>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
//foreach (DoorsOnMap.DoorInfo info in load.mapDoorInfo)
//{
// itemContainer.CreateDoor(info.doorType, info.posX, info.posY);
//}
try
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
DoorsOnMap.DoorInfo d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorType, d.doorName, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
catch
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
DoorsOnMap.DoorInfo d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorType, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
}
catch { }
yield return null;
}*/
public void SaveMapData(bool d)
{
//true = default; false = other
fileName = "";
MapData mapData = new MapData
{
mapDoorInfo = new List<MapData.Door>(),
mapEnemyInfo = new List<MapData.Enemy>(),
mapItemInfo = new List<MapData.Item>(),
mapBinaryObjectInfo = new List<MapData.BinaryObject>()
};
//Save Doors
try
{
foreach (GameObject door in GameObject.FindGameObjectsWithTag("Door"))
{
DoorBase currentItem = door.GetComponent<DoorBase>();
MapData.Door newInfo = new MapData.Door();
{
//newInfo.doorType = currentItem.doorType.ToString();
newInfo.doorName = currentItem.doorName;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
}
mapData.mapDoorInfo.Add(newInfo);
Destroy(door);
}
}
catch
{
Debug.Log("problem saving doors");
}
//Save Items
try
{
foreach (GameObject item in GameObject.FindGameObjectsWithTag("Item"))
{
ItemBase currentItem = item.GetComponent<ItemBase>();
MapData.Item newInfo = new MapData.Item();
{
newInfo.itemName = currentItem.itemName.ToString();
newInfo.value = currentItem.value;
newInfo.posX = (int)currentItem.transform.position.x;
newInfo.posY = (int)currentItem.transform.position.y;
//newInfo.active = currentItem.active;
}
mapData.mapItemInfo.Add(newInfo);
Destroy(item);
}
}
catch
{
Debug.Log("problem saving items");
}
//Save Enemies
try
{
foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
{
EnemyBase currentEnemy = enemy.GetComponent<EnemyBase>();
MapData.Enemy newInfo = new MapData.Enemy();
{
newInfo.enemyName = currentEnemy.enemyName.ToString();
newInfo.posX = (int)currentEnemy.transform.position.x;
newInfo.posY = (int)currentEnemy.transform.position.y;
newInfo.alive = currentEnemy.alive;
newInfo.heldItem = currentEnemy.heldItem;
}
mapData.mapEnemyInfo.Add(newInfo);
Destroy(enemy);
}
}
catch
{
Debug.Log("problem saving enemies");
}
//Save BinaryItems
try
{
foreach(GameObject binary in GameObject.FindGameObjectsWithTag("Button"))
{
BinaryObject currentObject = binary.GetComponent<BinaryObject>();
MapData.BinaryObject newObject = new MapData.BinaryObject();
{
newObject.objectName = currentObject.objectName.ToString();
newObject.buttonState = currentObject.buttonState;
newObject.objectState = currentObject.objectState;
newObject.buttonX = (int)currentObject.transform.position.x;
newObject.buttonY = (int)currentObject.transform.position.y;
newObject.objectX = currentObject.objectLocationX;
newObject.objectY = currentObject.objectLocationY;
newObject.canToggle = currentObject.canToggle;
}
}
}
catch
{
//nothing to save
}
string json = JsonUtility.ToJson(mapData);
if(d == true)
{
fileName = Path.Combine(defaults, Globals.currentMap + ".json");
Debug.Log(d);
}
else
{
fileName = Path.Combine(saveData, Globals.currentMap + ".json");
Debug.Log(d);
}
if (File.Exists(fileName))
{
File.Delete(fileName);
}
File.WriteAllText(fileName, json);
Debug.Log("save complete" + fileName);
}
public IEnumerator LoadMapData()
{
yield return new WaitForSeconds(.5f);
Debug.Log("loading map data");
try
{
if (File.Exists(Path.Combine(saveData, Globals.currentMap + ".json")))
{
fileName = Path.Combine(saveData, Globals.currentMap + ".json");
}
else
{
fileName = Path.Combine(defaults, Globals.currentMap + ".json");
}
Debug.Log("loading from " + fileName);
loadFile = File.ReadAllText(fileName);
MapData load = JsonUtility.FromJson<MapData>(loadFile);
Container itemContainer = GameObject.FindWithTag("Container").GetComponent<Container>();
try
{
for (int x = load.mapDoorInfo.Count - 1; x > -1; x--)
{
MapData.Door d = load.mapDoorInfo[x];
itemContainer.CreateDoor(d.doorName, d.posX, d.posY);
load.mapDoorInfo.RemoveAt(x);
}
}
catch
{
Debug.Log("problem loading doors");
}
try
{
for (int x = load.mapItemInfo.Count - 1; x > -1; x--)
{
MapData.Item i = load.mapItemInfo[x];
itemContainer.CreateItem(i.itemName, i.value, i.posX, i.posY);
load.mapItemInfo.RemoveAt(x);
}
}
catch
{
}
try
{
for (int x = load.mapEnemyInfo.Count - 1; x > -1; x--)
{
MapData.Enemy e = load.mapEnemyInfo[x];
itemContainer.CreateEnemy(e.enemyName, e.posX, e.posY,e.alive,e.heldItem);
load.mapEnemyInfo.RemoveAt(x);
}
}
catch
{
}
try
{
for (int x = load.mapBinaryObjectInfo.Count - 1; x > -1; x--)
{
MapData.BinaryObject o = load.mapBinaryObjectInfo[x];
itemContainer.CreateBinaryObject(o.objectName, o.buttonState, o.objectState, o.buttonX, o.buttonY, o.objectX, o.objectY, o.canToggle);
load.mapBinaryObjectInfo.RemoveAt(x);
}
}
catch
{
}
}
catch { }
yield return null;
}
}
|
gpl-3.0
|
fazerlicourice7/botWorld2017
|
src/grid/Location.java
|
8439
|
package grid;
import java.util.Comparator;
import world.World;
/*
* AP(r) Computer Science GridWorld Case Study:
* Copyright(c) 2002-2006 College Entrance Examination Board
* (http://www.collegeboard.com).
*
* This code 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.
*
* This code 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.
*
* @author Alyce Brady
* @author Chris Nevison
* @author APCS Development Committee
* @author Cay Horstmann
*/
/**
* A <code>Location</code> object represents the row and column of a location
* in a two-dimensional grid. <br />
* The API of this class is testable on the AP CS A and AB exams.
*/
public class Location implements Comparable
{
private int row; // row location in grid
private int col; // column location in grid
/**
* The turn angle for turning 90 degrees to the left.
*/
public static final int LEFT = -90;
/**
* The turn angle for turning 90 degrees to the right.
*/
public static final int RIGHT = 90;
/**
* The turn angle for turning 45 degrees to the left.
*/
public static final int HALF_LEFT = -45;
/**
* The turn angle for turning 45 degrees to the right.
*/
public static final int HALF_RIGHT = 45;
/**
* The turn angle for turning a full circle.
*/
public static final int FULL_CIRCLE = 360;
/**
* The turn angle for turning a half circle.
*/
public static final int HALF_CIRCLE = 180;
/**
* The turn angle for making no turn.
*/
public static final int AHEAD = 0;
/**
* The compass direction for north.
*/
public static final int NORTH = 0;
/**
* The compass direction for northeast.
*/
public static final int NORTHEAST = 45;
/**
* The compass direction for east.
*/
public static final int EAST = 90;
/**
* The compass direction for southeast.
*/
public static final int SOUTHEAST = 135;
/**
* The compass direction for south.
*/
public static final int SOUTH = 180;
/**
* The compass direction for southwest.
*/
public static final int SOUTHWEST = 225;
/**
* The compass direction for west.
*/
public static final int WEST = 270;
/**
* The compass direction for northwest.
*/
public static final int NORTHWEST = 315;
/**
* Constructs a location with given row and column coordinates.
* @param r the row
* @param c the column
*/
public Location(int r, int c)
{
row = r;
col = c;
}
/**
* Gets the row coordinate.
* @return the row of this location
*/
public int getRow()
{
return row;
}
/**
* Gets the column coordinate.
* @return the column of this location
*/
public int getCol()
{
return col;
}
/**
* Gets the adjacent location in any one of the eight compass directions.
* @param direction the direction in which to find a neighbor location
* @return the adjacent location in the direction that is closest to
* <tt>direction</tt>
*/
public Location getAdjacentLocation(int direction)
{
// reduce mod 360 and round to closest multiple of 45
int adjustedDirection = (direction + HALF_RIGHT / 2) % FULL_CIRCLE;
if (adjustedDirection < 0)
adjustedDirection += FULL_CIRCLE;
adjustedDirection = (adjustedDirection / HALF_RIGHT) * HALF_RIGHT;
int dc = 0;
int dr = 0;
if (adjustedDirection == EAST)
dc = 1;
else if (adjustedDirection == SOUTHEAST)
{
dc = 1;
dr = 1;
}
else if (adjustedDirection == SOUTH)
dr = 1;
else if (adjustedDirection == SOUTHWEST)
{
dc = -1;
dr = 1;
}
else if (adjustedDirection == WEST)
dc = -1;
else if (adjustedDirection == NORTHWEST)
{
dc = -1;
dr = -1;
}
else if (adjustedDirection == NORTH)
dr = -1;
else if (adjustedDirection == NORTHEAST)
{
dc = 1;
dr = -1;
}
return new Location(getRow() + dr, getCol() + dc);
}
/**
* Returns the direction from this location toward another location. The
* direction is rounded to the nearest compass direction.
* @param target a location that is different from this location
* @return the closest compass direction from this location toward
* <code>target</code>
*/
public int getDirectionToward(Location target)
{
int dx = target.getCol() - getCol();
int dy = target.getRow() - getRow();
// y axis points opposite to mathematical orientation
int angle = (int) Math.toDegrees(Math.atan2(-dy, dx));
// mathematical angle is counterclockwise from x-axis,
// compass angle is clockwise from y-axis
int compassAngle = RIGHT - angle;
// prepare for truncating division by 45 degrees
compassAngle += HALF_RIGHT / 2;
// wrap negative angles
if (compassAngle < 0)
compassAngle += FULL_CIRCLE;
// round to nearest multiple of 45
return (compassAngle / HALF_RIGHT) * HALF_RIGHT;
}
/**
* Indicates whether some other <code>Location</code> object is "equal to"
* this one.
* @param other the other location to test
* @return <code>true</code> if <code>other</code> is a
* <code>Location</code> with the same row and column as this location;
* <code>false</code> otherwise
*/
public boolean equals(Object other)
{
if (!(other instanceof Location))
return false;
Location otherLoc = (Location) other;
return getRow() == otherLoc.getRow() && getCol() == otherLoc.getCol();
}
/**
* Generates a hash code.
* @return a hash code for this location
*/
public int hashCode()
{
return getRow() * 3737 + getCol();
}
/**
* Compares this location to <code>other</code> for ordering. Returns a
* negative integer, zero, or a positive integer as this location is less
* than, equal to, or greater than <code>other</code>. Locations are
* ordered in row-major order. <br />
* (Precondition: <code>other</code> is a <code>Location</code> object.)
* @param other the other location to test
* @return a negative integer if this location is less than
* <code>other</code>, zero if the two locations are equal, or a positive
* integer if this location is greater than <code>other</code>
*/
public int compareTo(Object other)
{
Location otherLoc = (Location) other;
if (getRow() < otherLoc.getRow())
return -1;
if (getRow() > otherLoc.getRow())
return 1;
if (getCol() < otherLoc.getCol())
return -1;
if (getCol() > otherLoc.getCol())
return 1;
return 0;
}
/**
* (Added for RatBots) Calculates the distance to another location.
* The distance is reported as the sum of the x and y distances
* and therefore doesn't consider diagonal movement.
* @param other the location that the distance is calculated to
* @return the distance
*/
public int distanceTo(Location other)
{
int dx = Math.abs(row - other.getRow());
int dy = Math.abs(col - other.getCol());
return dx+dy;
}
public boolean isValidLocation()
{
if(this.getRow() < 0 || this.getRow() >= World.DEFAULT_ROWS)
return false;
if(this.getCol() < 0 || this.getCol() >= World.DEFAULT_COLS)
return false;
return true;
}
/**
* Creates a string that describes this location.
* @return a string with the row and column of this location, in the format
* (row, col)
*/
public String toString()
{
return "(r:" + getRow() + ", c:" + getCol() + ")";
}
}
|
gpl-3.0
|
sebkur/live-cg
|
project/src/main/java/de/topobyte/livecg/ui/geometryeditor/preferences/LAFSelector.java
|
2265
|
/* This file is part of LiveCG.
*
* Copyright (C) 2013 Sebastian Kuerten
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.topobyte.livecg.ui.geometryeditor.preferences;
import java.awt.Component;
import javax.swing.JComboBox;
import javax.swing.JList;
import javax.swing.UIManager;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.plaf.basic.BasicComboBoxRenderer;
import de.topobyte.livecg.preferences.Configuration;
public class LAFSelector extends JComboBox
{
private static final long serialVersionUID = 6856865390726849784L;
public LAFSelector(Configuration configuration)
{
super(buildValues());
setRenderer(new Renderer());
setEditable(false);
String lookAndFeel = configuration.getSelectedLookAndFeel();
setSelectedIndex(-1);
for (int i = 0; i < getModel().getSize(); i++) {
LookAndFeelInfo info = (LookAndFeelInfo) getModel().getElementAt(i);
if (info.getClassName().equals(lookAndFeel)) {
setSelectedIndex(i);
break;
}
}
}
private static LookAndFeelInfo[] buildValues()
{
LookAndFeelInfo[] lafs = UIManager.getInstalledLookAndFeels();
return lafs;
}
private class Renderer extends BasicComboBoxRenderer
{
private static final long serialVersionUID = 1L;
@Override
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
super.getListCellRendererComponent(list, value, index, isSelected,
cellHasFocus);
if (value != null) {
LookAndFeelInfo item = (LookAndFeelInfo) value;
setText(item.getName());
} else {
setText("default");
}
return this;
}
}
}
|
gpl-3.0
|
KohaSuomi/Koha
|
installer/data/mysql/atomicupdate/KD-2990-mongodb-datawarehouse-for-logging.perl
|
914
|
$DBversion = 'XXX'; # will be replaced by the RM
if( CheckVersion( $DBversion ) ) {
$dbh->do("
CREATE TABLE action_logs_cache (
action_id int(11) NOT NULL auto_increment,
timestamp timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP,
user int(11) NOT NULL default 0,
module text,
action text,
object int(11) default NULL,
info text,
interface VARCHAR(30) DEFAULT NULL,
PRIMARY KEY (action_id),
KEY timestamp_idx (timestamp),
KEY user_idx (user),
KEY module_idx (module(255)),
KEY action_idx (action(255)),
KEY object_idx (object),
KEY info_idx (info(255)),
KEY interface (interface)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
");
# Always end with this (adjust the bug info)
SetVersion( $DBversion );
print "Upgrade to $DBversion done (KD 2990 - MongoDB datawarehouse for storing the logging data.)\n";
}
|
gpl-3.0
|
gaich/quickapps
|
app/src/main/java/com/yoavst/quickapps/calendar/CalendarUtil.java
|
13741
|
package com.yoavst.quickapps.calendar;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.provider.CalendarContract;
import android.provider.CalendarContract.Events;
import com.yoavst.quickapps.Preferences_;
import com.yoavst.quickapps.R;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.TimeZone;
import static android.provider.CalendarContract.Events.ALL_DAY;
import static android.provider.CalendarContract.Events.DISPLAY_COLOR;
import static android.provider.CalendarContract.Events.DTEND;
import static android.provider.CalendarContract.Events.DTSTART;
import static android.provider.CalendarContract.Events.DURATION;
import static android.provider.CalendarContract.Events.EVENT_LOCATION;
import static android.provider.CalendarContract.Events.RRULE;
import static android.provider.CalendarContract.Events.TITLE;
import static android.provider.CalendarContract.Events._ID;
/**
* Created by Yoav.
*/
public class CalendarUtil {
private CalendarUtil() {
}
private static final SimpleDateFormat dayFormatter = new SimpleDateFormat(
"EEE, MMM d, yyyy");
private static final SimpleDateFormat dateFormatter = new SimpleDateFormat(
"EEE, MMM d, HH:mm");
private static final SimpleDateFormat hourFormatter = new SimpleDateFormat("HH:mm");
private static final SimpleDateFormat fullDateFormat = new SimpleDateFormat("EEE, MMM d");
private static final SimpleDateFormat otherDayFormatter = new SimpleDateFormat("MMM d, HH:mm");
private static final TimeZone timezone = Calendar.getInstance().getTimeZone();
public static ArrayList<Event> getCalendarEvents(Context context) {
CalendarResources.init(context);
boolean showRepeating = new Preferences_(context).showRepeatingEvents().get();
ArrayList<Event> events = new ArrayList<>();
String selection = "((" + DTSTART + " >= ?) OR (" + DTEND + " >= ?))";
String milli = String.valueOf(System.currentTimeMillis());
String[] selectionArgs = new String[]{milli, milli};
Cursor cursor = context.getContentResolver()
.query(
Events.CONTENT_URI,
new String[]{_ID, TITLE, DTSTART, DTEND, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, selection,
selectionArgs, null
);
cursor.moveToFirst();
int count = cursor.getCount();
if (count != 0) {
//<editor-fold desc="Future Events">
for (int i = 0; i < count; i++) {
int id = cursor.getInt(0);
String title = cursor.getString(1);
long startDate = Long.parseLong(cursor.getString(2));
String endDateString = cursor.getString(3);
String location = cursor.getString(4);
boolean isAllDay = cursor.getInt(5) != 0;
int color = cursor.getInt(6);
String rRule = cursor.getString(7);
String duration = cursor.getString(8);
if (!isAllDay) {
// If the event not repeat itself - regular event
if (rRule == null) {
long endDate = endDateString == null || endDateString.equals("null") ? 0 : Long.parseLong(endDateString);
if (endDate == 0)
events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color));
else
events.add(new Event(id, title, startDate, endDate, location).setColor(color));
} else if (showRepeating) {
// Event that repeat itself
events = addEvents(events, getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false));
}
} else {
if (rRule == null) {
// One day event probably
if (endDateString == null || Long.parseLong(endDateString) == 0)
events.add(new Event(id, title, dayFormatter.format(new Date(startDate - timezone.getOffset(startDate))), location).setColor(color));
else if (showRepeating) {
int offset = timezone.getOffset(startDate);
long newTime = startDate - offset;
long endTime = Long.parseLong(endDateString) - offset;
events.add(new Event(id, title, newTime, endTime, location, true).setColor(color));
}
} else if (showRepeating) {
// Repeat all day event, god why?!?
events = addEvents(events, getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true));
}
}
cursor.moveToNext();
}
//</editor-fold>
}
cursor.close();
if (showRepeating) {
String repeatingSections = "((" + DURATION + " IS NOT NULL) AND (" + RRULE + " IS NOT NULL) AND ((" + DTSTART + " < ?) OR (" + DTEND + " < ?)))";
Cursor repeatingCursor = context.getContentResolver()
.query(
Events.CONTENT_URI,
new String[]{_ID, TITLE, DTSTART, EVENT_LOCATION, ALL_DAY, DISPLAY_COLOR, RRULE, DURATION}, repeatingSections,
selectionArgs, null
);
repeatingCursor.moveToFirst();
int repeatingCount = repeatingCursor.getCount();
if (repeatingCount != 0) {
//<editor-fold desc="repeating past Events">
for (int i = 0; i < repeatingCount; i++) {
int id = repeatingCursor.getInt(0);
String title = repeatingCursor.getString(1);
long startDate = Long.parseLong(repeatingCursor.getString(2));
String location = repeatingCursor.getString(3);
boolean isAllDay = repeatingCursor.getInt(4) != 0;
int color = repeatingCursor.getInt(5);
String rRule = repeatingCursor.getString(6);
String duration = repeatingCursor.getString(7);
if (!isAllDay) {
ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate, duration, location, color, title, id, false);
events = addEvents(events, repeatingEvents);
} else {
ArrayList<Event> repeatingEvents = getEventFromRepeating(context, rRule, startDate - timezone.getOffset(startDate), duration, location, color, title, id, true);
events = addEvents(events, repeatingEvents);
}
repeatingCursor.moveToNext();
}
//</editor-fold>
repeatingCursor.close();
}
}
Collections.sort(events, new Comparator<Event>() {
@Override
//an integer < 0 if lhs is less than rhs, 0 if they are equal, and > 0 if lhs is greater than rhs.
public int compare(Event lhs, Event rhs) {
int first = (lhs.getStartDate() - rhs.getStartDate()) < 0 ? -1 : lhs.getStartDate() == rhs.getStartDate() ? 0 : 1;
int second = (lhs.getEndDate() - rhs.getEndDate()) < 0 ? -1 : lhs.getEndDate() == rhs.getEndDate() ? 0 : 1;
return first != 0 ? first : second;
}
});
return events;
}
private static ArrayList<Event> addEvents(ArrayList<Event> list, ArrayList<Event> toAdd) {
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MONTH, 6);
long milli = DateUtils.clearTime(calendar).getTimeInMillis();
long now = System.currentTimeMillis();
for (Event event : toAdd) {
if (event.getEndDate() <= milli && event.getEndDate() >= now) list.add(event);
}
return list;
}
private static ArrayList<Event> getEventFromRepeating(Context context, String rRule, long startDate, String duration, String location, int color, String title, int id, boolean isAllDay) {
ArrayList<Event> events = new ArrayList<>();
final String[] INSTANCE_PROJECTION = new String[]{
CalendarContract.Instances.EVENT_ID, // 0
CalendarContract.Instances.BEGIN, // 1
CalendarContract.Instances.END // 2
};
Calendar endTime = Calendar.getInstance();
endTime.add(Calendar.MONTH, 6);
String selection = CalendarContract.Instances.EVENT_ID + " = ?";
Uri.Builder builder = CalendarContract.Instances.CONTENT_URI.buildUpon();
ContentUris.appendId(builder, System.currentTimeMillis());
ContentUris.appendId(builder, endTime.getTimeInMillis());
Cursor cursor = context.getContentResolver().query(builder.build(),
INSTANCE_PROJECTION,
selection,
new String[]{Integer.toString(id)},
null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(id, title, cursor.getLong(1) - (isAllDay ? timezone.getOffset(startDate) : 0),
cursor.getLong(2) - (isAllDay ? timezone.getOffset(startDate) : 0), location, isAllDay).setColor(color));
} while (cursor.moveToNext());
}
return events;
}
public static String getDateFromEvent(Event event) {
if (event.getDate() != null) return event.getDate();
else if (event.isAllDay()) {
Calendar startPlusOneDay = Calendar.getInstance();
startPlusOneDay.setTimeInMillis(event.getStartDate());
startPlusOneDay.add(Calendar.DAY_OF_YEAR, 1);
Calendar endTime = Calendar.getInstance();
endTime.setTimeInMillis(event.getEndDate());
if (DateUtils.isSameDay(startPlusOneDay, endTime)) {
startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1);
if (DateUtils.isToday(startPlusOneDay))
return CalendarResources.today + " " + CalendarResources.allDay;
else if (DateUtils.isTomorrow(startPlusOneDay))
return CalendarResources.tomorrow + " " + CalendarResources.allDay;
return dayFormatter.format(new Date(event.getStartDate()));
} else {
endTime.add(Calendar.DAY_OF_YEAR, -1);
startPlusOneDay.add(Calendar.DAY_OF_YEAR, -1);
if (DateUtils.isToday(startPlusOneDay)) {
if (DateUtils.isTomorrow(endTime))
return CalendarResources.today + " - " + CalendarResources.tomorrow;
else
return CalendarResources.today + " " + CalendarResources.allDay + " - " + fullDateFormat.format(endTime.getTime());
} else if (DateUtils.isTomorrow(startPlusOneDay))
return CalendarResources.tomorrow + " - " + fullDateFormat.format(endTime.getTime());
return fullDateFormat.format(new Date(event.getStartDate())) + " - " + fullDateFormat.format(endTime.getTime());
}
} else {
String text;
Date first = new Date(event.getStartDate());
Date end = new Date(event.getEndDate());
if (DateUtils.isSameDay(first, end)) {
if (DateUtils.isToday(first))
text = CalendarResources.today + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end);
else if (DateUtils.isWithinDaysFuture(first, 1))
text = CalendarResources.tomorrow + " " + hourFormatter.format(first) + " - " + hourFormatter.format(end);
else
text = dateFormatter.format(first) + " - " + hourFormatter.format(end);
} else if (DateUtils.isToday(first)) {
text = CalendarResources.today + hourFormatter.format(first) + " - " + otherDayFormatter.format(end);
} else {
text = otherDayFormatter.format(first) + " - " + otherDayFormatter.format(end);
}
return text;
}
}
public static Intent launchEventById(long id) {
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri.Builder uri = Events.CONTENT_URI.buildUpon();
uri.appendPath(Long.toString(id));
intent.setData(uri.build());
return intent;
}
public static String getTimeToEvent(Event event) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(event.getStartDate());
Calendar now = Calendar.getInstance();
now.set(Calendar.SECOND, 0);
now.set(Calendar.MILLISECOND, 0);
if (calendar.getTimeInMillis() <= now.getTimeInMillis()) return CalendarResources.now;
else {
long secondsLeft = (calendar.getTimeInMillis() - now.getTimeInMillis()) / 1000;
if (secondsLeft < 60) return CalendarResources.in + " 1 " + CalendarResources.minute;
long minutesLeft = secondsLeft / 60;
if (minutesLeft < 60)
return CalendarResources.in + " " + minutesLeft + " " + (minutesLeft > 1 ? CalendarResources.minutes : CalendarResources.minute);
long hoursLeft = minutesLeft / 50;
if (hoursLeft < 24)
return CalendarResources.in + " " + hoursLeft + " " + (hoursLeft > 1 ? CalendarResources.hours : CalendarResources.hour);
int days = (int) (hoursLeft / 24);
if (days < 30)
return CalendarResources.in + " " + days + " " + (days > 1 ? CalendarResources.days : CalendarResources.day);
int months = days / 30;
if (months < 12)
return CalendarResources.in + " " + months + " " + (months > 1 ? CalendarResources.months : CalendarResources.month);
else return CalendarResources.moreThenAYearLeft;
}
}
public static class CalendarResources {
public static String today;
public static String tomorrow;
public static String allDay;
public static String now;
public static String in;
public static String minute;
public static String minutes;
public static String hour;
public static String hours;
public static String day;
public static String days;
public static String week;
public static String weeks;
public static String month;
public static String months;
public static String moreThenAYearLeft;
public static void init(Context context) {
if (today == null || moreThenAYearLeft == null) {
today = context.getString(R.string.today);
tomorrow = context.getString(R.string.tomorrow);
allDay = context.getString(R.string.all_day);
now = context.getString(R.string.now);
in = context.getString(R.string.in);
String[] min = context.getString(R.string.minute_s).split("/");
minute = min[0];
minutes = min[1];
String[] hoursArray = context.getString(R.string.hour_s).split("/");
hour = hoursArray[0];
hours = hoursArray[1];
String[] dayArray = context.getString(R.string.day_s).split("/");
day = dayArray[0];
days = dayArray[1];
String[] weekArray = context.getString(R.string.week_s).split("/");
week = weekArray[0];
weeks = weekArray[1];
String[] monthArray = context.getString(R.string.month_s).split("/");
month = monthArray[0];
months = monthArray[1];
moreThenAYearLeft = context.getString(R.string.more_then_year);
}
}
}
}
|
gpl-3.0
|
PlamenHP/Softuni
|
Entity Framework/Introduction to DB Apps/3. Get Minion Names/Properties/AssemblyInfo.cs
|
1432
|
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("3. Get Minion Names")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("3. Get Minion Names")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("bc91e659-ee53-4238-ab47-d6f903948cb6")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
|
gpl-3.0
|
griest024/PokemonEssentialsEditor
|
lib/pkmnee/import/plugin/rmxp/rgss.rb
|
427
|
#===============================================================================
# Filename: rgss.rb
#
# Developer: Raku (rakudayo@gmail.com)
#
# Description: This is the core file to include to enable loading and dumping
# of RMXP's .rxdata files.
#===============================================================================
require_relative 'rgss_internal'
require_relative 'rgss_rpg'
require_relative 'rgss_mod'
|
gpl-3.0
|
glidelite/glidelite
|
src/action/bundle.h
|
1225
|
/*
* Copyright (c) 2018 Siloft
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef BUNDLE_H_
#define BUNDLE_H_
int bundle(int argc, char *argv[], int command_index);
#endif // BUNDLE_H_
|
gpl-3.0
|
CapsAdmin/goluwa
|
framework/lua/libraries/graphics/render2d/stencil.lua
|
3304
|
local render2d = ... or _G.render2d
do
local X, Y, W, H = 0,0
function render2d.SetScissor(x, y, w, h)
X = x
Y = y
W = w or render.GetWidth()
H = h or render.GetHeight()
if not x then
X = 0
Y = 0
render.SetScissor()
else
x, y = render2d.ScreenToWorld(-x, -y)
render.SetScissor(-x, -y, w, h)
end
end
function render2d.GetScissor()
return X, Y, W, H
end
utility.MakePushPopFunction(render2d, "Scissor")
end
do
function render2d.SetStencilState(tbl)
if tbl.function_ then
end
end
--[[
local function stencil_pass(func, ref)
if func == "never" then
return false
end
if func == "equal" then
return pixel == ref
end
end
local stencil_pass = stencil_pass(func, ref)
local depth_pass = depth_pass()
if depth_pass and stencil_pass then
elseif not depth_pass and stencil_pass then
elseif not stencil_pass then
if op == "incr" then
pixel = pixel + ref
end
end
1: 000000000 -- clear
2: 000111110 -- draw stencil rect
2: 000112210 -- draw stencil rect
2: 000111110 -- draw stencil rect
]]
local i = 0
local X,Y,W,H
function render2d.PushStencilRect(x,y,w,h, i_override)
render.StencilFunction("never", 1)
render.StencilOperation("increase", "keep", "zero")
render2d.PushTexture()
render.SetColorMask(0,0,0,0)
render2d.DrawRect(x,y,w,h)
render.SetColorMask(1,1,1,1)
render2d.PopTexture()
render.StencilFunction("equal", i)
i = i + 1
X,Y,W,H = x,y,w,h
end
function render2d.PopStencilRect()
render.StencilFunction("never", 1)
render.StencilOperation("decrease", "keep", "zero")
render2d.PushTexture()
render.SetColorMask(0,0,0,0)
render2d.DrawRect(X,Y,W,H)
render.SetColorMask(1,1,1,1)
render2d.PopTexture()
if i >= 4 then i = 0 end
end
local i = 0
local X,Y,W,H
function render2d.PushStencilRect2(x,y,w,h, i_override)
render.StencilFunction("never", 1)
render.StencilOperation("increase", "keep", "zero")
render2d.PushTexture()
render2d.DrawRect(x,y,w,h)
render2d.PopTexture()
render.StencilFunction("equal", i)
i = i + 1
X,Y,W,H = x,y,w,h
end
function render2d.PopStencilRect2()
render.StencilFunction("never", 1)
render.StencilOperation("decrease", "keep", "zero")
render2d.PushTexture()
render2d.DrawRect(X,Y,W,H)
render2d.PopTexture()
if i >= 4 then i = 0 end
end
end
do
local X, Y, W, H
function render2d.EnableClipRect(x, y, w, h, i)
i = i or 1
render.SetStencil(true)
render.GetFrameBuffer():ClearStencil(0) -- out = 0
render.StencilOperation("keep", "replace", "replace")
-- if true then stencil = 33 return true end
render.StencilFunction("always", i)
-- on fail, keep zero value
-- on success replace it with 33
-- write to the stencil buffer
-- on fail is probably never reached
render2d.PushTexture()
render.SetColorMask(0,0,0,0)
render2d.DrawRect(x, y, w, h)
render.SetColorMask(1,1,1,1)
render2d.PopTexture()
-- if stencil == 33 then stencil = 33 return true else return false end
render.StencilFunction("equal", i)
X = x
Y = y
W = w
H = h
end
function render2d.GetClipRect()
return X or 0, Y or 0, W or render.GetWidth(), H or render.GetHeight()
end
function render2d.DisableClipRect()
render.SetStencil(false)
end
end
|
gpl-3.0
|
tim740/skUtilities
|
src/uk/tim740/skUtilities/util/ExprTimeInTimeZone.java
|
1995
|
package uk.tim740.skUtilities.util;
import ch.njol.skript.lang.Expression;
import ch.njol.skript.lang.SkriptParser;
import ch.njol.skript.lang.util.SimpleExpression;
import ch.njol.util.Kleenean;
import org.bukkit.event.Event;
import uk.tim740.skUtilities.skUtilities;
import javax.annotation.Nullable;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
/**
* Created by tim740 on 11/09/2016
*/
public class ExprTimeInTimeZone extends SimpleExpression<String> {
private Expression<String> str;
@Override
@Nullable
protected String[] get(Event e) {
String s = str.getSingle(e);
String[] sl = new String[0];
try {
BufferedReader br = new BufferedReader(new FileReader(new File("plugins/Skript/config.sk").getAbsoluteFile()));
sl = br.lines().toArray(String[]::new);
br.close();
} catch (Exception x) {
skUtilities.prSysE(x.getMessage(), getClass().getSimpleName(), x);
}
String sf = "";
for (String aSl : sl) {
if (aSl.contains("date format: ")) {
sf = aSl.replaceFirst("date format: ", "");
}
}
String ff;
if (sf.equalsIgnoreCase("default")) {
ff = new SimpleDateFormat().toPattern();
} else {
ff = sf;
}
return new String[]{ZonedDateTime.ofInstant(Instant.now(), ZoneId.of(s)).format(DateTimeFormatter.ofPattern(ff))};
}
@SuppressWarnings("unchecked")
@Override
public boolean init(Expression<?>[] e, int i, Kleenean k, SkriptParser.ParseResult p) {
str = (Expression<String>) e[0];
return true;
}
@Override
public Class<? extends String> getReturnType() {
return String.class;
}
@Override
public boolean isSingle() {
return true;
}
@Override
public String toString(@Nullable Event e, boolean b) {
return getClass().getName();
}
}
|
gpl-3.0
|
petebrew/tellervo
|
Databases/cpgdb/readingnotes.sql
|
9192
|
-- Erase all reading notes for this VMeasurementID
CREATE OR REPLACE FUNCTION cpgdb.ClearReadingNotes(
tblVMeasurement.VMeasurementID%TYPE -- the vmeasurement to tie this to
) RETURNS integer AS $_$
DECLARE
_VMID ALIAS FOR $1;
VMOp text;
ret integer;
BEGIN
-- Get the VMeasurementOp
SELECT op.name INTO VMOp FROM tblVMeasurement
INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID)
WHERE vmeasurementID=_VMID;
IF NOT FOUND THEN
RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID;
END IF;
-- Just delete all the notes!
IF VMOp = 'Direct' THEN
DELETE FROM tblReadingReadingNote WHERE ReadingID IN
(SELECT readingID FROM tblVMeasurement
INNER JOIN tblMeasurement USING (measurementID)
INNER JOIN tblReading USING (measurementID)
INNER JOIN tblReadingReadingNote USING (readingID)
WHERE VMeasurementID=_VMID);
ELSE
DELETE FROM tblVMeasurementRelYearReadingNote WHERE VMeasurementID=_VMID;
END IF;
GET DIAGNOSTICS ret = ROW_COUNT;
RETURN ret;
END;
$_$ LANGUAGE PLPGSQL VOLATILE;
-- Add a reading note to this vmeasurement
CREATE OR REPLACE FUNCTION cpgdb.AddReadingNote(
tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to
int, -- The year to bind this note to (relative, starts at zero)
int, -- The reading note ID to add
boolean) -- Is this a force disabled override (only for non-direct, MUST BE NULL for direct)
RETURNS void AS $_$
DECLARE
_VMID ALIAS FOR $1;
_RelYear ALIAS FOR $2;
_ReadingNoteID ALIAS FOR $3;
_Override ALIAS FOR $4;
VMOp text;
myReadingID tblReading.ReadingID%TYPE;
myOverride boolean;
VMReadingCount int;
BEGIN
-- Get the VMeasurementOp
SELECT op.name INTO VMOp FROM tblVMeasurement
INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID)
WHERE vmeasurementID=_VMID;
IF NOT FOUND THEN
RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID;
END IF;
-- Direct VM -> Attach to Reading
IF VMOp = 'Direct' THEN
IF _Override IS NOT NULL THEN
RAISE EXCEPTION 'Override must not be set for Direct VMs';
END IF;
SELECT readingID INTO myReadingID
FROM tblVMeasurement
INNER JOIN tblMeasurement USING (measurementID)
INNER JOIN tblReading USING (measurementID)
WHERE VMeasurementID=_VMID AND RelYear=_RelYear;
IF NOT FOUND THEN
RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID;
END IF;
INSERT INTO tblReadingReadingNote (ReadingID, ReadingNoteID) VALUES (myReadingID, _ReadingNoteID);
ELSE
-- Derived VM -> Attach to vmeasurement
myOverride := _Override;
-- null override means false
IF myOverride IS NULL THEN
myOverride := FALSE;
END IF;
-- Validate relyear
SELECT readingCount INTO VMReadingCount FROM tblVMeasurementMetaCache WHERE VMeasurementID=_VMID;
IF NOT FOUND OR VMReadingCount <= _RelYear THEN
RAISE EXCEPTION 'VMeasurement % does not exist, is malformed, or relyear % is out of range.', _VMID, _RelYear;
END IF;
INSERT INTO tblVMeasurementRelYearReadingNote (VMeasurementID, RelYear, ReadingNoteID, DisabledOverride)
VALUES (_VMID, _RelYear, _ReadingNoteID, myOverride);
END IF;
END;
$_$ LANGUAGE PLPGSQL VOLATILE;
-- Add a CUSTOM reading note to this vmeasurement
-- Tries to find an existing match first
CREATE OR REPLACE FUNCTION cpgdb.AddCustomReadingNote(
tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to
int, -- The year to bind this note to (relative, starts at zero)
text) -- The custom reading note to add
RETURNS tlkpReadingNote AS $_$
DECLARE
_VMID ALIAS FOR $1;
_RelYear ALIAS FOR $2;
_NoteText ALIAS FOR $3;
VMOp text;
myReadingID tblReading.ReadingID%TYPE;
myOverride boolean;
VMReadingCount int;
myReadingNoteID tlkpReadingNote.ReadingNoteID%TYPE;
myVMRYRN tblVMeasurementRelYearReadingNote.RelYearReadingNoteID%TYPE;
outrow tlkpReadingNote%ROWTYPE;
BEGIN
-- Look for existing vocabulary case insensitively
SELECT ReadingNoteID INTO myReadingNoteID FROM tlkpReadingNote WHERE note ILIKE _NoteText;
IF FOUND THEN
PERFORM cpgdb.AddReadingNote(_VMID, _RelYear, myReadingNoteID, null);
SELECT * INTO outrow FROM tlkpReadingNote WHERE ReadingNoteID=myReadingNoteID;
RETURN outrow;
END IF;
-- Get the VMeasurementOp
SELECT op.name INTO VMOp FROM tblVMeasurement
INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID)
WHERE vmeasurementID=_VMID;
IF NOT FOUND THEN
RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID;
END IF;
-- Create a new reading note
myReadingNoteID := nextval('tlkpreadingnote_readingnoteid_seq'::regclass);
-- Direct VM -> Attach to Reading
IF VMOp = 'Direct' THEN
IF _Override IS NOT NULL THEN
RAISE EXCEPTION 'Override must not be set for Direct VMs';
END IF;
SELECT readingID INTO myReadingID
FROM tblVMeasurement
INNER JOIN tblMeasurement USING (measurementID)
INNER JOIN tblReading USING (measurementID)
WHERE VMeasurementID=_VMID AND RelYear=_RelYear;
IF NOT FOUND THEN
RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID;
END IF;
INSERT INTO tlkpReadingNote(ReadingNoteID, note, vocabularyid, parentReadingID) VALUES (myReadingNoteID, _NoteText, 0, myReadingID);
INSERT INTO tblReadingReadingNote (ReadingReadingNoteID, ReadingID, ReadingNoteID) VALUES (myRRNID, myReadingID, _ReadingNoteID);
ELSE
-- Validate relyear
SELECT readingCount INTO VMReadingCount FROM tblVMeasurementMetaCache WHERE VMeasurementID=_VMID;
IF NOT FOUND OR VMReadingCount <= _RelYear THEN
RAISE EXCEPTION 'VMeasurement % does not exist, is malformed, or relyear % is out of range.', _VMID, _RelYear;
END IF;
-- Complicated circular reference here :<
-- First, insert the new readingNote
INSERT INTO tlkpReadingNote(ReadingNoteID, note, vocabularyid) VALUES (myReadingNoteID, _NoteText, 0);
-- Now, insert a new tblVMeasurementRelYearReadingNote row
myVMRYRN := nextval('tblvmeasurementrelyearreadingnote_relyearreadingnoteid_seq'::regclass);
INSERT INTO tblVMeasurementRelYearReadingNote (RelYearReadingNoteID, VMeasurementID, RelYear, ReadingNoteID)
VALUES (myVMRYRN, _VMID, _RelYear, myReadingNoteID);
-- Now, tie the readingNote directly to the new row
UPDATE tlkpReadingNote SET parentVMRelYearReadingNoteID=myVMRYRN WHERE ReadingNoteID=myReadingNoteID;
END IF;
SELECT * INTO outrow FROM tlkpReadingNote WHERE ReadingNoteID=myReadingNoteID;
RETURN outrow;
END;
$_$ LANGUAGE PLPGSQL VOLATILE;
-- Remove a reading note from this vmeasurement
CREATE OR REPLACE FUNCTION cpgdb.RemoveReadingNote(
tblVMeasurement.VMeasurementID%TYPE, -- the vmeasurement to tie this to
int, -- The year to bind this note to (relative, starts at zero)
int) -- The reading note ID to add
RETURNS integer AS $_$
DECLARE
_VMID ALIAS FOR $1;
_RelYear ALIAS FOR $2;
_ReadingNoteID ALIAS FOR $3;
VMOp text;
myReadingID tblReading.ReadingID%TYPE;
ret integer;
BEGIN
-- Get the VMeasurementOp
SELECT op.name INTO VMOp FROM tblVMeasurement
INNER JOIN tlkpVMeasurementOp op USING (vmeasurementOpID)
WHERE vmeasurementID=_VMID;
IF NOT FOUND THEN
RAISE EXCEPTION 'Invalid/nonexistent vmeasurement %', _VMID;
END IF;
-- Direct VM -> Remove from Reading
IF VMOp = 'Direct' THEN
SELECT readingID INTO myReadingID
FROM tblVMeasurement
INNER JOIN tblMeasurement USING (measurementID)
INNER JOIN tblReading USING (measurementID)
WHERE VMeasurementID=_VMID AND RelYear=_RelYear;
IF NOT FOUND THEN
RAISE EXCEPTION 'No reading found for relyear % on vmeasurementid %. Year must exist.', _RelYear, _VMID;
END IF;
DELETE FROM tblReadingReadingNote WHERE ReadingID=myReadingID AND ReadingNoteID=_ReadingNoteID;
ELSE
-- Remove from RelYearReadingNote
DELETE FROM tblVMeasurementRelYearReadingNote WHERE VMeasurementID=_VMID AND RelYear=_RelYear AND ReadingNoteID=_ReadingNoteID;
END IF;
GET DIAGNOSTICS ret = ROW_COUNT;
RETURN ret;
END;
$_$ LANGUAGE PLPGSQL VOLATILE;
-- Param 1: Vocabulary name
-- Param 2: Note text
CREATE OR REPLACE FUNCTION cpgdb.GetNote(text, text) RETURNS tlkpReadingNote AS $_$
DECLARE
noterec tlkpReadingNote;
BEGIN
SELECT rnote.* INTO noterec
FROM tlkpReadingNote rnote
LEFT JOIN tlkpVocabulary voc USING (vocabularyid)
WHERE voc.name=$1 AND rnote.note=$2;
IF NOT FOUND THEN
RAISE EXCEPTION 'Note "%" not found for vocabulary "%"', $2, $1;
END IF;
RETURN noterec;
END;
$_$ LANGUAGE PLPGSQL STABLE;
|
gpl-3.0
|
allembedded/python_web_framework
|
WebApplication/Views/PageView.py
|
781
|
"""
Page view class
"""
import os
from Server.Importer import ImportFromModule
class PageView(ImportFromModule("Server.PageViewBase", "PageViewBase")):
"""
Page view class.
"""
_PAGE_TITLE = "Python Web Framework"
def __init__(self, htmlToLoad):
"""
Constructor.
- htmlToLoad : HTML to load
"""
self.SetPageTitle(self._PAGE_TITLE)
self.AddMetaData("charset=\"UTF-8\"")
self.AddMetaData("name=\"viewport\" content=\"width=device-width, initial-scale=1\"")
self.AddStyleSheet("/css/styles.css")
self.AddJavaScript("/js/http.js")
self.LoadHtml(os.path.join(os.path.dirname(__file__), "%s.html" % htmlToLoad))
self.SetPageData({ "PageTitle" : self._PAGE_TITLE })
|
gpl-3.0
|
minjing/uapi
|
uapi.service/src/main/java/uapi/service/ResponseCode.java
|
1491
|
/*
* Copyright (C) 2010 The UAPI Authors
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at the LICENSE file.
*
* You must gained the permission from the authors if you want to
* use the project into a commercial product
*/
package uapi.service;
import uapi.InvalidArgumentException;
import uapi.helper.ArgumentChecker;
import java.util.HashMap;
import java.util.Map;
/**
* Define response code
*/
public abstract class ResponseCode {
private final Map<String, String> _codeMsgKeyMapping = new HashMap<>();
private final MessageExtractor _msgExtractor = new MessageExtractor(this.getClass().getClassLoader());
public void init() {
getMessageLoader().registerExtractor(this._msgExtractor);
}
protected abstract MessageLoader getMessageLoader();
public String getMessageKey(final String code) {
ArgumentChecker.required(code, "code");
return this._codeMsgKeyMapping.get("code");
}
protected void addCodeMessageKeyMapping(String code, String messageKey) {
ArgumentChecker.required(code, "code");
ArgumentChecker.required(messageKey, "messageKey");
if (this._codeMsgKeyMapping.containsKey(code)) {
throw new InvalidArgumentException("Overwrite existing code message key is not allowed - {}", code);
}
this._codeMsgKeyMapping.put(code, messageKey);
this._msgExtractor.addDefinedKeys(messageKey);
}
}
|
gpl-3.0
|
agent4788/SHC_Framework
|
shc/lib/event/eventeditor.class.php
|
39876
|
<?php
namespace SHC\Event;
//Imports
use RWF\Date\DateTime;
use RWF\Util\StringUtils;
use SHC\Condition\Condition;
use SHC\Condition\ConditionEditor;
use SHC\Core\SHC;
use SHC\Switchable\Switchable;
use SHC\Switchable\SwitchableEditor;
/**
* Ereignise Verwalten
*
* @author Oliver Kleditzsch
* @copyright Copyright (c) 2014, Oliver Kleditzsch
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
* @since 2.0.0-0
* @version 2.0.0-0
*/
class EventEditor {
/**
* Ereignis Luftfeuchte steigt
*
* @var Integer
*/
const EVENT_HUMIDITY_CLIMB = 1;
/**
* Ereignis Luftfeuchte faellt
*
* @var Integer
*/
const EVENT_HUMIDITY_FALLS = 2;
/**
* Ereignis Eingang wechselt von LOW auf HIGH
*
* @var Integer
*/
const EVENT_INPUT_HIGH = 4;
/**
* Ereignis EIngang wechselt von HIGH auf LOW
*
* @var Integer
*/
const EVENT_INPUT_LOW = 8;
/**
* Ereignis Lichtstaerke steigt
*
* @var Integer
*/
const EVENT_LIGHTINTENSITY_CLIMB = 16;
/**
* Ereignis Lichtsaerke faellt
*
* @var Integer
*/
const EVENT_LIGHTINTENSITY_FALLS = 32;
/**
* Ereignis Feuchtigkeit steigt
*
* @var Integer
*/
const EVENT_MOISTURE_CLIMB = 64;
/**
* Ereignis Feuchtigkeit steigt
*
* @var Integer
*/
const EVENT_MOISTURE_FALLS = 128;
/**
* Ereignis Temperatur steigt
*
* @var Integer
*/
const EVENT_TEMPERATURE_CLIMB = 256;
/**
* Ereignis Temperatur faellt
*
* @var Integer
*/
const EVENT_TEMPERATURE_FALLS = 512;
/**
* Ereignis Benutzer kommt nach Hause
*
* @var Integer
*/
const EVENT_USER_COMES_HOME = 1024;
/**
* Ereignis Benutzer verlaesst das Haus
*
* @var Integer
*/
const EVENT_USER_LEAVE_HOME = 2048;
/**
* Ereignis Sonnenaufgang
*
* @var Integer
*/
const EVENT_SUNRISE = 4096;
/**
* Ereignis Sonnenuntergang
*
* @var Integer
*/
const EVENT_SUNSET = 8192;
/**
* Ereignis Datei erstellt
*
* @var Integer
*/
const EVENT_FILE_CREATE = 16384;
/**
* Ereignis Datei geloescht
*
* @var Integer
*/
const EVENT_FILE_DELETE = 32768;
/**
* nach ID sortieren
*
* @var String
*/
const SORT_BY_ID = 'id';
/**
* nach Namen sortieren
*
* @var String
*/
const SORT_BY_NAME = 'name';
/**
* nicht sortieren
*
* @var String
*/
const SORT_NOTHING = 'unsorted';
/**
* Ereignisse
*
* @var Array
*/
protected $events = array();
/**
* Singleton Instanz
*
* @var \SHC\Event\EventEditor
*/
protected static $instance = null;
/**
* name der HashMap
*
* @var String
*/
protected static $tableName = 'shc:events';
protected function __construct() {
$this->loadData();
}
/**
* laedt die Ereignisse aus den XML Daten und erzeugt die Objekte
*/
public function loadData() {
//Daten Vorbereiten
$oldEvents = $this->events;
$this->events = array();
$events = SHC::getDatabase()->hGetAllArray(self::$tableName);
//Daten einlesen
foreach ($events as $event) {
//Variablen Vorbereiten
$class = (string) $event['class'];
$data = array();
foreach ($event as $index => $value) {
if (!in_array($index, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) {
$data[$index] = $value;
}
}
/* @var $eventObj \SHC\Event\Event */
$eventObj = new $class(
(int) $event['id'], (string) $event['name'], $data, ((int) $event['enabled'] == true ? true : false), DateTime::createFromDatabaseDateTime((string) $event['lastExecute'])
);
//Bedingungen anhaengen
foreach ($event['conditions'] as $conditionId) {
$condition = ConditionEditor::getInstance()->getConditionByID($conditionId);
if ($condition instanceof Condition) {
$eventObj->addCondition($condition);
}
}
//schaltbare Elemente Hinzufuegen
if(isset($event['switchable'])) {
foreach ($event['switchable'] as $switchable) {
$switchableObject = SwitchableEditor::getInstance()->getElementById((int) $switchable['id']);
if ($switchableObject instanceof Switchable) {
$eventObj->addSwitchable($switchableObject, (int) $switchable['command']);
}
}
}
//Objekt status vom alten Objekt ins neue übertragen
if(isset($oldEvents[(int) $event['id']])) {
/* @var $eventObj \SHC\Event\Event */
$eventObj->setState($oldEvents[(int) $event['id']]->getState());
if($oldEvents[(int) $event['id']]->getTime() instanceof DateTime) {
$eventObj->setTime($oldEvents[(int) $event['id']]->getTime());
}
}
$this->events[(int) $event['id']] = $eventObj;
}
}
/**
* gibt das Ereignis mit der IOD zurueck
*
* @param int $id Ereignis ID
* @return \SHC\Event\Event
*/
public function getEventById($id) {
if (isset($this->events[$id])) {
return $this->events[$id];
}
return null;
}
/**
* prueft ob der Name des Events schon verwendet wird
*
* @param String $name Name
* @return Boolean
*/
public function isEventNameAvailable($name) {
foreach ($this->events as $event) {
/* @var $condition \SHC\Event\Event */
if (StringUtils::toLower($event->getName()) == StringUtils::toLower($name)) {
return false;
}
}
return true;
}
/**
* gibt eine Liste mit allen Bedingungen zurueck
*
* @param String $orderBy Art der Sortierung (
* id => nach ID sorieren,
* name => nach Namen sortieren,
* unsorted => unsortiert
* )
* @return Array
*/
public function listEvents($orderBy = 'id') {
if ($orderBy == 'id') {
//nach ID sortieren
$events = $this->events;
ksort($events, SORT_NUMERIC);
return $events;
} elseif ($orderBy == 'name') {
//nach Namen sortieren
$events = $this->events;
//Sortierfunktion
$orderFunction = function($a, $b) {
if ($a->getName() == $b->getName()) {
return 0;
}
if ($a->getName() < $b->getName()) {
return -1;
}
return 1;
};
usort($events, $orderFunction);
return $events;
}
return $this->events;
}
/**
* erstellt ein Event
*
* @param String $class Klassenname
* @param String $name Name
* @param Boolean $enabled Aktiv
* @param Array $data Zusatzdaten
* @param Array $conditions Liste der Bedingunen
* @return Boolean
* @throws \Exception
*/
protected function addEvent($class, $name, array $data = array(), $enabled = true, array $conditions) {
//Ausnahme wenn Name des Events schon belegt
if (!$this->isEventNameAvailable($name)) {
throw new \Exception('Der Name des Events ist schon vergeben', 1502);
}
$db = SHC::getDatabase();
$index = $db->autoIncrement(self::$tableName);
$newEvent = array(
'id' => $index,
'class' => $class,
'name' => $name,
'enabled' => ($enabled == true ? true : false),
'conditions' => $conditions,
'lastExecute' => '2000-01-01 00:00:00',
'switchable' => array()
);
foreach ($data as $tag => $value) {
if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) {
$newEvent[$tag] = $value;
}
}
if($db->hSetNxArray(self::$tableName, $index, $newEvent) == 0) {
return false;
}
return true;
}
/**
* bearbeitet ein Event
*
* @param Integer $id ID
* @param String $name Name
* @param Array $data Zusatzdaten
* @param Boolean $enabled Aktiv
* @param Array $conditions Liste der Bedingunen
* @return Boolean
* @throws \Exception
*/
protected function editEvent($id, $name = null, array $data = null, $enabled = null, array $conditions = null) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $id)) {
$event = $db->hGetArray(self::$tableName, $id);
//Name
if ($name !== null) {
//Ausnahme wenn Name der Bedingung schon belegt
if ((string) $event['name'] != $name && !$this->isEventNameAvailable($name)) {
throw new \Exception('Der Name der Bedingung ist schon vergeben', 1502);
}
$event['name'] = $name;
}
//Aktiv
if ($enabled !== null) {
$event['enabled'] = ($enabled == true ? 1 : 0);
}
//Bedingungen
if($conditions !== null) {
$event['conditions'] = implode(',', $conditions);
}
//Zusatzdaten
foreach($data as $tag => $value) {
if (!in_array($tag, array('id', 'name', 'class', 'enabled', 'conditions', 'lastExecute', 'switchable'))) {
if($value !== null) {
$event[$tag] = $value;
}
}
}
if($db->hSetArray(self::$tableName, $id, $event) == 0) {
return true;
}
}
return false;
}
/**
* Speichert den Zeitpunkt der letzten Ausfuehrung fuer ein Ereignis
*
* @param Integer $id Ereignis ID
* @param \RWF\Date\DateTime $lastExecute letzte Ausfuehrung
* @return Boolean
*/
public function updateLastExecute($id, DateTime $lastExecute) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $id)) {
$event = $db->hGetArray(self::$tableName, $id);
if(isset($event['id']) && $event['id'] == $id) {
$event['lastExecute'] = $lastExecute->getDatabaseDateTime();
if($db->hSetArray(self::$tableName, $id, $event) == 0) {
return true;
}
} else {
//Datensatz nicht mehr vorhanden
return false;
}
}
return false;
}
/**
* erstellt ein Luftfeuchte Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addHumidityClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\HumidityClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Luftfeuchte Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editHumidityClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Luftfeuchte Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addHumidityFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\HumidityFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Luftfeuchte Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editHumidityFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Lichtstaerke Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addLightIntensityClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\LightIntensityClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Lichtstaerke Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editLightIntensityClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Lichtstaerke Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addLightIntensityFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\LightIntensityFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Lichtstaerke Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editLightIntensityFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Feuchtigkeits Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addMoistureClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\MoistureClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Feuchtigkeits Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editMoistureClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Feuchtigkeits Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addMoistureFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\MoistureFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Feuchtigkeits Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert (Prozent)
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editMoistureFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Temperatur Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addTemperatureClimbOverEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\TemperatureClimbOver', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Temperatur Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editTemperatureClimbOverEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Temperatur Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addTemperatureFallsBelowEvent($name, $enabled, array $sensors, $limit, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\TemperatureFallsBelow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Temperatur Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $sensors Sensoren
* @param Float $limit Grenzwert
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editTemperatureFallsBelowEvent($id, $name = null, $enabled = null, array $sensors = null, $limit = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'sensors' => implode(',', $sensors),
'limit' => $limit,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Eingangsevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addInputHighEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\InputHigh', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Eingangsevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editInputHighEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Eingangsevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addInputLowEvent($name, $enabled, array $inputs, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\InputLow', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Eingangsevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $inputs Eingaenge
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editInputLowEvent($id, $name = null, $enabled = null, array $inputs = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'inputs' => implode(',', $inputs),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Benutzerevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addUserComesHomeEvent($name, $enabled, array $users, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\UserComesHome', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Benutzerevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editUserComesHomeEvent($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Benutzerevent
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addUserLeavesHomeEvent($name, $enabled, array $users, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\UserLeavesHome', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Benutzerevent
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $users benutzer zu Hause
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editUserLeavesHomeEvent($id, $name = null, $enabled = null, array $users = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'users' => implode(',', $users),
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein neuen Event Sonnenaufgang
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function addSunriseEvent($name, $enabled, array $conditions = null) {
//Speichern
return $this->addEvent('\SHC\Event\Events\Sunrise', $name, array(), $enabled, $conditions);
}
/**
* bearbeitet ein Event Sonnenaufgang
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function editSunriseEvent($id, $name = null, $enabled = null, array $conditions = null) {
//Speichern
return $this->editEvent($id, $name, array(), $enabled, $conditions);
}
/**
* erstellt ein neuen Event Sonnenuntergang
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function addSunsetEvent($name, $enabled, array $conditions = null) {
//Speichern
return $this->addEvent('\SHC\Event\Events\Sunset', $name, array(), $enabled, $conditions);
}
/**
* bearbeitet ein Event Sonnenuntergang
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param Array $conditions Liste der Bedingunen
*/
public function editSunsetEvent($id, $name = null, $enabled = null, array $conditions = null) {
//Speichern
return $this->editEvent($id, $name, array(), $enabled, $conditions);
}
/**
* erstellt ein Datei erstellt Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addFileCreateEvent($name, $enabled, $file, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\FileCreate', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Datei erstellt Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editFileCreateEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* erstellt ein Datei geloescht Event
*
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function addFileDeleteEvent($name, $enabled, $file, $interval, array $conditions = array()) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->addEvent('\SHC\Event\Events\FileDelete', $name, $data, $enabled, $conditions);
}
/**
* bearbeitet ein Datei geloescht Event
*
* @param Integer $id ID
* @param String $name Name
* @param Boolean $enabled Aktiviert
* @param String $file Datei
* @param Integer $interval Sperrzeit
* @param Array $conditions Liste der Bedingunen
* @return bool
*/
public function editFileDeleteEvent($id, $name = null, $enabled = null, $file = null, $interval = null, array $conditions = null) {
//Daten vorbereiten
$data = array(
'file' => $file,
'interval' => $interval
);
//Speichern
return $this->editEvent($id, $name, $data, $enabled, $conditions);
}
/**
* loascht ein Event
*
* @param Integer $id ID
* @return Boolean
*/
public function removeEvent($id) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $id)) {
if($db->hDel(self::$tableName, $id)) {
return true;
}
}
return false;
}
/**
* fuegt einem Event eine Bedingung hinzu
*
* @param Integer $eventId ID des Events
* @param Integer $conditionId ID der Bedingung
* @return Boolean
*/
public function addConditionToEvent($eventId, $conditionId) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
$event['conditions'][] = $conditionId;
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* entfernt eine Bedingung aus einem Event
*
* @param Integer $eventId ID des Events
* @param Integer $conditionId ID der Bedingung
* @return Boolean
*/
public function removeConditionFromEvent($eventId, $conditionId) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
$event['conditions'] = array_diff($event['conditions'], array($conditionId));
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* fuegt einem Event ein Schaltbares Element hinzu
*
* @param Integer $eventId ID des Events
* @param Integer $switchableId ID des Schaltbaren Elements
* @param Integer $command Befehl
* @return Boolean
*/
public function addSwitchableToEvent($eventId, $switchableId, $command) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
$event['switchable'][] = array('id' => $switchableId, 'command' => $command);
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* setzt den Befehl eines Schaltbaren Elements in einem Event
*
* @param Integer $eventId ID des Events
* @param Integer $switchableId ID des Schaltbaren Elements
* @param Integer $command Befehl
* @return Boolean
*/
public function setEventSwitchableCommand($eventId, $switchableId, $command) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
foreach($event['switchable'] as $index => $switchable) {
if($switchable['id'] == $switchableId) {
$event['switchable'][$index]['command'] = $command;
break;
}
}
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* entfernt ein Schaltbares Element von einem Event
*
* @param Integer $eventId ID des Events
* @param Integer $switchableId ID des Schaltbaren Elements
* @return Boolean
*/
public function removeSwitchableFromEvent($eventId, $switchableId) {
$db = SHC::getDatabase();
//pruefen ob Datensatz existiert
if($db->hExists(self::$tableName, $eventId)) {
$event = $db->hGetArray(self::$tableName, $eventId);
foreach($event['switchable'] as $index => $switchable) {
if($switchable['id'] == $switchableId) {
unset($event['switchable'][$index]);
break;
}
}
if($db->hSetArray(self::$tableName, $eventId, $event) == 0) {
return true;
}
}
return false;
}
/**
* geschuetzt wegen Singleton
*/
private function __clone() {
}
/**
* gibt den Ereignis Editor Editor zurueck
*
* @return \SHC\Event\EventEditor
*/
public static function getInstance() {
if (self::$instance === null) {
self::$instance = new EventEditor();
}
return self::$instance;
}
}
|
gpl-3.0
|
michaelBenin/raptor-editor
|
src/dependencies/jquery.js
|
274078
|
/*
* jQuery JavaScript Library v1.10.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-30T21:49Z
*/
(function( window, undefined ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//"use strict";
var
// The deferred used on DOM ready
readyList,
// A central reference to the root jQuery(document)
rootjQuery,
// Support: IE<10
// For `typeof xmlNode.method` instead of `xmlNode.method !== undefined`
core_strundefined = typeof undefined,
// Use the correct document accordingly with window argument (sandbox)
location = window.location,
document = window.document,
docElem = document.documentElement,
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// [[Class]] -> type pairs
class2type = {},
// List of deleted data cache ids, so we can reuse them
core_deletedIds = [],
core_version = "1.10.1",
// Save a reference to some core methods
core_concat = core_deletedIds.concat,
core_push = core_deletedIds.push,
core_slice = core_deletedIds.slice,
core_indexOf = core_deletedIds.indexOf,
core_toString = class2type.toString,
core_hasOwn = class2type.hasOwnProperty,
core_trim = core_version.trim,
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Used for matching numbers
core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,
// Used for splitting on whitespace
core_rnotwhite = /\S+/g,
// Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE)
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
},
// The ready event handler
completed = function( event ) {
// readyState === "complete" is good enough for us to call the dom ready in oldIE
if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
detach();
jQuery.ready();
}
},
// Clean-up method for dom ready events
detach = function() {
if ( document.addEventListener ) {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
} else {
document.detachEvent( "onreadystatechange", completed );
window.detachEvent( "onload", completed );
}
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: core_version,
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return core_slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
},
slice: function() {
return this.pushStack( core_slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: core_push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var src, copyIsArray, copy, name, options, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ),
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger("ready").off("ready");
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
/* jshint eqeqeq: false */
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
if ( obj == null ) {
return String( obj );
}
return typeof obj === "object" || typeof obj === "function" ?
class2type[ core_toString.call(obj) ] || "object" :
typeof obj;
},
isPlainObject: function( obj ) {
var key;
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!core_hasOwn.call(obj, "constructor") &&
!core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Support: IE<9
// Handle iteration over inherited properties before own properties.
if ( jQuery.support.ownLast ) {
for ( key in obj ) {
return core_hasOwn.call( obj, key );
}
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
for ( key in obj ) {}
return key === undefined || core_hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
parseHTML: function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
},
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( data ) {
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
}
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && jQuery.trim( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Use native String.trim function wherever possible
trim: core_trim && !core_trim.call("\uFEFF\xA0") ?
function( text ) {
return text == null ?
"" :
core_trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
core_push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
var len;
if ( arr ) {
if ( core_indexOf ) {
return core_indexOf.call( arr, elem, i );
}
len = arr.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in arr && arr[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var l = second.length,
i = first.length,
j = 0;
if ( typeof l === "number" ) {
for ( ; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var retVal,
ret = [],
i = 0,
length = elems.length;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return core_concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var args, proxy, tmp;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = core_slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
length = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < length; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// A method for quickly swapping in/out CSS properties to get correct calculations.
// Note: this method belongs to the css module but it's needed here for the support module.
// If support gets modularized, this method should be moved back to the css module.
swap: function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
// Standards-based browsers support DOMContentLoaded
} else if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
// If IE event model is used
} else {
// Ensure firing before onload, maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", completed );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", completed );
// If IE and not a frame
// continually check to see if the document is ready
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch(e) {}
if ( top && top.doScroll ) {
(function doScrollCheck() {
if ( !jQuery.isReady ) {
try {
// Use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
top.doScroll("left");
} catch(e) {
return setTimeout( doScrollCheck, 50 );
}
// detach all dom ready events
detach();
// and execute any waiting functions
jQuery.ready();
}
})();
}
}
}
return readyList.promise( obj );
};
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || type !== "function" &&
( length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj );
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
/*!
* Sizzle CSS Selector Engine v1.9.4-pre
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2013-05-27
*/
(function( window, undefined ) {
var i,
support,
cachedruns,
Expr,
getText,
isXML,
compile,
outermostContext,
sortInput,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
hasDuplicate = false,
sortOrder = function() { return 0; },
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
"*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
// Prefer arguments quoted,
// then not containing pseudos/brackets,
// then attribute selectors/non-parenthetical expressions,
// then anything else
// These preferences are here to reduce the number of selectors
// needing tokenize in the PSEUDO preFilter
pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rsibling = new RegExp( whitespace + "*[+~]" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
// BMP codepoint
high < 0 ?
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && context.parentNode || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* For feature detection
* @param {Function} fn The function to test for native support
*/
function isNative( fn ) {
return rnative.test( fn + "" );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key += " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied if the test fails
* @param {Boolean} test The result of a test. If true, null will be set as the handler in leiu of the specified handler
*/
function addHandle( attrs, handler, test ) {
attrs = attrs.split("|");
var current,
i = attrs.length,
setHandle = test ? null : handler;
while ( i-- ) {
// Don't override a user's handler
if ( !(current = Expr.attrHandle[ attrs[i] ]) || current === handler ) {
Expr.attrHandle[ attrs[i] ] = setHandle;
}
}
}
/**
* Fetches boolean attributes by node
* @param {Element} elem
* @param {String} name
*/
function boolHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
var val = elem.getAttributeNode( name );
return val && val.specified ?
val.value :
elem[ name ] === true ? name.toLowerCase() : null;
}
/**
* Fetches attributes without interpolation
* http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
* @param {Element} elem
* @param {String} name
*/
function interpolationHandler( elem, name ) {
// XML does not need to be checked as this will not be assigned for XML documents
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
/**
* Uses defaultValue to retrieve value in IE6/7
* @param {Element} elem
* @param {String} name
*/
function valueHandler( elem ) {
// Ignore the value *property* on inputs by using defaultValue
// Fallback to Sizzle.attr by returning undefined where appropriate
// XML does not need to be checked as this will not be assigned for XML documents
if ( elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns Returns -1 if a precedes b, 1 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Detect xml
* @param {Element|Object} elem An element or a document
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.parentWindow;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
if ( parent && parent.frameElement ) {
parent.attachEvent( "onbeforeunload", function() {
setDocument();
});
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
// Support: IE<8
// Prevent attribute/property "interpolation"
div.innerHTML = "<a href='#'></a>";
addHandle( "type|href|height|width", interpolationHandler, div.firstChild.getAttribute("href") === "#" );
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
addHandle( booleans, boolHandler, div.getAttribute("disabled") == null );
div.className = "i";
return !div.getAttribute("className");
});
// Support: IE<9
// Retrieving value should defer to defaultValue
support.input = assert(function( div ) {
div.innerHTML = "<input>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
});
// IE6/7 still return empty string for value,
// but are actually retrieving the property
addHandle( "value", valueHandler, support.attributes && support.input );
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = isNative(doc.querySelectorAll)) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select><option selected=''></option></select>";
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Opera 10-12/IE8
// ^= $= *= and empty values
// Should not select anything
// Support: Windows 8 Native Apps
// The type attribute is restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "t", "" );
if ( div.querySelectorAll("[t^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = isNative( (matches = docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = isNative(docElem.contains) || docElem.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( doc.createElement("div") ) & 1;
});
// Document order sorting
sortOrder = docElem.compareDocumentPosition ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b );
if ( compare ) {
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
}
// Not directly comparable, sort on existence of method
return a.compareDocumentPosition ? -1 : 1;
} :
function( a, b ) {
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
// Parentless nodes are either documents or disconnected
} else if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [elem] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = ( fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined );
return val === undefined ?
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null :
val;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
for ( ; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (see #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[5] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] && match[4] !== undefined ) {
match[2] = match[4];
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is only affected by element nodes and content nodes(including text(3), cdata(4)),
// not comment, processing instructions, or others
// Thanks to Diego Perini for the nodeName shortcut
// Greater than "@" means alpha characters (specifically not starting with "#" or "?")
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
function tokenize( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( tokens = [] );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
}
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var data, cache, outerCache,
dirkey = dirruns + " " + doneName;
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) {
if ( (data = cache[1]) === true || data === cachedruns ) {
return data === true;
}
} else {
cache = outerCache[ dir ] = [ dirkey ];
cache[1] = matcher( elem, context, xml ) || cachedruns;
if ( cache[1] === true ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
// A counter to specify which element is currently being matched
var matcherCachedRuns = 0,
bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, expandContext ) {
var elem, j, matcher,
setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
// We must always have either seed elements or context
elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1);
if ( outermost ) {
outermostContext = context !== document && context;
cachedruns = matcherCachedRuns;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
for ( ; (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
cachedruns = ++matcherCachedRuns;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !group ) {
group = tokenize( selector );
}
i = group.length;
while ( i-- ) {
cached = matcherFromTokens( group[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
}
return cached;
};
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function select( selector, context, results, seed ) {
var i, tokens, token, type, find,
match = tokenize( selector );
if ( !seed ) {
// Try to minimize operations if there is only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && context.parentNode || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
}
// Compile and execute a filtering function
// Provide `match` to avoid retokenization if we modified the selector above
compile( selector, match )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector )
);
return results;
}
// Deprecated
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Initialize against the default document
setDocument();
// Support: Chrome<<14
// Always assume duplicates if they aren't passed to the comparison function
[0, 0].sort( sortOrder );
support.detectDuplicates = hasDuplicate;
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})( window );
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Flag to know if list is currently firing
firing,
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// First callback to fire (used internally by add and fireWith)
firingStart,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( list && ( !fired || stack ) ) {
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var action = tuple[ 0 ],
fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = core_slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value;
if( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
jQuery.support = (function( support ) {
var all, a, input, select, fragment, opt, eventName, isSupported, i,
div = document.createElement("div");
// Setup
div.setAttribute( "className", "t" );
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
// Finish early in limited (non-browser) environments
all = div.getElementsByTagName("*") || [];
a = div.getElementsByTagName("a")[ 0 ];
if ( !a || !a.style || !all.length ) {
return support;
}
// First batch of tests
select = document.createElement("select");
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName("input")[ 0 ];
a.style.cssText = "top:1px;float:left;opacity:.5";
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
support.getSetAttribute = div.className !== "t";
// IE strips leading whitespace when .innerHTML is used
support.leadingWhitespace = div.firstChild.nodeType === 3;
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
support.tbody = !div.getElementsByTagName("tbody").length;
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
support.htmlSerialize = !!div.getElementsByTagName("link").length;
// Get the style information from getAttribute
// (IE uses .cssText instead)
support.style = /top/.test( a.getAttribute("style") );
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
support.hrefNormalized = a.getAttribute("href") === "/a";
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
support.opacity = /^0.5/.test( a.style.opacity );
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
support.cssFloat = !!a.style.cssFloat;
// Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
support.checkOn = !!input.value;
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
support.optSelected = opt.selected;
// Tests for enctype support on a form (#6743)
support.enctype = !!document.createElement("form").enctype;
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
support.html5Clone = document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>";
// Will be defined later
support.inlineBlockNeedsLayout = false;
support.shrinkWrapBlocks = false;
support.pixelPosition = false;
support.deleteExpando = true;
support.noCloneEvent = true;
support.reliableMarginRight = true;
support.boxSizingReliable = true;
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Support: IE<9
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
// Check if we can trust getAttribute("value")
input = document.createElement("input");
input.setAttribute( "value", "" );
support.input = input.getAttribute( "value" ) === "";
// Check if an input maintains its value after becoming a radio
input.value = "t";
input.setAttribute( "type", "radio" );
support.radioValue = input.value === "t";
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "checked", "t" );
input.setAttribute( "name", "t" );
fragment = document.createDocumentFragment();
fragment.appendChild( input );
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Support: IE<9
// Opera does not clone events (and typeof div.attachEvent === undefined).
// IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
if ( div.attachEvent ) {
div.attachEvent( "onclick", function() {
support.noCloneEvent = false;
});
div.cloneNode( true ).click();
}
// Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event)
// Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
for ( i in { submit: true, change: true, focusin: true }) {
div.setAttribute( eventName = "on" + i, "t" );
support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
// Support: IE<9
// Iteration over object's inherited properties before its own.
for ( i in jQuery( support ) ) {
break;
}
support.ownLast = i !== "0";
// Run tests that need a body at doc ready
jQuery(function() {
var container, marginDiv, tds,
divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
container = document.createElement("div");
container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px";
body.appendChild( container ).appendChild( div );
// Support: IE8
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Support: IE8
// Check if empty table cells still have offsetWidth/Height
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check box-sizing and margin behavior.
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
// Workaround failing boxSizing test due to offsetWidth returning wrong value
// with some non-1 values of body zoom, ticket #13543
jQuery.swap( body, body.style.zoom != null ? { zoom: 1 } : {}, function() {
support.boxSizing = div.offsetWidth === 4;
});
// Use window.getComputedStyle because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
marginDiv = div.appendChild( document.createElement("div") );
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
support.reliableMarginRight =
!parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight );
}
if ( typeof div.style.zoom !== core_strundefined ) {
// Support: IE<8
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Support: IE6
// Check if elements with layout shrink-wrap their children
div.style.display = "block";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
if ( support.inlineBlockNeedsLayout ) {
// Prevent IE 6 from affecting layout for positioned elements #11048
// Prevent IE from shrinking the body in IE 7 mode #12869
// Support: IE<8
body.style.zoom = 1;
}
}
body.removeChild( container );
// Null elements to avoid leaks in IE
container = div = tds = marginDiv = null;
});
// Null elements to avoid leaks in IE
all = select = fragment = opt = a = input = null;
return support;
})({});
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
function internalData( elem, name, data, pvt /* Internal Use Only */ ){
if ( !jQuery.acceptData( elem ) ) {
return;
}
var ret, thisCache,
internalKey = jQuery.expando,
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
id = elem[ internalKey ] = core_deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
// Avoid exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( typeof name === "string" ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
}
function internalRemoveData( elem, name, pvt ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split(" ");
}
}
} else {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = name.concat( jQuery.map( name, jQuery.camelCase ) );
}
i = name.length;
while ( i-- ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject( cache[ id ] ) ) {
return;
}
}
// Destroy the cache
if ( isNode ) {
jQuery.cleanData( [ elem ], true );
// Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
/* jshint eqeqeq: false */
} else if ( jQuery.support.deleteExpando || cache != cache.window ) {
/* jshint eqeqeq: true */
delete cache[ id ];
// When all else fails, null
} else {
cache[ id ] = null;
}
}
jQuery.extend({
cache: {},
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"applet": true,
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data ) {
return internalData( elem, name, data );
},
removeData: function( elem, name ) {
return internalRemoveData( elem, name );
},
// For internal use only.
_data: function( elem, name, data ) {
return internalData( elem, name, data, true );
},
_removeData: function( elem, name ) {
return internalRemoveData( elem, name, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
// Do not set data on non-element because it will not be cleared (#8335).
if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) {
return false;
}
var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ];
// nodes accept data unless otherwise specified; rejection can be conditional
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var attrs, name,
data = null,
i = 0,
elem = this[0];
// Special expections of .data basically thwart jQuery.access,
// so implement the relevant behavior ourselves
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attrs = elem.attributes;
for ( ; i < attrs.length; i++ ) {
name = attrs[i].name;
if ( name.indexOf("data-") === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
return arguments.length > 1 ?
// Sets one value
this.each(function() {
jQuery.data( this, key, value );
}) :
// Gets one value
// Try to fetch any internally stored data first
elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null;
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
var name;
for ( name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray(data) ) {
queue = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return jQuery._data( elem, key ) || jQuery._data( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
jQuery._removeData( elem, type + "queue" );
jQuery._removeData( elem, key );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while( i-- ) {
tmp = jQuery._data( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var nodeHook, boolHook,
rclass = /[\t\r\n\f]/g,
rreturn = /\r/g,
rfocusable = /^(?:input|select|textarea|button|object)$/i,
rclickable = /^(?:a|area)$/i,
ruseDefault = /^(?:checked|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
getSetInput = jQuery.support.input;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
elem.className = jQuery.trim( cur );
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j,
i = 0,
len = this.length,
proceed = arguments.length === 0 || typeof value === "string" && value;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( core_rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
elem.className = value ? jQuery.trim( cur ) : "";
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.match( core_rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
// Toggle whole class name
} else if ( type === core_strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
},
val: function( value ) {
var ret, hooks, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// Use proper attribute retrieval(#6932, #12072)
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
elem.text;
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// oldIE doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( jQuery(option).val(), values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === core_strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( core_rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
elem[ propName ] = false;
// Support: IE<9
// Also clear defaultChecked/defaultSelected (if appropriate)
} else {
elem[ jQuery.camelCase( "default-" + name ) ] =
elem[ propName ] = false;
}
// See #9699 for explanation of this approach (setting first, then removal)
} else {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
},
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
// Use proper attribute retrieval(#12072)
var tabindex = jQuery.find.attr( elem, "tabindex" );
return tabindex ?
parseInt( tabindex, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
-1;
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
// IE<8 needs the *property* name
elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
// Use defaultChecked and defaultSelected for oldIE
} else {
elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = jQuery.expr.attrHandle[ name ] || jQuery.find.attr;
jQuery.expr.attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
function( elem, name, isXML ) {
var fn = jQuery.expr.attrHandle[ name ],
ret = isXML ?
undefined :
/* jshint eqeqeq: false */
(jQuery.expr.attrHandle[ name ] = undefined) !=
getter( elem, name, isXML ) ?
name.toLowerCase() :
null;
jQuery.expr.attrHandle[ name ] = fn;
return ret;
} :
function( elem, name, isXML ) {
return isXML ?
undefined :
elem[ jQuery.camelCase( "default-" + name ) ] ?
name.toLowerCase() :
null;
};
});
// fix oldIE attroperties
if ( !getSetInput || !getSetAttribute ) {
jQuery.attrHooks.value = {
set: function( elem, value, name ) {
if ( jQuery.nodeName( elem, "input" ) ) {
// Does not return so that setAttribute is also used
elem.defaultValue = value;
} else {
// Use nodeHook if defined (#1954); otherwise setAttribute is fine
return nodeHook && nodeHook.set( elem, value, name );
}
}
};
}
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = {
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
elem.setAttributeNode(
(ret = elem.ownerDocument.createAttribute( name ))
);
}
ret.value = value += "";
// Break association with cloned elements by also using setAttribute (#9646)
return name === "value" || value === elem.getAttribute( name ) ?
value :
undefined;
}
};
jQuery.expr.attrHandle.id = jQuery.expr.attrHandle.name = jQuery.expr.attrHandle.coords =
// Some attributes are constructed with empty-string values when not defined
function( elem, name, isXML ) {
var ret;
return isXML ?
undefined :
(ret = elem.getAttributeNode( name )) && ret.value !== "" ?
ret.value :
null;
};
jQuery.valHooks.button = {
get: function( elem, name ) {
var ret = elem.getAttributeNode( name );
return ret && ret.specified ?
ret.value :
undefined;
},
set: nodeHook.set
};
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
set: function( elem, value, name ) {
nodeHook.set( elem, value === "" ? false : value, name );
}
};
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
};
});
}
// Some attributes require a special call on IE
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !jQuery.support.hrefNormalized ) {
// href/src property should get the full normalized URL (#10299/#12915)
jQuery.each([ "href", "src" ], function( i, name ) {
jQuery.propHooks[ name ] = {
get: function( elem ) {
return elem.getAttribute( name, 4 );
}
};
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Note: IE uppercases css property names, but if we were to .toLowerCase()
// .cssText, that would destroy case senstitivity in URL's, like in "background"
return elem.style.cssText || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = value + "" );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !jQuery.support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
var rformElems = /^(?:input|select|textarea)$/i,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var tmp, events, t, handleObjIn,
special, eventHandle, handleObj,
handlers, type, namespaces, origType,
elemData = jQuery._data( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, handleObj, tmp,
origCount, t, events,
special, handlers, type,
namespaces, origType,
elemData = jQuery.hasData( elem ) && jQuery._data( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( core_rnotwhite ) || [""];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery._removeData( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var handle, ontype, cur,
bubbleType, special, tmp, i,
eventPath = [ elem || document ],
type = core_hasOwn.call( event, "type" ) ? event.type : event,
namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
try {
elem[ type ]();
} catch ( e ) {
// IE<9 dies on focus/blur to hidden element (#1486,#12518)
// only reproducible on winXP IE8 native, not IE9 in IE8 mode
}
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, ret, handleObj, matched, j,
handlerQueue = [],
args = core_slice.call( arguments ),
handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var sel, handleObj, matches, i,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
/* jshint eqeqeq: false */
for ( ; cur != this; cur = cur.parentNode || this ) {
/* jshint eqeqeq: true */
// Don't check non-elements (#13208)
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: IE<9
// Fix target property (#1925)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Support: Chrome 23+, Safari?
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// Support: IE<9
// For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
event.metaKey = !!event.metaKey;
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var body, eventDoc, doc,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
try {
this.focus();
return false;
} catch ( e ) {
// Support: IE<9
// If we error on focus to hidden element (#1486, #12518),
// let .trigger() run the handlers
}
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Even when returnValue equals to undefined Firefox will still show alert
if ( event.result !== undefined ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
var name = "on" + type;
if ( elem.detachEvent ) {
// #8545, #7054, preventing memory leaks for custom events in IE6-8
// detachEvent needed property on element, by name of that event, to properly expose it to GC
if ( typeof elem[ name ] === core_strundefined ) {
elem[ name ] = null;
}
elem.detachEvent( name, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( !e ) {
return;
}
// If preventDefault exists, run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// Support: IE
// Otherwise set the returnValue property of the original event to false
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( !e ) {
return;
}
// If stopPropagation exists, run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// Support: IE
// Set the cancelBubble property of the original event to true
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !jQuery._data( form, "submitBubbles" ) ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
jQuery._data( form, "submitBubbles", true );
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
}
// Allow triggered, simulated change events (#11500)
jQuery.event.simulate( "change", this, event, true );
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
jQuery._data( elem, "changeBubbles", true );
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return !rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var type, origFn;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var isSimple = /^.[^:#\[\.,]*$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
rneedsContext = jQuery.expr.match.needsContext,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var i,
ret = [],
self = this,
len = self.length;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
has: function( target ) {
var i,
targets = jQuery( target, this ),
len = targets.length;
return this.filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
cur = ret.push( cur );
break;
}
}
}
return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
do {
cur = cur[ dir ];
} while ( cur && cur.nodeType !== 1 );
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
ret = jQuery.unique( ret );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
ret = ret.reverse();
}
}
return this.pushStack( ret );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( isSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
manipulation_rcheckableType = /^(?:checkbox|radio)$/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
area: [ 1, "<map>", "</map>" ],
param: [ 1, "<object>", "</object>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
// IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
// unless wrapped in a div with non-breaking characters in front of it.
_default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
},
safeFragment = createSafeFragment( document ),
fragmentDiv = safeFragment.appendChild( document.createElement("div") );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
// If this is a select, ensure that it displays empty (#12336)
// Support: IE<9
if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
elem.options.length = 0;
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
undefined;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var
// Snapshot the DOM in case .domManip sweeps something relevant into its fragment
args = jQuery.map( this, function( elem ) {
return [ elem.nextSibling, elem.parentNode ];
}),
i = 0;
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
var next = args[ i++ ],
parent = args[ i++ ];
if ( parent ) {
// Don't use the snapshot next if it has moved (#13810)
if ( next && next.parentNode !== parent ) {
next = this.nextSibling;
}
jQuery( this ).remove();
parent.insertBefore( elem, next );
}
// Allow new content to include elements from the context set
}, true );
// Force removal if there was no new content (e.g., from empty arguments)
return i ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback, allowIntersection ) {
// Flatten any nested arrays
args = core_concat.apply( [], args );
var first, node, hasScripts,
scripts, doc, fragment,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[0],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[0] = value.call( this, index, self.html() );
}
self.domManip( args, callback, allowIntersection );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, !allowIntersection && this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[i], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Hope ajax is available...
jQuery._evalUrl( node.src );
} else {
jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
}
}
}
}
// Fix #11809: Avoid leaking memory
fragment = first = null;
}
}
return this;
}
});
// Support: IE<8
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType === 1 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[1];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var elem,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
}
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function fixCloneNodeIssues( src, dest ) {
var nodeName, e, data;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 copies events bound via attachEvent when using cloneNode.
if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) {
data = jQuery._data( dest );
for ( e in data.events ) {
jQuery.removeEvent( dest, e, data.handle );
}
// Event data gets referenced instead of copied if the expando gets copied too
dest.removeAttribute( jQuery.expando );
}
// IE blanks contents when cloning scripts, and tries to evaluate newly-set text
if ( nodeName === "script" && dest.text !== src.text ) {
disableScript( dest ).text = src.text;
restoreScript( dest );
// IE6-10 improperly clones children of object elements using classid.
// IE10 throws NoModificationAllowedError if parent is null, #12132.
} else if ( nodeName === "object" ) {
if ( dest.parentNode ) {
dest.outerHTML = src.outerHTML;
}
// This path appears unavoidable for IE9. When cloning an object
// element in IE9, the outerHTML strategy above is not sufficient.
// If the src has innerHTML and the destination does not,
// copy the src.innerHTML into the dest.innerHTML. #10324
if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
dest.innerHTML = src.innerHTML;
}
} else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
dest.defaultChecked = dest.checked = src.checked;
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.defaultSelected = dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
i = 0,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone(true);
jQuery( insert[i] )[ original ]( elems );
// Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
core_push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
function getAll( context, tag ) {
var elems, elem,
i = 0,
found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) :
typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) :
undefined;
if ( !found ) {
for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
if ( !tag || jQuery.nodeName( elem, tag ) ) {
found.push( elem );
} else {
jQuery.merge( found, getAll( elem, tag ) );
}
}
}
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], found ) :
found;
}
// Used in buildFragment, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( manipulation_rcheckableType.test( elem.type ) ) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var destElements, node, clone, i, srcElements,
inPage = jQuery.contains( elem.ownerDocument, elem );
if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
clone = elem.cloneNode( true );
// IE<=8 does not properly clone detached, unknown element nodes
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
}
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
// Fix all IE cloning issues
for ( i = 0; (node = srcElements[i]) != null; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
fixCloneNodeIssues( node, destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0; (node = srcElements[i]) != null; i++ ) {
cloneCopyEvent( node, destElements[i] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
destElements = srcElements = node = null;
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var j, elem, contains,
tmp, tag, tbody, wrap,
l = elems.length,
// Ensure a safe fragment
safe = createSafeFragment( context ),
nodes = [],
i = 0;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || safe.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
// Descend through wrappers to the right content
j = wrap[0];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Manually add leading whitespace removed by IE
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
elem = tag === "table" && !rtbody.test( elem ) ?
tmp.firstChild :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !rtbody.test( elem ) ?
tmp :
0;
j = elem && elem.childNodes.length;
while ( j-- ) {
if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
elem.removeChild( tbody );
}
}
}
jQuery.merge( nodes, tmp.childNodes );
// Fix #12392 for WebKit and IE > 9
tmp.textContent = "";
// Fix #12392 for oldIE
while ( tmp.firstChild ) {
tmp.removeChild( tmp.firstChild );
}
// Remember the top-level container for proper cleanup
tmp = safe.lastChild;
}
}
}
// Fix #11356: Clear elements from fragment
if ( tmp ) {
safe.removeChild( tmp );
}
// Reset defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
if ( !jQuery.support.appendChecked ) {
jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
}
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( safe.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
tmp = null;
return safe;
},
cleanData: function( elems, /* internal */ acceptData ) {
var elem, type, id, data,
i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( acceptData || jQuery.acceptData( elem ) ) {
id = elem[ internalKey ];
data = id && cache[ id ];
if ( data ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
// Remove cache only if it was not already removed by jQuery.event.remove
if ( cache[ id ] ) {
delete cache[ id ];
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( deleteExpando ) {
delete elem[ internalKey ];
} else if ( typeof elem.removeAttribute !== core_strundefined ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
core_deletedIds.push( id );
}
}
}
}
},
_evalUrl: function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
}
});
jQuery.fn.extend({
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
var iframe, getStyles, curCSS,
ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity\s*=\s*([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ),
rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ),
elemdisplay = { BODY: "block" },
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
},
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name.charAt(0).toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function isHidden( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = jQuery._data( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) );
}
} else {
if ( !values[ index ] ) {
hidden = isHidden( elem );
if ( display && display !== "none" || !hidden ) {
jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.fn.extend({
css: function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
var len, styles,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
var bool = typeof state === "boolean";
return this.each(function() {
if ( bool ? state : isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var num, val, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
// NOTE: we've included the "window" in window.getComputedStyle
// because jsdom on node.js will break without it.
if ( window.getComputedStyle ) {
getStyles = function( elem ) {
return window.getComputedStyle( elem, null );
};
curCSS = function( elem, name, _computed ) {
var width, minWidth, maxWidth,
computed = _computed || getStyles( elem ),
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined,
style = elem.style;
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// A tribute to the "awesome hack by Dean Edwards"
// Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
// Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if ( document.documentElement.currentStyle ) {
getStyles = function( elem ) {
return elem.currentStyle;
};
curCSS = function( elem, name, _computed ) {
var left, rs, rsLeft,
computed = _computed || getStyles( elem ),
ret = computed ? computed[ name ] : undefined,
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && style[ name ] ) {
ret = style[ name ];
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
// but not position css attributes, as those are proportional to the parent element instead
// and we can't measure the parent instead because it might trigger a "stacking dolls" problem
if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
// Remember the original values
left = style.left;
rs = elem.runtimeStyle;
rsLeft = rs && rs.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
rs.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
rs.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
// Try to determine the default display value of an element
function css_defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = ( iframe ||
jQuery("<iframe frameborder='0' width='0' height='0'/>")
.css( "cssText", "display:block !important" )
).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document;
doc.write("<!doctype html><html><body>");
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
// Called ONLY from within css_defaultDisplay
function actualDisplay( name, doc ) {
var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
display = jQuery.css( elem[0], "display" );
elem.remove();
return display;
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
// if value === "", then remove inline opacity #12685
if ( ( value >= 1 || value === "" ) &&
jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
style.removeAttribute ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there is no filter style applied in a css rule or unset inline opacity, we are done
if ( value === "" || currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
// These hooks cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
jQuery(function() {
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
};
}
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
if ( !jQuery.support.pixelPosition && jQuery.fn.position ) {
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = {
get: function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
};
});
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
(!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function(){
var type = this.type;
// Use .is(":disabled") so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !manipulation_rcheckableType.test( type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
//Serialize an array of form elements or a set of
//key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var
// Document location
ajaxLocParts,
ajaxLocation,
ajax_nonce = jQuery.now(),
ajax_rquery = /\?/,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var deep, key,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, response, type,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){
jQuery.fn[ type ] = function( fn ){
return this.on( type, fn );
};
});
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Cross-domain detection vars
parts,
// Loop variable
i,
// URL without anti-cache param
cacheURL,
// Response headers as string
responseHeadersString,
// timeout handle
timeoutTimer,
// To know if global events are to be dispatched
fireGlobals,
transport,
// Response headers
responseHeaders,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) :
// Otherwise add one to the end
cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var firstDataType, ct, finalDataType, type,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || jQuery("head")[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement("script");
script.async = true;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( script.parentNode ) {
script.parentNode.removeChild( script );
}
// Dereference the script
script = null;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
// Use native DOM manipulation to avoid our domManip AJAX trickery
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( undefined, true );
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
var xhrCallbacks, xhrSupported,
xhrId = 0,
// #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject && function() {
// Abort all pending requests
var key;
for ( key in xhrCallbacks ) {
xhrCallbacks[ key ]( undefined, true );
}
};
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
xhrSupported = jQuery.ajaxSettings.xhr();
jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
xhrSupported = jQuery.support.ajax = !!xhrSupported;
// Create transport if the browser can provide an xhr
if ( xhrSupported ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var handle, i,
xhr = s.xhr();
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( err ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status, responseHeaders, statusText, responses;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occurred
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
responses = {};
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
if ( typeof xhr.responseText === "string" ) {
responses.text = xhr.responseText;
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
if ( !s.async ) {
// if we're in sync mode we fire the callback
callback();
} else if ( xhr.readyState === 4 ) {
// (IE6 & IE7) if it's in cache and has been
// retrieved directly we need to fire the callback
setTimeout( callback );
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback( undefined, true );
}
}
};
}
});
}
var fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
}]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = jQuery._data( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( elem, "display" ) === "inline" &&
jQuery.css( elem, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
if ( !jQuery.support.shrinkWrapBlocks ) {
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
continue;
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = jQuery._data( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
jQuery._removeData( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE <=9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || jQuery._data( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = jQuery._data( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = jQuery._data( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
attrs = { height: type },
i = 0;
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth? 1 : 0;
for( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p*Math.PI ) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer,
timers = jQuery.timers,
i = 0;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
if ( timer() && jQuery.timers.push( timer ) ) {
jQuery.fx.start();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Back Compat <1.8 extension point
jQuery.fx.step = {};
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
box = { top: 0, left: 0 },
elem = this[ 0 ],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== core_strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
};
};
jQuery.offset = {
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
parentOffset = { top: 0, left: 0 },
elem = this[ 0 ];
// fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// we assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
win.document.documentElement[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return jQuery.access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// Limit scope pollution from any deprecated API
// (function() {
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// })();
if ( typeof module === "object" && module && typeof module.exports === "object" ) {
// Expose jQuery as module.exports in loaders that implement the Node
// module pattern (including browserify). Do not create the global, since
// the user will be storing it themselves locally, and globals are frowned
// upon in the Node module world.
module.exports = jQuery;
} else {
// Otherwise expose jQuery to the global object as usual
window.jQuery = window.$ = jQuery;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function () { return jQuery; } );
}
}
})( window );
|
gpl-3.0
|
NoHomey/FMI-introduction-to-programming-course
|
homework1/task10.cc
|
4135
|
#include <iostream>
using namespace std;
#define FLOAT(name, value) float name = value
#define CONST_FLOAT(name, value) const FLOAT(name, value)
#define VAR_FLOAT(name) FLOAT(name, 0)
#define VAR_INT(name) int name = 0
#define DEFINE_LINEAR_EQUATION(n)\
VAR_FLOAT(a##n);\
VAR_FLOAT(b##n);\
VAR_FLOAT(c##n)\
#define READ(input) cin >> input
#define IS_LESS_THAN_EPSILON(diff) ((diff < EPSILON) && (diff > -EPSILON))
#define READ_LINEAR_EQUATION(n)\
READ(a##n);\
READ(b##n);\
READ(c##n)\
#define IS_ZERO(value) IS_LESS_THAN_EPSILON(value)
#define IS_NOT_ZERO(value) (!IS_LESS_THAN_EPSILON(value))
#define IS_NOT_ZERO_LINE(line) (IS_NOT_ZERO(a##line) || IS_NOT_ZERO(b##line) || IS_NOT_ZERO(c##line))
#define SOLUTION_PART_1(n, divisor) c##n / divisor##n
#define SOLUTION_PART_2(n, multiplier, found, divisor) (c##n - (multiplier##n * found)) / divisor##n
#define ONE_SOLUTION() solution = One
#define NO_SOLUTION() solution = No
#define GAUSE(n1, n2, n3, cnt , calc)\
CONST_FLOAT(k##n1, (-cnt##n2) / cnt##n1);\
CONST_FLOAT(calc##n3, (calc##n1 * k##n1) + calc##n2);\
CONST_FLOAT(c##n3, (c##n1 * k##n1) + c##n2)\
#define IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(zero, first, second, divisor1, divisor2, n1, n2)\
if(IS_ZERO(zero) && (solution == Many)) {\
if IS_ZERO(divisor1##n1) {\
NO_SOLUTION();\
} else {\
first = SOLUTION_PART_1(n1, divisor1);\
second = SOLUTION_PART_2(n2, divisor1, first, divisor2);\
ONE_SOLUTION();\
}\
}\
#define FIND_SOLUTION(n, first, second, k, divisor1, divisor2)\
CONST_FLOAT(first##n, SOLUTION_PART_1(k, divisor1));\
CONST_FLOAT(second##n, SOLUTION_PART_2(n, divisor1, first##n, divisor2))\
#define DIFF(F, f) CONST_FLOAT(DIFF_##F, f##1 - f##2)
#define PRINT(value) cout << value
#define PRINT_CASE(what, message)\
case what:\
PRINT(message);\
break\
#define IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(a, b, m)\
if((absWholePart >= a) && (absWholePart < b)) {\
multiplier = m;\
}\
#define FORMAT(num)\
sign = (num <= -EPSILON ? -1 : 1);\
wholePart = num + (sign * EPSILON);\
multiplier = 1;\
absWholePart = sign * wholePart;\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(0, 10, 10000)\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(10, 100, 1000)\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(100, 1000, 100)\
IF_ABS_WHOLE_PART_BETWEEN_THAN_MULTIPLIER(1000, 10000, 10)\
floatPart = (int)((num + (sign * EPSILON)) * multiplier) - (wholePart * multiplier);\
num = ((float)floatPart / multiplier) + wholePart\
/* @begin */
enum Solution {
No,
One,
Many
};
CONST_FLOAT(EPSILON, 0.00001);
int main() {
DEFINE_LINEAR_EQUATION(1);
DEFINE_LINEAR_EQUATION(2);
VAR_FLOAT(x);
VAR_FLOAT(y);
Solution solution = Many;
READ_LINEAR_EQUATION(1);
READ_LINEAR_EQUATION(2);
if(IS_NOT_ZERO_LINE(1) && IS_NOT_ZERO_LINE(2)) {
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(a1, y, x, b, a, 1, 2)
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(a2, y, x, b, a, 2, 1)
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(b1, x, y, a, b, 1, 2)
IF_ZERO_AND_NO_SOLUTION_THAN_SOLVE(b2, x, y, a, b, 2, 1)
if(solution == Many) {
GAUSE(1, 2, 3, a, b);
GAUSE(2, 1, 4, b, a);
if((IS_ZERO(b3) && IS_NOT_ZERO(c3)) || (IS_ZERO(a4) && IS_NOT_ZERO(c4))) {
NO_SOLUTION();
} else {
FIND_SOLUTION(1, y, x, 3, b, a);
FIND_SOLUTION(2, x, y, 4, a, b);
DIFF(X, x);
DIFF(Y, y);
if(IS_LESS_THAN_EPSILON(DIFF_X) && IS_LESS_THAN_EPSILON(DIFF_Y)) {
x = x1;
y = y1;
ONE_SOLUTION();
}
}
}
}
switch(solution) {
PRINT_CASE(No, "No solution");
PRINT_CASE(Many, "Many solutions");
case One:
VAR_INT(sign);
VAR_INT(wholePart);
VAR_INT(absWholePart);
VAR_INT(floatPart);
VAR_INT(multiplier);
FORMAT(x);
FORMAT(y);
PRINT(x) << ' ' << y;
break;
}
PRINT('\n');
return 0;
}
|
gpl-3.0
|
matlink/SMSSecure
|
src/org/smssecure/smssecure/recipients/RecipientFactory.java
|
4267
|
/**
* Copyright (C) 2011 Whisper Systems
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.smssecure.smssecure.recipients;
import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import org.smssecure.smssecure.contacts.avatars.ContactPhotoFactory;
import org.smssecure.smssecure.database.CanonicalAddressDatabase;
import org.smssecure.smssecure.util.Util;
import org.whispersystems.libaxolotl.util.guava.Optional;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
public class RecipientFactory {
private static final RecipientProvider provider = new RecipientProvider();
public static Recipients getRecipientsForIds(Context context, String recipientIds, boolean asynchronous) {
if (TextUtils.isEmpty(recipientIds))
return new Recipients();
return getRecipientsForIds(context, Util.split(recipientIds, " "), asynchronous);
}
public static Recipients getRecipientsFor(Context context, List<Recipient> recipients, boolean asynchronous) {
long[] ids = new long[recipients.size()];
int i = 0;
for (Recipient recipient : recipients) {
ids[i++] = recipient.getRecipientId();
}
return provider.getRecipients(context, ids, asynchronous);
}
public static Recipients getRecipientsFor(Context context, Recipient recipient, boolean asynchronous) {
long[] ids = new long[1];
ids[0] = recipient.getRecipientId();
return provider.getRecipients(context, ids, asynchronous);
}
public static Recipient getRecipientForId(Context context, long recipientId, boolean asynchronous) {
return provider.getRecipient(context, recipientId, asynchronous);
}
public static Recipients getRecipientsForIds(Context context, long[] recipientIds, boolean asynchronous) {
return provider.getRecipients(context, recipientIds, asynchronous);
}
public static Recipients getRecipientsFromString(Context context, @NonNull String rawText, boolean asynchronous) {
StringTokenizer tokenizer = new StringTokenizer(rawText, ",");
List<String> ids = new LinkedList<>();
while (tokenizer.hasMoreTokens()) {
Optional<Long> id = getRecipientIdFromNumber(context, tokenizer.nextToken());
if (id.isPresent()) {
ids.add(String.valueOf(id.get()));
}
}
return getRecipientsForIds(context, ids, asynchronous);
}
private static Recipients getRecipientsForIds(Context context, List<String> idStrings, boolean asynchronous) {
long[] ids = new long[idStrings.size()];
int i = 0;
for (String id : idStrings) {
ids[i++] = Long.parseLong(id);
}
return provider.getRecipients(context, ids, asynchronous);
}
private static Optional<Long> getRecipientIdFromNumber(Context context, String number) {
number = number.trim();
if (number.isEmpty()) return Optional.absent();
if (hasBracketedNumber(number)) {
number = parseBracketedNumber(number);
}
return Optional.of(CanonicalAddressDatabase.getInstance(context).getCanonicalAddressId(number));
}
private static boolean hasBracketedNumber(String recipient) {
int openBracketIndex = recipient.indexOf('<');
return (openBracketIndex != -1) &&
(recipient.indexOf('>', openBracketIndex) != -1);
}
private static String parseBracketedNumber(String recipient) {
int begin = recipient.indexOf('<');
int end = recipient.indexOf('>', begin);
String value = recipient.substring(begin + 1, end);
return value;
}
public static void clearCache() {
provider.clearCache();
}
}
|
gpl-3.0
|
burukuru/grakn
|
grakn-test/test-integration/src/test/java/ai/grakn/generator/RelationPlayers.java
|
1612
|
/*
* Grakn - A Distributed Semantic Database
* Copyright (C) 2016 Grakn Labs Limited
*
* Grakn 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.
*
* Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>.
*
*/
package ai.grakn.generator;
import ai.grakn.concept.Label;
import ai.grakn.graql.admin.RelationPlayer;
import ai.grakn.graql.admin.VarPatternAdmin;
import static ai.grakn.graql.Graql.var;
/**
* @author Felix Chapman
*/
public class RelationPlayers extends AbstractGenerator<RelationPlayer> {
public RelationPlayers() {
super(RelationPlayer.class);
}
@Override
public RelationPlayer generate() {
if (random.nextBoolean()) {
return RelationPlayer.of(gen(VarPatternAdmin.class));
} else {
VarPatternAdmin varPattern;
if (random.nextBoolean()) {
varPattern = var().label(gen(Label.class)).admin();
} else {
varPattern = gen(VarPatternAdmin.class);
}
return RelationPlayer.of(varPattern, gen(VarPatternAdmin.class));
}
}
}
|
gpl-3.0
|
ThoNill/JanusMiniForth
|
JanusMiniForth/src/org/janus/miniforth/Compare.java
|
1226
|
package org.janus.miniforth;
import org.janus.data.DataContext;
public class Compare extends WordImpl {
public enum Comp {
EQ, NEQ, LT, GT, LEQ, GEQ
}
Comp comp;
public Compare(Comp comp) {
super(-1);
this.comp = comp;
}
@Override
public void perform(DataContext context) {
super.perform(context);
MiniForthContext withStack = (MiniForthContext) context;
Comparable a = (Comparable) withStack.pop();
Comparable b = (Comparable) withStack.pop();
boolean result = false;
if (a.getClass().equals(b.getClass())) {
result = compare(a, b);
} else {
throw new IllegalArgumentException("Vergleich nicht möglich");
}
withStack.pushBoolean(result);
}
private boolean compare(Comparable a, Comparable b) {
int c = a.compareTo(b);
if (c == 0) {
if (comp.equals(Comp.NEQ)) {
return false;
} else {
return comp.equals(Comp.EQ) || comp.equals(Comp.LEQ)
|| comp.equals(Comp.GEQ);
}
} else {
if (c > 0) {
return comp.equals(Comp.NEQ) || comp.equals(Comp.LEQ)
|| comp.equals(Comp.LT);
} else {
return comp.equals(Comp.NEQ) || comp.equals(Comp.GEQ)
|| comp.equals(Comp.GT);
}
}
}
}
|
gpl-3.0
|
wdkk/iSuperColliderKit
|
editors/sc-ide/widgets/code_editor/highlighter.hpp
|
3435
|
/*
SuperCollider Qt IDE
Copyright (c) 2012 Jakob Leben & Tim Blechmann
http://www.audiosynth.com
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
*/
#ifndef SCIDE_SC_SYNTAX_HIGHLIGHTER_HPP_INCLUDED
#define SCIDE_SC_SYNTAX_HIGHLIGHTER_HPP_INCLUDED
#include "tokens.hpp"
#include <QSyntaxHighlighter>
#include <QVector>
namespace ScIDE {
namespace Settings { class Manager; }
class Main;
enum SyntaxFormat
{
PlainFormat,
ClassFormat,
KeywordFormat,
BuiltinFormat,
PrimitiveFormat,
SymbolFormat,
StringFormat,
CharFormat,
NumberFormat,
EnvVarFormat,
CommentFormat,
FormatCount
};
struct SyntaxRule
{
SyntaxRule(): type(Token::Unknown) {}
SyntaxRule( Token::Type t, const QString &s ): type(t), expr(s) {}
Token::Type type;
QRegExp expr;
};
class SyntaxHighlighterGlobals : public QObject
{
Q_OBJECT
public:
SyntaxHighlighterGlobals( Main *, Settings::Manager * settings );
inline const QTextCharFormat * formats() const
{
return mFormats;
}
inline const QTextCharFormat & format( SyntaxFormat type ) const
{
return mFormats[type];
}
inline static const SyntaxHighlighterGlobals * instance() { Q_ASSERT(mInstance); return mInstance; }
public Q_SLOTS:
void applySettings( Settings::Manager * );
Q_SIGNALS:
void syntaxFormatsChanged();
private:
friend class SyntaxHighlighter;
void initSyntaxRules();
void initKeywords();
void initBuiltins();
void applySettings( Settings::Manager*, const QString &key, SyntaxFormat );
QTextCharFormat mFormats[FormatCount];
QVector<SyntaxRule> mInCodeRules;
QRegExp mInSymbolRegexp, mInStringRegexp;
static SyntaxHighlighterGlobals *mInstance;
};
class SyntaxHighlighter:
public QSyntaxHighlighter
{
Q_OBJECT
static const int inCode = 0;
static const int inString = 1;
static const int inSymbol = 2;
static const int inComment = 100;
// NOTE: Integers higher than inComment are reserved for multi line comments,
// and indicate the comment nesting level!
public:
SyntaxHighlighter(QTextDocument *parent = 0);
private:
void highlightBlock(const QString &text);
void highlightBlockInCode(const QString& text, int & currentIndex, int & currentState);
void highlightBlockInString(const QString& text, int & currentIndex, int & currentState);
void highlightBlockInSymbol(const QString& text, int & currentIndex, int & currentState);
void highlightBlockInComment(const QString& text, int & currentIndex, int & currentState);
Token::Type findMatchingRule(QString const & text, int & currentIndex, int & lengthOfMatch);
const SyntaxHighlighterGlobals *mGlobals;
};
}
#endif
|
gpl-3.0
|
MysteriumNetwork/node
|
core/service/manager.go
|
5078
|
/*
* Copyright (C) 2018 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package service
import (
"encoding/json"
"errors"
log "github.com/cihub/seelog"
"github.com/mysteriumnetwork/node/communication"
"github.com/mysteriumnetwork/node/identity"
"github.com/mysteriumnetwork/node/market"
"github.com/mysteriumnetwork/node/session"
)
var (
// ErrorLocation error indicates that action (i.e. disconnect)
ErrorLocation = errors.New("failed to detect service location")
// ErrUnsupportedServiceType indicates that manager tried to create an unsupported service type
ErrUnsupportedServiceType = errors.New("unsupported service type")
)
// Service interface represents pluggable Mysterium service
type Service interface {
Serve(providerID identity.Identity) error
Stop() error
ProvideConfig(publicKey json.RawMessage) (session.ServiceConfiguration, session.DestroyCallback, error)
}
// DialogWaiterFactory initiates communication channel which waits for incoming dialogs
type DialogWaiterFactory func(providerID identity.Identity, serviceType string) (communication.DialogWaiter, error)
// DialogHandlerFactory initiates instance which is able to handle incoming dialogs
type DialogHandlerFactory func(market.ServiceProposal, session.ConfigNegotiator) communication.DialogHandler
// DiscoveryFactory initiates instance which is able announce service discoverability
type DiscoveryFactory func() Discovery
// Discovery registers the service to the discovery api periodically
type Discovery interface {
Start(ownIdentity identity.Identity, proposal market.ServiceProposal)
Stop()
Wait()
}
// NewManager creates new instance of pluggable instances manager
func NewManager(
serviceRegistry *Registry,
dialogWaiterFactory DialogWaiterFactory,
dialogHandlerFactory DialogHandlerFactory,
discoveryFactory DiscoveryFactory,
) *Manager {
return &Manager{
serviceRegistry: serviceRegistry,
servicePool: NewPool(),
dialogWaiterFactory: dialogWaiterFactory,
dialogHandlerFactory: dialogHandlerFactory,
discoveryFactory: discoveryFactory,
}
}
// Manager entrypoint which knows how to start pluggable Mysterium instances
type Manager struct {
dialogWaiterFactory DialogWaiterFactory
dialogHandlerFactory DialogHandlerFactory
serviceRegistry *Registry
servicePool *Pool
discoveryFactory DiscoveryFactory
}
// Start starts an instance of the given service type if knows one in service registry.
// It passes the options to the start method of the service.
// If an error occurs in the underlying service, the error is then returned.
func (manager *Manager) Start(providerID identity.Identity, serviceType string, options Options) (id ID, err error) {
service, proposal, err := manager.serviceRegistry.Create(serviceType, options)
if err != nil {
return id, err
}
dialogWaiter, err := manager.dialogWaiterFactory(providerID, serviceType)
if err != nil {
return id, err
}
providerContact, err := dialogWaiter.Start()
if err != nil {
return id, err
}
proposal.SetProviderContact(providerID, providerContact)
dialogHandler := manager.dialogHandlerFactory(proposal, service)
if err = dialogWaiter.ServeDialogs(dialogHandler); err != nil {
return id, err
}
discovery := manager.discoveryFactory()
discovery.Start(providerID, proposal)
instance := Instance{
state: Starting,
options: options,
service: service,
proposal: proposal,
dialogWaiter: dialogWaiter,
discovery: discovery,
}
id, err = manager.servicePool.Add(&instance)
if err != nil {
return id, err
}
go func() {
instance.state = Running
serveErr := service.Serve(providerID)
if serveErr != nil {
log.Error("Service serve failed: ", serveErr)
}
instance.state = NotRunning
stopErr := manager.servicePool.Stop(id)
if stopErr != nil {
log.Error("Service stop failed: ", stopErr)
}
discovery.Wait()
}()
return id, nil
}
// List returns array of running service instances.
func (manager *Manager) List() map[ID]*Instance {
return manager.servicePool.List()
}
// Kill stops all services.
func (manager *Manager) Kill() error {
return manager.servicePool.StopAll()
}
// Stop stops the service.
func (manager *Manager) Stop(id ID) error {
return manager.servicePool.Stop(id)
}
// Service returns a service instance by requested id.
func (manager *Manager) Service(id ID) *Instance {
return manager.servicePool.Instance(id)
}
|
gpl-3.0
|
TarmoA/ProjectAsteroid
|
Documents/ohjelmointistuff/ProjectAsteroid/docs/scalafx/scene/control/IndexRange$.html
|
23469
|
<!DOCTYPE html >
<html>
<head>
<title>IndexRange - ScalaFX API 8.0.0-R4 - scalafx.scene.control.IndexRange</title>
<meta name="description" content="IndexRange - ScalaFX API 8.0.0 - R4 - scalafx.scene.control.IndexRange" />
<meta name="keywords" content="IndexRange ScalaFX API 8.0.0 R4 scalafx.scene.control.IndexRange" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link href="../../../lib/template.css" media="screen" type="text/css" rel="stylesheet" />
<link href="../../../lib/diagrams.css" media="screen" type="text/css" rel="stylesheet" id="diagrams-css" />
<script type="text/javascript" src="../../../lib/jquery.js" id="jquery-js"></script>
<script type="text/javascript" src="../../../lib/jquery-ui.js"></script>
<script type="text/javascript" src="../../../lib/template.js"></script>
<script type="text/javascript" src="../../../lib/tools.tooltip.js"></script>
<script type="text/javascript">
if(top === self) {
var url = '../../../index.html';
var hash = 'scalafx.scene.control.IndexRange$';
var anchor = window.location.hash;
var anchor_opt = '';
if (anchor.length >= 1)
anchor_opt = '@' + anchor.substring(1);
window.location.href = url + '#' + hash + anchor_opt;
}
</script>
</head>
<body class="value">
<div id="definition">
<a href="IndexRange.html" title="Go to companion"><img src="../../../lib/object_to_class_big.png" /></a>
<p id="owner"><a href="../../package.html" class="extype" name="scalafx">scalafx</a>.<a href="../package.html" class="extype" name="scalafx.scene">scene</a>.<a href="package.html" class="extype" name="scalafx.scene.control">control</a></p>
<h1><a href="IndexRange.html" title="Go to companion">IndexRange</a></h1>
</div>
<h4 id="signature" class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">object</span>
</span>
<span class="symbol">
<span class="name">IndexRange</span>
</span>
</h4>
<div id="comment" class="fullcommenttop"><div class="toggleContainer block">
<span class="toggle">Linear Supertypes</span>
<div class="superTypes hiddenContent"><span class="extype" name="scala.AnyRef">AnyRef</span>, <span class="extype" name="scala.Any">Any</span></div>
</div></div>
<div id="mbrsel">
<div id="textfilter"><span class="pre"></span><span class="input"><input id="mbrsel-input" type="text" accesskey="/" /></span><span class="post"></span></div>
<div id="order">
<span class="filtertype">Ordering</span>
<ol>
<li class="alpha in"><span>Alphabetic</span></li>
<li class="inherit out"><span>By inheritance</span></li>
</ol>
</div>
<div id="ancestors">
<span class="filtertype">Inherited<br />
</span>
<ol id="linearization">
<li class="in" name="scalafx.scene.control.IndexRange"><span>IndexRange</span></li><li class="in" name="scala.AnyRef"><span>AnyRef</span></li><li class="in" name="scala.Any"><span>Any</span></li>
</ol>
</div><div id="ancestors">
<span class="filtertype"></span>
<ol>
<li class="hideall out"><span>Hide All</span></li>
<li class="showall in"><span>Show all</span></li>
</ol>
<a href="http://docs.scala-lang.org/overviews/scaladoc/usage.html#members" target="_blank">Learn more about member selection</a>
</div>
<div id="visbl">
<span class="filtertype">Visibility</span>
<ol><li class="public in"><span>Public</span></li><li class="all out"><span>All</span></li></ol>
</div>
</div>
<div id="template">
<div id="allMembers">
<div id="values" class="values members">
<h3>Value Members</h3>
<ol><li name="scala.AnyRef#!=" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="!=(x$1:Any):Boolean"></a>
<a id="!=(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $bang$eq" class="name">!=</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef###" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="##():Int"></a>
<a id="##():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $hash$hash" class="name">##</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#==" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="==(x$1:Any):Boolean"></a>
<a id="==(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span title="gt4s: $eq$eq" class="name">==</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scalafx.scene.control.IndexRange#VALUE_DELIMITER" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="VALUE_DELIMITER:String"></a>
<a id="VALUE_DELIMITER:String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">val</span>
</span>
<span class="symbol">
<span class="name">VALUE_DELIMITER</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<p class="shortcomment cmt">Index range value delimiter.</p>
</li><li name="scala.Any#asInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="asInstanceOf[T0]:T0"></a>
<a id="asInstanceOf[T0]:T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">asInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Any.asInstanceOf.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#clone" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="clone():Object"></a>
<a id="clone():AnyRef"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">clone</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.AnyRef">AnyRef</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.CloneNotSupportedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#eq" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="eq(x$1:AnyRef):Boolean"></a>
<a id="eq(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">eq</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#equals" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="equals(x$1:Any):Boolean"></a>
<a id="equals(Any):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">equals</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Any">Any</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#finalize" visbl="prt" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="finalize():Unit"></a>
<a id="finalize():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">finalize</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Attributes</dt><dd>protected[<a href="../../../java$lang.html" class="extype" name="java.lang">java.lang</a>] </dd><dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="symbol">classOf[java.lang.Throwable]</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#getClass" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="getClass():Class[_]"></a>
<a id="getClass():Class[_]"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">getClass</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.Class">Class</span>[_]</span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.AnyRef#hashCode" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="hashCode():Int"></a>
<a id="hashCode():Int"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">hashCode</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Int">Int</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scala.Any#isInstanceOf" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="isInstanceOf[T0]:Boolean"></a>
<a id="isInstanceOf[T0]:Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">isInstanceOf</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>Any</dd></dl></div>
</li><li name="scala.AnyRef#ne" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="ne(x$1:AnyRef):Boolean"></a>
<a id="ne(AnyRef):Boolean"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">ne</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.AnyRef">AnyRef</span></span>)</span><span class="result">: <span class="extype" name="scala.Boolean">Boolean</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scalafx.scene.control.IndexRange#normalize" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="normalize(v1:Int,v2:Int):scalafx.scene.control.IndexRange"></a>
<a id="normalize(Int,Int):IndexRange"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">normalize</span><span class="params">(<span name="v1">v1: <span class="extype" name="scala.Int">Int</span></span>, <span name="v2">v2: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span>
</span>
</h4>
<p class="shortcomment cmt">Convenience method to create an IndexRange instance that has the smaller value as the start
index, and the larger value as the end index.</p>
</li><li name="scala.AnyRef#notify" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notify():Unit"></a>
<a id="notify():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notify</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#notifyAll" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="notifyAll():Unit"></a>
<a id="notifyAll():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">notifyAll</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scalafx.scene.control.IndexRange#sfxIndexRange" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="sfxIndexRange(r:scalafx.scene.control.IndexRange):javafx.scene.control.IndexRange"></a>
<a id="sfxIndexRange(IndexRange):javafx.scene.control.IndexRange"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">implicit </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">sfxIndexRange</span><span class="params">(<span name="r">r: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span>)</span><span class="result">: <span class="extype" name="javafx.scene.control.IndexRange">javafx.scene.control.IndexRange</span></span>
</span>
</h4>
</li><li name="scala.AnyRef#synchronized" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="synchronized[T0](x$1:=>T0):T0"></a>
<a id="synchronized[T0](⇒T0):T0"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">synchronized</span><span class="tparams">[<span name="T0">T0</span>]</span><span class="params">(<span name="arg0">arg0: ⇒ <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>)</span><span class="result">: <span class="extype" name="java.lang.AnyRef.synchronized.T0">T0</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd></dl></div>
</li><li name="scala.AnyRef#toString" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="toString():String"></a>
<a id="toString():String"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">toString</span><span class="params">()</span><span class="result">: <span class="extype" name="java.lang.String">String</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef → Any</dd></dl></div>
</li><li name="scalafx.scene.control.IndexRange#valueOf" visbl="pub" data-isabs="false" fullComment="no" group="Ungrouped">
<a id="valueOf(value:String):scalafx.scene.control.IndexRange"></a>
<a id="valueOf(String):IndexRange"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier"></span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">valueOf</span><span class="params">(<span name="value">value: <span class="extype" name="scala.Predef.String">String</span></span>)</span><span class="result">: <a href="IndexRange.html" class="extype" name="scalafx.scene.control.IndexRange">IndexRange</a></span>
</span>
</h4>
<p class="shortcomment cmt">Convenience method to parse in a String of the form '2,6', which will create an IndexRange
instance with a start value of 2, and an end value of 6.</p>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait():Unit"></a>
<a id="wait():Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">()</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long,x$2:Int):Unit"></a>
<a id="wait(Long,Int):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>, <span name="arg1">arg1: <span class="extype" name="scala.Int">Int</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li><li name="scala.AnyRef#wait" visbl="pub" data-isabs="false" fullComment="yes" group="Ungrouped">
<a id="wait(x$1:Long):Unit"></a>
<a id="wait(Long):Unit"></a>
<h4 class="signature">
<span class="modifier_kind">
<span class="modifier">final </span>
<span class="kind">def</span>
</span>
<span class="symbol">
<span class="name">wait</span><span class="params">(<span name="arg0">arg0: <span class="extype" name="scala.Long">Long</span></span>)</span><span class="result">: <span class="extype" name="scala.Unit">Unit</span></span>
</span>
</h4>
<div class="fullcomment"><dl class="attributes block"> <dt>Definition Classes</dt><dd>AnyRef</dd><dt>Annotations</dt><dd>
<span class="name">@throws</span><span class="args">(<span>
<span class="defval" name="classOf[java.lang.InterruptedException]">...</span>
</span>)</span>
</dd></dl></div>
</li></ol>
</div>
</div>
<div id="inheritedMembers">
<div class="parent" name="scala.AnyRef">
<h3>Inherited from <span class="extype" name="scala.AnyRef">AnyRef</span></h3>
</div><div class="parent" name="scala.Any">
<h3>Inherited from <span class="extype" name="scala.Any">Any</span></h3>
</div>
</div>
<div id="groupedMembers">
<div class="group" name="Ungrouped">
<h3>Ungrouped</h3>
</div>
</div>
</div>
<div id="tooltip"></div>
<div id="footer"> </div>
</body>
</html>
|
gpl-3.0
|
s20121035/rk3288_android5.1_repo
|
frameworks/minikin/include/minikin/CmapCoverage.h
|
932
|
/*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef MINIKIN_CMAP_COVERAGE_H
#define MINIKIN_CMAP_COVERAGE_H
#include <minikin/SparseBitSet.h>
namespace android {
class CmapCoverage {
public:
static bool getCoverage(SparseBitSet &coverage, const uint8_t* cmap_data, size_t cmap_size);
};
} // namespace android
#endif // MINIKIN_CMAP_COVERAGE_H
|
gpl-3.0
|
Spaner/TrackIt
|
src/main/java/com/trackit/business/domain/Folder.java
|
2498
|
/*
* This file is part of Track It!.
* Copyright (C) 2013 Henrique Malheiro
* Copyright (C) 2015 Pedro Gomes
*
* TrackIt! 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.
*
* Track It! 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 Track It!. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.trackit.business.domain;
import java.util.ArrayList;
import java.util.List;
import com.trackit.business.exception.TrackItException;
import com.trackit.presentation.event.Event;
import com.trackit.presentation.event.EventManager;
import com.trackit.presentation.event.EventPublisher;
public class Folder extends TrackItBaseType implements DocumentItem {
private String name;
private List<GPSDocument> documents;
public Folder(String name) {
super();
this.name = name;
documents = new ArrayList<GPSDocument>();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<GPSDocument> getDocuments() {
return documents;
}
public void add(GPSDocument document) {
documents.add(document);
}
public void remove(GPSDocument document) {
documents.remove(document);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Folder other = (Folder) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return String.format("Folder [name=%s]", name);
}
@Override
public void publishSelectionEvent(EventPublisher publisher) {
EventManager.getInstance().publish(publisher, Event.FOLDER_SELECTED, this);
}
@Override
public void accept(Visitor visitor) throws TrackItException {
visitor.visit(this);
}
}
|
gpl-3.0
|
philippaborrill/AFLF_timecourse_control
|
run_extract_by_pattern.sh
|
937
|
#!/bin/bash
#
# SLURM batch script to launch BLAST
#
#SBATCH -p nbi-medium # partition (queue)
#SBATCH -N 1 # number of nodes
#SBATCH -n 1 # number of cores
#SBATCH --mem 30000 # memory pool for all cores
#SBATCH -t 2-00:00 # time (D-HH:MM)
#SBATCH -o /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/slurm_output/extractNAC.%N.%j.out # STDOUT
#SBATCH -e /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/slurm_output/extractNAC.%N.%j.err # STDERR
#SBATCH -J extractNAC
#SBATCH --mail-type=END,FAIL # notifications for job done & fail
#SBATCH --mail-user=philippa.borrill\@jic.ac.uk # send-to address
source perl-5.22.1
cd /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/TF_analysis/
perl /nbi/Research-Groups/NBI/Cristobal-Uauy/PB_AFLF/control_timecourse/scripts/fasta_extract_by_pattern.pl -r -p "|NAC|" Tritcum_aestivum_seq.fas > Triticum_aestivum_NAC.fa
|
gpl-3.0
|
P3D-Legacy/p3d-legacy
|
P3D/Pokemon/Items/Fossils/FossilizedDino.vb
|
422
|
Namespace Items.Standard
<Item(615, "Fossilized Dino")>
Public Class FossilizedDino
Inherits FossilItem
Public Overrides ReadOnly Property Description As String = "The fossil of an ancient Pokémon that once lived in the sea. What it looked like is a mystery."
Public Sub New()
_textureRectangle = New Rectangle(24, 72, 24, 24)
End Sub
End Class
End Namespace
|
gpl-3.0
|
vb2005xu/eduTrac
|
eduTrac/Classes/Models/ProfileModel.php
|
2264
|
<?php namespace eduTrac\Classes\Models;
if ( ! defined('BASE_PATH') ) exit('No direct script access allowed');
/**
* Profile Model
*
* PHP 5.4+
*
* eduTrac(tm) : Student Information System (http://www.7mediaws.org/)
* @copyright (c) 2013 7 Media Web Solutions, LLC
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 3
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @license http://www.gnu.org/licenses/gpl-3.0.html GNU General Public License, version 3
* @link http://www.7mediaws.org/
* @since 3.0.0
* @package eduTrac
* @author Joshua Parker <josh@7mediaws.org>
*/
use \eduTrac\Classes\Core\DB;
use \eduTrac\Classes\Libraries\Util;
class ProfileModel {
private $_auth;
public function __construct() {
$this->_auth = new \eduTrac\Classes\Libraries\Cookies;
}
public function index() {}
public function runProfile($data) {
$update1 = [
"fname" => $data['fname'],"lname" => $data['lname'],
"mname" => Util::_trim($data['mname']),"email" => Util::_trim($data['email']),
"ssn" => Util::_trim($data['ssn']),"dob" => $data['dob']
];
$bind = [ ":personID" => $this->_auth->getPersonField('personID') ];
$q = DB::inst()->update("person",$update1,"personID = :personID",$bind);
if(!empty($data['password'])) {
$update2 = ["password" => et_hash_password($data['password'])];
DB::inst()->update("person",$update2,"personID = :personID",$bind);
}
redirect( BASE_URL . 'profile/' );
}
public function __destruct() {
DB::inst()->close();
}
}
|
gpl-3.0
|
UnstuckME/UnstuckME
|
UnstuckME/UnstuckMeLoggers/ErrContainerServer.cs
|
1846
|
using System;
namespace UnstuckMeLoggers
{
public enum ERR_TYPES_SERVER
{
// if you add one of these please add it in the switch statement to be handled
SERVER_GUI_LOGIN,
SERVER_GUI_LOGOUT,
SERVER_CONNECTION_ERROR,
SERVER_GUI_INTERACTION_ERROR,
SERVER_START,
SERVER_STOP,
DATABASE_RETURN_ERROR,
DATABASE_CONNECTION_ERROR
}
internal class ErrContainerServer
{
string i_ErrorMsg; // the error message string contained by the thrown exception
string i_ErrTypeStartMark; // the xml like tag that defines the start of the error
string i_ErrTypeEndMark; // the xml like tag that defines the end of the error
string i_ErrorTime; // the string representaition of the time the errors occurance
string i_AdditionalInfo; // a string that holds any additional info you would like logged such as what caused the error
internal ErrContainerServer(string ErrorMsg, string ErrTypeStartMark, string ErrTypeEndMark, string ErrorTime, string AdditionalInfo = null)
{
i_ErrorMsg = ErrorMsg;
i_ErrTypeStartMark = ErrTypeStartMark;
i_ErrTypeEndMark = ErrTypeEndMark;
i_ErrorTime = ErrorTime;
i_AdditionalInfo = AdditionalInfo;
}
public override string ToString()
{
string temp = i_ErrTypeStartMark + Environment.NewLine + "\t" + "<ErrMsg=" + i_ErrorMsg + "/>";
if (i_AdditionalInfo != null)
temp = temp + Environment.NewLine + "<AdditionalInfo=" + i_AdditionalInfo + "/>";
temp = temp + Environment.NewLine + "\t" + "<ErrTime=" + i_ErrorTime + "/>" + Environment.NewLine + i_ErrTypeEndMark;
return temp;
}
}
}
|
gpl-3.0
|
IODisrupt/OmegaBot
|
cogs/runescapecompare.py
|
2978
|
import discord
import asyncio
import datetime
import time
import aiohttp
import threading
import glob
import re
import json
import os
import urllib.request
from discord.ext import commands
from random import randint
from random import choice as randchoice
from random import choice as rndchoice
from random import shuffle
from .utils.dataIO import fileIO
from .utils import checks
from bs4 import BeautifulSoup
class Runescapecompare:
"""Runescape-relate commands"""
def __init__(self, bot):
self.bot = bot
"""
imLink = http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=
nmLink = http://services.runescape.com/m=hiscore/index_lite.ws?player=
"""
@commands.group(name="compare", pass_context=True)
async def _compare(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.say("Please, choose a skill to compare!")
#####Overall#####
@_compare.command(name="overall", pass_context=True)
async def compare_overall(self, ctx, name1 : str, name2 : str):
address1 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name1
address2 = "http://services.runescape.com/m=hiscore_ironman/index_lite.ws?player=" + name2
try:
website1 = urllib.request.urlopen(address1)
website2 = urllib.request.urlopen(address2)
website_html1 = website1.read().decode(website1.headers.get_content_charset())
website_html2 = website2.read().decode(website2.headers.get_content_charset())
stats1 = website_html1.split("\n")
stats2 = website_html2.split("\n")
stat1 = stats1[0].split(",")
stat2= stats2[0].split(",")
if stat1[2] > stat2[2]:
comparerank = int(stat2[0]) - int(stat1[0])
comparelvl = int(stat1[1]) - int(stat2[1])
comparexp = int(stat1[2]) - int(stat2[2])
await self.bot.say("```" + name1 + "'s ranking is " + str(comparerank) + " ranks higher than " + name2 + "'s rank.\n" + name1 + "'s level is " + str(comparelvl) + " levels higher than " + name2 + "'s.\n" + name1 + "'s total experience is " + str(comparexp) + " higher than " + name2 + "'s.```")
if stat2[2] > stat1[2]:
comparerank = stat2[0] - stat1[0]
comparelvl = stat2[1] - stat1[1]
comparexp = stat2[2] - stat1[2]
await self.bot.say("```" + name2 + "'s ranking is " + str(comparerank) + " ranks higher than " + name1 + "'s rank.\n" + name2 + "'s level is " + str(comparelvl) + " levels higher than " + name1 + "'s.\n" + name2 + "'s total experience is " + str(comparexp) + " higher than " + name1 + "'s.```")
except:
await self.bot.say("Sorry... Something went wrong there. Did you type the name correctly?")
def setup(bot):
n = Runescapecompare(bot)
bot.add_cog(n)
|
gpl-3.0
|