repo_name
stringlengths 4
116
| path
stringlengths 4
379
| size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|
dsebastien/DefinitelyTyped | types/react-native-share-menu/react-native-share-menu-tests.ts | 124 | import ShareMenu from 'react-native-share-menu';
ShareMenu.getSharedText((text: string) => {
const message = text;
});
| mit |
joomla-projects/cms-naked | tests/unit/suites/libraries/joomla/language/JLanguageStemmerTest.php | 989 | <?php
/**
* @package Joomla.UnitTest
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
/**
* Test class for JLanguageStemmer.
*
* @package Joomla.UnitTest
* @subpackage Language
* @since 11.1
*/
class JLanguageStemmerTest extends PHPUnit_Framework_TestCase
{
/**
* Test...
*
* @return void
*/
public function testGetInstance()
{
$instance = JLanguageStemmer::getInstance('porteren');
$this->assertInstanceof(
'JLanguageStemmer',
$instance
);
$this->assertInstanceof(
'JLanguageStemmerPorteren',
$instance
);
$instance2 = JLanguageStemmer::getInstance('porteren');
$this->assertSame(
$instance,
$instance2
);
}
/**
* Test...
*
* @expectedException RuntimeException
*
* @return void
*/
public function testGetInstanceException()
{
JLanguageStemmer::getInstance('unexisting');
}
}
| gpl-2.0 |
summerpulse/openjdk7 | jdk/src/share/classes/sun/nio/cs/ext/EUC_JP.java | 15375 | /*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
*/
package sun.nio.cs.ext;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import sun.nio.cs.HistoricallyNamedCharset;
import sun.nio.cs.Surrogate;
public class EUC_JP
extends Charset
implements HistoricallyNamedCharset
{
public EUC_JP() {
super("EUC-JP", ExtendedCharsets.aliasesFor("EUC-JP"));
}
public String historicalName() {
return "EUC_JP";
}
public boolean contains(Charset cs) {
return ((cs.name().equals("US-ASCII"))
|| (cs instanceof JIS_X_0201)
|| (cs instanceof JIS_X_0208)
|| (cs instanceof JIS_X_0212)
|| (cs instanceof EUC_JP));
}
public CharsetDecoder newDecoder() {
return new Decoder(this);
}
public CharsetEncoder newEncoder() {
// Need to force the replacement byte to 0x3f
// because JIS_X_0208_Encoder defines its own
// alternative 2 byte substitution to permit it
// to exist as a self-standing Encoder
byte[] replacementBytes = { (byte)0x3f };
return new Encoder(this).replaceWith(replacementBytes);
}
static class Decoder extends JIS_X_0208_Decoder
implements DelegatableDecoder {
JIS_X_0201.Decoder decoderJ0201;
JIS_X_0212_Decoder decoderJ0212;
private static final short[] j0208Index1 =
JIS_X_0208_Decoder.getIndex1();
private static final String[] j0208Index2 =
JIS_X_0208_Decoder.getIndex2();
protected Decoder(Charset cs) {
super(cs);
decoderJ0201 = new JIS_X_0201.Decoder(cs);
decoderJ0212 = new JIS_X_0212_Decoder(cs);
start = 0xa1;
end = 0xfe;
}
protected char decode0212(int byte1, int byte2) {
return decoderJ0212.decodeDouble(byte1, byte2);
}
protected char decodeDouble(int byte1, int byte2) {
if (byte1 == 0x8e) {
return decoderJ0201.decode(byte2 - 256);
}
// Fix for bug 4121358 - similar fix for bug 4117820 put
// into ByteToCharDoubleByte.getUnicode()
if (((byte1 < 0) || (byte1 > getIndex1().length))
|| ((byte2 < start) || (byte2 > end)))
return REPLACE_CHAR;
int n = (j0208Index1[byte1 - 0x80] & 0xf) * (end - start + 1)
+ (byte2 - start);
return j0208Index2[j0208Index1[byte1 - 0x80] >> 4].charAt(n);
}
private CoderResult decodeArrayLoop(ByteBuffer src,
CharBuffer dst)
{
byte[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
assert (sp <= sl);
sp = (sp <= sl ? sp : sl);
char[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
assert (dp <= dl);
dp = (dp <= dl ? dp : dl);
int b1 = 0, b2 = 0;
int inputSize = 0;
char outputChar = REPLACE_CHAR; // U+FFFD;
try {
while (sp < sl) {
b1 = sa[sp] & 0xff;
inputSize = 1;
if ((b1 & 0x80) == 0) {
outputChar = (char)b1;
}
else { // Multibyte char
if ((b1 & 0xff) == 0x8f) { // JIS0212
if (sp + 3 > sl)
return CoderResult.UNDERFLOW;
b1 = sa[sp + 1] & 0xff;
b2 = sa[sp + 2] & 0xff;
inputSize += 2;
outputChar = decode0212(b1-0x80, b2-0x80);
} else {
// JIS0208
if (sp + 2 > sl)
return CoderResult.UNDERFLOW;
b2 = sa[sp + 1] & 0xff;
inputSize++;
outputChar = decodeDouble(b1, b2);
}
}
if (outputChar == REPLACE_CHAR) { // can't be decoded
return CoderResult.unmappableForLength(inputSize);
}
if (dp + 1 > dl)
return CoderResult.OVERFLOW;
da[dp++] = outputChar;
sp += inputSize;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
private CoderResult decodeBufferLoop(ByteBuffer src,
CharBuffer dst)
{
int mark = src.position();
int b1 = 0, b2 = 0;
int inputSize = 0;
char outputChar = REPLACE_CHAR; // U+FFFD;
try {
while (src.hasRemaining()) {
b1 = src.get() & 0xff;
inputSize = 1;
if ((b1 & 0x80) == 0) {
outputChar = (char)b1;
} else { // Multibyte char
if ((b1 & 0xff) == 0x8f) { // JIS0212
if (src.remaining() < 2)
return CoderResult.UNDERFLOW;
b1 = src.get() & 0xff;
b2 = src.get() & 0xff;
inputSize += 2;
outputChar = decode0212(b1-0x80, b2-0x80);
} else {
// JIS0208
if (src.remaining() < 1)
return CoderResult.UNDERFLOW;
b2 = src.get() & 0xff;
inputSize++;
outputChar = decodeDouble(b1, b2);
}
}
if (outputChar == REPLACE_CHAR) {
return CoderResult.unmappableForLength(inputSize);
}
if (dst.remaining() < 1)
return CoderResult.OVERFLOW;
dst.put(outputChar);
mark += inputSize;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(mark);
}
}
// Make some protected methods public for use by JISAutoDetect
public CoderResult decodeLoop(ByteBuffer src, CharBuffer dst) {
if (src.hasArray() && dst.hasArray())
return decodeArrayLoop(src, dst);
else
return decodeBufferLoop(src, dst);
}
public void implReset() {
super.implReset();
}
public CoderResult implFlush(CharBuffer out) {
return super.implFlush(out);
}
}
static class Encoder extends JIS_X_0208_Encoder {
JIS_X_0201.Encoder encoderJ0201;
JIS_X_0212_Encoder encoderJ0212;
private static final short[] j0208Index1 =
JIS_X_0208_Encoder.getIndex1();
private static final String[] j0208Index2 =
JIS_X_0208_Encoder.getIndex2();
private final Surrogate.Parser sgp = new Surrogate.Parser();
protected Encoder(Charset cs) {
super(cs, 3.0f, 3.0f);
encoderJ0201 = new JIS_X_0201.Encoder(cs);
encoderJ0212 = new JIS_X_0212_Encoder(cs);
}
public boolean canEncode(char c) {
byte[] encodedBytes = new byte[3];
if (encodeSingle(c, encodedBytes) == 0) { //doublebyte
if (encodeDouble(c) == 0)
return false;
}
return true;
}
protected int encodeSingle(char inputChar, byte[] outputByte) {
byte b;
if (inputChar == 0) {
outputByte[0] = (byte)0;
return 1;
}
if ((b = encoderJ0201.encode(inputChar)) == 0)
return 0;
if (b > 0 && b < 128) {
outputByte[0] = b;
return 1;
}
outputByte[0] = (byte)0x8e;
outputByte[1] = b;
return 2;
}
protected int encodeDouble(char ch) {
int offset = j0208Index1[((ch & 0xff00) >> 8 )] << 8;
int r = j0208Index2[offset >> 12].charAt((offset & 0xfff) +
(ch & 0xff));
if (r != 0)
return r + 0x8080;
r = encoderJ0212.encodeDouble(ch);
if (r == 0)
return r;
return r + 0x8F8080;
}
private CoderResult encodeArrayLoop(CharBuffer src,
ByteBuffer dst)
{
char[] sa = src.array();
int sp = src.arrayOffset() + src.position();
int sl = src.arrayOffset() + src.limit();
assert (sp <= sl);
sp = (sp <= sl ? sp : sl);
byte[] da = dst.array();
int dp = dst.arrayOffset() + dst.position();
int dl = dst.arrayOffset() + dst.limit();
assert (dp <= dl);
dp = (dp <= dl ? dp : dl);
int outputSize = 0;
byte[] outputByte;
int inputSize = 0; // Size of input
byte[] tmpBuf = new byte[3];
try {
while (sp < sl) {
outputByte = tmpBuf;
char c = sa[sp];
if (Character.isSurrogate(c)) {
if (sgp.parse(c, sa, sp, sl) < 0)
return sgp.error();
return sgp.unmappableResult();
}
outputSize = encodeSingle(c, outputByte);
if (outputSize == 0) { // DoubleByte
int ncode = encodeDouble(c);
if (ncode != 0 ) {
if ((ncode & 0xFF0000) == 0) {
outputByte[0] = (byte) ((ncode & 0xff00) >> 8);
outputByte[1] = (byte) (ncode & 0xff);
outputSize = 2;
} else {
outputByte[0] = (byte) 0x8f;
outputByte[1] = (byte) ((ncode & 0xff00) >> 8);
outputByte[2] = (byte) (ncode & 0xff);
outputSize = 3;
}
} else {
return CoderResult.unmappableForLength(1);
}
}
if (dl - dp < outputSize)
return CoderResult.OVERFLOW;
// Put the byte in the output buffer
for (int i = 0; i < outputSize; i++) {
da[dp++] = outputByte[i];
}
sp++;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(sp - src.arrayOffset());
dst.position(dp - dst.arrayOffset());
}
}
private CoderResult encodeBufferLoop(CharBuffer src,
ByteBuffer dst)
{
int outputSize = 0;
byte[] outputByte;
int inputSize = 0; // Size of input
byte[] tmpBuf = new byte[3];
int mark = src.position();
try {
while (src.hasRemaining()) {
outputByte = tmpBuf;
char c = src.get();
if (Character.isSurrogate(c)) {
if (sgp.parse(c, src) < 0)
return sgp.error();
return sgp.unmappableResult();
}
outputSize = encodeSingle(c, outputByte);
if (outputSize == 0) { // DoubleByte
int ncode = encodeDouble(c);
if (ncode != 0 ) {
if ((ncode & 0xFF0000) == 0) {
outputByte[0] = (byte) ((ncode & 0xff00) >> 8);
outputByte[1] = (byte) (ncode & 0xff);
outputSize = 2;
} else {
outputByte[0] = (byte) 0x8f;
outputByte[1] = (byte) ((ncode & 0xff00) >> 8);
outputByte[2] = (byte) (ncode & 0xff);
outputSize = 3;
}
} else {
return CoderResult.unmappableForLength(1);
}
}
if (dst.remaining() < outputSize)
return CoderResult.OVERFLOW;
// Put the byte in the output buffer
for (int i = 0; i < outputSize; i++) {
dst.put(outputByte[i]);
}
mark++;
}
return CoderResult.UNDERFLOW;
} finally {
src.position(mark);
}
}
protected CoderResult encodeLoop(CharBuffer src,
ByteBuffer dst)
{
if (src.hasArray() && dst.hasArray())
return encodeArrayLoop(src, dst);
else
return encodeBufferLoop(src, dst);
}
}
}
| gpl-2.0 |
nerzhul/ansible | lib/ansible/plugins/callback/junit.py | 8269 | # (c) 2016 Matt Clay <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import time
from ansible.module_utils._text import to_bytes
from ansible.plugins.callback import CallbackBase
try:
from junit_xml import TestSuite, TestCase
HAS_JUNIT_XML = True
except ImportError:
HAS_JUNIT_XML = False
try:
from collections import OrderedDict
HAS_ORDERED_DICT = True
except ImportError:
try:
from ordereddict import OrderedDict
HAS_ORDERED_DICT = True
except ImportError:
HAS_ORDERED_DICT = False
class CallbackModule(CallbackBase):
"""
This callback writes playbook output to a JUnit formatted XML file.
Tasks show up in the report as follows:
'ok': pass
'failed' with 'EXPECTED FAILURE' in the task name: pass
'failed' due to an exception: error
'failed' for other reasons: failure
'skipped': skipped
This plugin makes use of the following environment variables:
JUNIT_OUTPUT_DIR (optional): Directory to write XML files to.
Default: ~/.ansible.log
Requires:
junit_xml
"""
CALLBACK_VERSION = 2.0
CALLBACK_TYPE = 'aggregate'
CALLBACK_NAME = 'junit'
CALLBACK_NEEDS_WHITELIST = True
def __init__(self):
super(CallbackModule, self).__init__()
self._output_dir = os.getenv('JUNIT_OUTPUT_DIR', os.path.expanduser('~/.ansible.log'))
self._playbook_path = None
self._playbook_name = None
self._play_name = None
self._task_data = None
self.disabled = False
if not HAS_JUNIT_XML:
self.disabled = True
self._display.warning('The `junit_xml` python module is not installed. '
'Disabling the `junit` callback plugin.')
if HAS_ORDERED_DICT:
self._task_data = OrderedDict()
else:
self.disabled = True
self._display.warning('The `ordereddict` python module is not installed. '
'Disabling the `junit` callback plugin.')
if not os.path.exists(self._output_dir):
os.mkdir(self._output_dir)
def _start_task(self, task):
""" record the start of a task for one or more hosts """
uuid = task._uuid
if uuid in self._task_data:
return
play = self._play_name
name = task.get_name().strip()
path = task.get_path()
if not task.no_log:
args = ', '.join(('%s=%s' % a for a in task.args.items()))
if args:
name += ' ' + args
self._task_data[uuid] = TaskData(uuid, name, path, play)
def _finish_task(self, status, result):
""" record the results of a task for a single host """
task_uuid = result._task._uuid
if hasattr(result, '_host'):
host_uuid = result._host._uuid
host_name = result._host.name
else:
host_uuid = 'include'
host_name = 'include'
task_data = self._task_data[task_uuid]
if status == 'failed' and 'EXPECTED FAILURE' in task_data.name:
status = 'ok'
task_data.add_host(HostData(host_uuid, host_name, status, result))
def _build_test_case(self, task_data, host_data):
""" build a TestCase from the given TaskData and HostData """
name = '[%s] %s: %s' % (host_data.name, task_data.play, task_data.name)
duration = host_data.finish - task_data.start
if host_data.status == 'included':
return TestCase(name, task_data.path, duration, host_data.result)
res = host_data.result._result
rc = res.get('rc', 0)
dump = self._dump_results(res, indent=0)
if host_data.status == 'ok':
return TestCase(name, task_data.path, duration, dump)
test_case = TestCase(name, task_data.path, duration)
if host_data.status == 'failed':
if 'exception' in res:
message = res['exception'].strip().split('\n')[-1]
output = res['exception']
test_case.add_error_info(message, output)
elif 'msg' in res:
message = res['msg']
test_case.add_failure_info(message, dump)
else:
test_case.add_failure_info('rc=%s' % rc, dump)
elif host_data.status == 'skipped':
if 'skip_reason' in res:
message = res['skip_reason']
else:
message = 'skipped'
test_case.add_skipped_info(message)
return test_case
def _generate_report(self):
""" generate a TestSuite report from the collected TaskData and HostData """
test_cases = []
for task_uuid, task_data in self._task_data.items():
for host_uuid, host_data in task_data.host_data.items():
test_cases.append(self._build_test_case(task_data, host_data))
test_suite = TestSuite(self._playbook_name, test_cases)
report = TestSuite.to_xml_string([test_suite])
output_file = os.path.join(self._output_dir, '%s-%s.xml' % (self._playbook_name, time.time()))
with open(output_file, 'wb') as xml:
xml.write(to_bytes(report, errors='surrogate_or_strict'))
def v2_playbook_on_start(self, playbook):
self._playbook_path = playbook._file_name
self._playbook_name = os.path.splitext(os.path.basename(self._playbook_path))[0]
def v2_playbook_on_play_start(self, play):
self._play_name = play.get_name()
def v2_runner_on_no_hosts(self, task):
self._start_task(task)
def v2_playbook_on_task_start(self, task, is_conditional):
self._start_task(task)
def v2_playbook_on_cleanup_task_start(self, task):
self._start_task(task)
def v2_playbook_on_handler_task_start(self, task):
self._start_task(task)
def v2_runner_on_failed(self, result, ignore_errors=False):
if ignore_errors:
self._finish_task('ok', result)
else:
self._finish_task('failed', result)
def v2_runner_on_ok(self, result):
self._finish_task('ok', result)
def v2_runner_on_skipped(self, result):
self._finish_task('skipped', result)
def v2_playbook_on_include(self, included_file):
self._finish_task('included', included_file)
def v2_playbook_on_stats(self, stats):
self._generate_report()
class TaskData:
"""
Data about an individual task.
"""
def __init__(self, uuid, name, path, play):
self.uuid = uuid
self.name = name
self.path = path
self.play = play
self.start = None
self.host_data = OrderedDict()
self.start = time.time()
def add_host(self, host):
if host.uuid in self.host_data:
if host.status == 'included':
# concatenate task include output from multiple items
host.result = '%s\n%s' % (self.host_data[host.uuid].result, host.result)
else:
raise Exception('%s: %s: %s: duplicate host callback: %s' % (self.path, self.play, self.name, host.name))
self.host_data[host.uuid] = host
class HostData:
"""
Data about an individual host.
"""
def __init__(self, uuid, name, status, result):
self.uuid = uuid
self.name = name
self.status = status
self.result = result
self.finish = time.time()
| gpl-3.0 |
saurabh6790/med_app_rels | patches/november_2012/gle_floating_point_issue.py | 731 | # Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
def execute():
import webnotes
webnotes.conn.sql("""update `tabGL Entry`
set debit = round(debit, 2), credit = round(credit, 2)""")
gle = webnotes.conn.sql("""select voucher_type, voucher_no,
sum(ifnull(debit,0)) - sum(ifnull(credit, 0)) as diff
from `tabGL Entry`
group by voucher_type, voucher_no
having sum(ifnull(debit, 0)) != sum(ifnull(credit, 0))""", as_dict=1)
for d in gle:
webnotes.conn.sql("""update `tabGL Entry` set debit = debit - %s
where voucher_type = %s and voucher_no = %s and debit > 0 limit 1""",
(d['diff'], d['voucher_type'], d['voucher_no'])) | agpl-3.0 |
masterhou/OctoPrint | src/octoprint/static/js/app/viewmodels/loginstate.js | 4414 | $(function() {
function LoginStateViewModel() {
var self = this;
self.loginUser = ko.observable();
self.loginPass = ko.observable();
self.loginRemember = ko.observable(false);
self.loggedIn = ko.observable(false);
self.username = ko.observable(undefined);
self.isAdmin = ko.observable(false);
self.isUser = ko.observable(false);
self.allViewModels = undefined;
self.currentUser = ko.observable(undefined);
self.userMenuText = ko.computed(function() {
if (self.loggedIn()) {
return self.username();
} else {
return gettext("Login");
}
});
self.reloadUser = function() {
if (self.currentUser() == undefined) {
return;
}
$.ajax({
url: API_BASEURL + "users/" + self.currentUser().name,
type: "GET",
success: self.fromResponse
})
};
self.requestData = function() {
$.ajax({
url: API_BASEURL + "login",
type: "POST",
data: {"passive": true},
success: self.fromResponse
})
};
self.fromResponse = function(response) {
if (response && response.name) {
self.loggedIn(true);
self.username(response.name);
self.isUser(response.user);
self.isAdmin(response.admin);
self.currentUser(response);
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onUserLoggedIn")) {
viewModel.onUserLoggedIn(response);
}
});
} else {
self.loggedIn(false);
self.username(undefined);
self.isUser(false);
self.isAdmin(false);
self.currentUser(undefined);
_.each(self.allViewModels, function(viewModel) {
if (viewModel.hasOwnProperty("onUserLoggedOut")) {
viewModel.onUserLoggedOut();
}
});
}
};
self.login = function() {
var username = self.loginUser();
var password = self.loginPass();
var remember = self.loginRemember();
self.loginUser("");
self.loginPass("");
self.loginRemember(false);
$.ajax({
url: API_BASEURL + "login",
type: "POST",
data: {"user": username, "pass": password, "remember": remember},
success: function(response) {
new PNotify({title: gettext("Login successful"), text: _.sprintf(gettext('You are now logged in as "%(username)s"'), {username: response.name}), type: "success"});
self.fromResponse(response);
},
error: function(jqXHR, textStatus, errorThrown) {
new PNotify({title: gettext("Login failed"), text: gettext("User unknown or wrong password"), type: "error"});
}
})
};
self.logout = function() {
$.ajax({
url: API_BASEURL + "logout",
type: "POST",
success: function(response) {
new PNotify({title: gettext("Logout successful"), text: gettext("You are now logged out"), type: "success"});
self.fromResponse(response);
}
})
};
self.onLoginUserKeyup = function(data, event) {
if (event.keyCode == 13) {
$("#login_pass").focus();
}
};
self.onLoginPassKeyup = function(data, event) {
if (event.keyCode == 13) {
self.login();
}
};
self.onAllBound = function(allViewModels) {
self.allViewModels = allViewModels;
};
self.onDataUpdaterReconnect = function() {
self.requestData();
};
self.onStartupComplete = function() {
self.requestData();
};
}
OCTOPRINT_VIEWMODELS.push([
LoginStateViewModel,
[],
[]
]);
}); | agpl-3.0 |
wxstars/phabricator | src/applications/feed/controller/PhabricatorFeedController.php | 1091 | <?php
abstract class PhabricatorFeedController extends PhabricatorController {
public function buildStandardPageResponse($view, array $data) {
$page = $this->buildStandardPageView();
$page->setApplicationName(pht('Feed'));
$page->setBaseURI('/feed/');
$page->setTitle(idx($data, 'title'));
$page->setGlyph("\xE2\x88\x9E");
$page->appendChild($view);
$response = new AphrontWebpageResponse();
if (!empty($data['public'])) {
$page->setFrameable(true);
$page->setShowChrome(false);
$response->setFrameable(true);
}
return $response->setContent($page->render());
}
protected function buildSideNavView() {
$user = $this->getRequest()->getUser();
$nav = new AphrontSideNavFilterView();
$nav->setBaseURI(new PhutilURI($this->getApplicationURI()));
id(new PhabricatorFeedSearchEngine())
->setViewer($user)
->addNavigationItems($nav->getMenu());
$nav->selectFilter(null);
return $nav;
}
public function buildApplicationMenu() {
return $this->buildSideNavView()->getMenu();
}
}
| apache-2.0 |
zdary/intellij-community | java/java-tests/testData/inspection/redundantArrayForVarargs/RawArray.java | 245 | public class RawArray {
{
try {
String.class.getConstructor(<warning descr="Redundant array creation for calling varargs method">new Class[]{String.class}</warning>);
} catch (Exception e) {
e.printStackTrace();
}
}
} | apache-2.0 |
xyb/homebrew-cask | Casks/jewelrybox.rb | 338 | cask "jewelrybox" do
version "1.5"
sha256 "96c0bae3cc0ce312ce3df290a4d1eddff2da781dfaafe4707b298dc17eb53993"
url "https://github.com/remear/jewelrybox/releases/download/#{version}/JewelryBox_v#{version}.tar.bz2"
name "JewelryBox"
desc "RVM manager"
homepage "https://github.com/remear/jewelrybox"
app "JewelryBox.app"
end
| bsd-2-clause |
razvansividra/pnlzf2-1 | vendor/ZF2/library/Zend/Mail/Storage/Part/PartInterface.php | 3739 | <?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Zend\Mail\Storage\Part;
use RecursiveIterator;
interface PartInterface extends RecursiveIterator
{
/**
* Check if part is a multipart message
*
* @return bool if part is multipart
*/
public function isMultipart();
/**
* Body of part
*
* If part is multipart the raw content of this part with all sub parts is returned
*
* @return string body
* @throws Exception\ExceptionInterface
*/
public function getContent();
/**
* Return size of part
*
* @return int size
*/
public function getSize();
/**
* Get part of multipart message
*
* @param int $num number of part starting with 1 for first part
* @return PartInterface wanted part
* @throws Exception\ExceptionInterface
*/
public function getPart($num);
/**
* Count parts of a multipart part
*
* @return int number of sub-parts
*/
public function countParts();
/**
* Get all headers
*
* The returned headers are as saved internally. All names are lowercased. The value is a string or an array
* if a header with the same name occurs more than once.
*
* @return \Zend\Mail\Headers
*/
public function getHeaders();
/**
* Get a header in specified format
*
* Internally headers that occur more than once are saved as array, all other as string. If $format
* is set to string implode is used to concat the values (with Zend\Mime\Mime::LINEEND as delim).
*
* @param string $name name of header, matches case-insensitive, but camel-case is replaced with dashes
* @param string $format change type of return value to 'string' or 'array'
* @return string|array|\Zend\Mail\Header\HeaderInterface|\ArrayIterator value of header in wanted or internal format
* @throws Exception\ExceptionInterface
*/
public function getHeader($name, $format = null);
/**
* Get a specific field from a header like content type or all fields as array
*
* If the header occurs more than once, only the value from the first header
* is returned.
*
* Throws an exception if the requested header does not exist. If
* the specific header field does not exist, returns null.
*
* @param string $name name of header, like in getHeader()
* @param string $wantedPart the wanted part, default is first, if null an array with all parts is returned
* @param string $firstName key name for the first part
* @return string|array wanted part or all parts as array($firstName => firstPart, partname => value)
* @throws Exception\ExceptionInterface
*/
public function getHeaderField($name, $wantedPart = '0', $firstName = '0');
/**
* Getter for mail headers - name is matched in lowercase
*
* This getter is short for PartInterface::getHeader($name, 'string')
*
* @see PartInterface::getHeader()
*
* @param string $name header name
* @return string value of header
* @throws Exception\ExceptionInterface
*/
public function __get($name);
/**
* magic method to get content of part
*
* @return string content
*/
public function __toString();
}
| bsd-3-clause |
oggy/rubyspec | library/delegate/delegator/method_spec.rb | 1964 | require File.expand_path('../../../../spec_helper', __FILE__)
require File.expand_path('../../fixtures/classes', __FILE__)
describe "Delegator#method" do
before :all do
@simple = DelegateSpecs::Simple.new
@delegate = DelegateSpecs::Delegator.new(@simple)
end
it "returns a method object for public methods of the delegate object" do
m = @delegate.method(:pub)
m.should be_an_instance_of(Method)
m.call.should == :foo
end
it "returns a method object for protected methods of the delegate object" do
m = @delegate.method(:prot)
m.should be_an_instance_of(Method)
m.call.should == :protected
end
it "raises a NameError for a private methods of the delegate object" do
lambda {
@delegate.method(:priv)
}.should raise_error(NameError)
end
it "returns a method object for public methods of the Delegator class" do
m = @delegate.method(:extra)
m.should be_an_instance_of(Method)
m.call.should == :cheese
end
it "returns a method object for protected methods of the Delegator class" do
m = @delegate.method(:extra_protected)
m.should be_an_instance_of(Method)
m.call.should == :baz
end
it "returns a method object for private methods of the Delegator class" do
m = @delegate.method(:extra_private)
m.should be_an_instance_of(Method)
m.call.should == :bar
end
it "raises a NameError for an invalid method name" do
lambda {
@delegate.method(:invalid_and_silly_method_name)
}.should raise_error(NameError)
end
ruby_version_is "1.9" do
it "returns a method that respond_to_missing?" do
m = @delegate.method(:pub_too)
m.should be_an_instance_of(Method)
m.call.should == :pub_too
end
end
it "raises a NameError if method is no longer valid because object has changed" do
m = @delegate.method(:pub)
@delegate.__setobj__([1,2,3])
lambda {
m.call
}.should raise_error(NameError)
end
end
| mit |
Mileto/NiuShard | Scripts/Services/XmlSpawner/XMLSpawner Extras/XmlPoints/ChallengeGames/TeamLMSGauntlet.cs | 17826 | using System;
using Server;
using Server.Gumps;
using Server.Network;
using Server.Mobiles;
using System.Collections;
using Server.Targeting;
using Server.Engines.XmlSpawner2;
/*
** TeamLMSGauntlet
** ArteGordon
** updated 12/05/04
**
** used to set up a team lms pvp challenge game through the XmlPoints system.
*/
namespace Server.Items
{
public class TeamLMSGauntlet : BaseChallengeGame
{
public class ChallengeEntry : BaseChallengeEntry
{
public ChallengeEntry(Mobile m) : base (m)
{
}
public ChallengeEntry() : base ()
{
}
}
private static TimeSpan MaximumOutOfBoundsDuration = TimeSpan.FromSeconds(15); // maximum time allowed out of bounds before disqualification
private static TimeSpan MaximumOfflineDuration = TimeSpan.FromSeconds(60); // maximum time allowed offline before disqualification
private static TimeSpan MaximumHiddenDuration = TimeSpan.FromSeconds(10); // maximum time allowed hidden before disqualification
private static TimeSpan RespawnTime = TimeSpan.FromSeconds(6); // delay until autores if autores is enabled
public static bool OnlyInChallengeGameRegion = false; // if this is true, then the game can only be set up in a challenge game region
private Mobile m_Challenger;
private ArrayList m_Organizers = new ArrayList();
private ArrayList m_Participants = new ArrayList();
private bool m_GameLocked;
private bool m_GameInProgress;
private int m_TotalPurse;
private int m_EntryFee;
private int m_ArenaSize = 0; // maximum distance from the challenge gauntlet allowed before disqualification. Zero is unlimited range
private int m_Winner = 0;
// how long before the gauntlet decays if a gauntlet is dropped but never started
public override TimeSpan DecayTime { get{ return TimeSpan.FromMinutes( 15 ); } } // this will apply to the setup
public override ArrayList Organizers { get { return m_Organizers; } }
public override bool AllowPoints { get{ return false; } } // determines whether kills during the game will award points. If this is false, UseKillDelay is ignored
public override bool UseKillDelay { get{ return true; } } // determines whether the normal delay between kills of the same player for points is enforced
public bool AutoRes { get { return true; } } // determines whether players auto res after being killed
public override bool GameLocked { get{ return m_GameLocked; } set { m_GameLocked = value; }}
public override bool GameInProgress { get{ return m_GameInProgress; } set { m_GameInProgress = value; }}
[CommandProperty( AccessLevel.GameMaster )]
public override Mobile Challenger { get{ return m_Challenger; } set { m_Challenger = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public override bool GameCompleted { get{ return !m_GameInProgress && m_GameLocked; } }
[CommandProperty( AccessLevel.GameMaster )]
public override int ArenaSize { get{ return m_ArenaSize; } set { m_ArenaSize = value; } }
[CommandProperty( AccessLevel.GameMaster )]
public int Winner { get{ return m_Winner; } set { m_Winner = value; } }
public override ArrayList Participants { get{ return m_Participants; } set { m_Participants = value; } }
public override int TotalPurse { get { return m_TotalPurse; } set { m_TotalPurse = value; } }
public override int EntryFee { get { return m_EntryFee; } set { m_EntryFee = value; } }
public override bool InsuranceIsFree(Mobile from, Mobile awardto)
{
return true;
}
public override bool AreTeamMembers(Mobile from, Mobile target)
{
if(from == null || target == null) return false;
int frommember = 0;
int targetmember = 0;
// go through each teams members list and determine whether the players are on any team list
if(Participants != null)
{
foreach(IChallengeEntry entry in Participants)
{
if(!(entry.Status == ChallengeStatus.Active)) continue;
Mobile m = entry.Participant;
if(m == from)
{
frommember = entry.Team;
}
if(m == target)
{
targetmember = entry.Team;
}
}
}
return (frommember == targetmember && frommember != 0 && targetmember != 0);
}
public override bool AreChallengers(Mobile from, Mobile target)
{
if(from == null || target == null) return false;
int frommember = 0;
int targetmember = 0;
// go through each teams members list and determine whether the players are on any team list
if(Participants != null)
{
foreach(IChallengeEntry entry in Participants)
{
if(!(entry.Status == ChallengeStatus.Active)) continue;
Mobile m = entry.Participant;
if(m == from)
{
frommember = entry.Team;
}
if(m == target)
{
targetmember = entry.Team;
}
}
}
return (frommember != targetmember && frommember != 0 && targetmember != 0);
}
public override void OnTick()
{
CheckForDisqualification();
}
public void CheckForDisqualification()
{
if(Participants == null || !GameInProgress) return;
bool statuschange = false;
foreach(IChallengeEntry entry in Participants)
{
if(entry.Participant == null || entry.Status == ChallengeStatus.Forfeit || entry.Status == ChallengeStatus.Disqualified) continue;
bool hadcaution = (entry.Caution != ChallengeStatus.None);
// and a map check
if(entry.Participant.Map != Map)
{
// check to see if they are offline
if(entry.Participant.Map == Map.Internal)
{
// then give them a little time to return before disqualification
if(entry.Caution == ChallengeStatus.Offline)
{
// were previously out of bounds so check for disqualification
// check to see how long they have been out of bounds
if(DateTime.UtcNow - entry.LastCaution > MaximumOfflineDuration)
{
entry.Status = ChallengeStatus.Disqualified;
GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified"
RefreshSymmetricNoto(entry.Participant);
statuschange = true;
}
} else
{
entry.LastCaution = DateTime.UtcNow;
statuschange = true;
}
entry.Caution = ChallengeStatus.Offline;
} else
{
// changing to any other map is instant disqualification
entry.Status = ChallengeStatus.Disqualified;
GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified"
RefreshSymmetricNoto(entry.Participant);
statuschange = true;
}
} else
// make a range check
if(m_ArenaSize > 0 && !Utility.InRange(entry.Participant.Location, Location, m_ArenaSize)
|| (IsInChallengeGameRegion && !(Region.Find(entry.Participant.Location, entry.Participant.Map) is ChallengeGameRegion)))
{
if(entry.Caution == ChallengeStatus.OutOfBounds)
{
// were previously out of bounds so check for disqualification
// check to see how long they have been out of bounds
if(DateTime.UtcNow - entry.LastCaution > MaximumOutOfBoundsDuration)
{
entry.Status = ChallengeStatus.Disqualified;
GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified"
RefreshSymmetricNoto(entry.Participant);
statuschange = true;
}
} else
{
entry.LastCaution = DateTime.UtcNow;
// inform the player
XmlPoints.SendText(entry.Participant, 100309, MaximumOutOfBoundsDuration.TotalSeconds); // "You are out of bounds! You have {0} seconds to return"
statuschange = true;
}
entry.Caution = ChallengeStatus.OutOfBounds;
} else
// make a hiding check
if(entry.Participant.Hidden)
{
if(entry.Caution == ChallengeStatus.Hidden)
{
// were previously hidden so check for disqualification
// check to see how long they have hidden
if(DateTime.UtcNow - entry.LastCaution > MaximumHiddenDuration)
{
entry.Status = ChallengeStatus.Disqualified;
GameBroadcast(100308, entry.Participant.Name); // "{0} has been disqualified"
RefreshSymmetricNoto(entry.Participant);
statuschange = true;
}
} else
{
entry.LastCaution = DateTime.UtcNow;
// inform the player
XmlPoints.SendText(entry.Participant, 100310, MaximumHiddenDuration.TotalSeconds); // "You have {0} seconds become unhidden"
statuschange = true;
}
entry.Caution = ChallengeStatus.Hidden;
} else
{
entry.Caution = ChallengeStatus.None;
}
if(hadcaution && entry.Caution == ChallengeStatus.None)
statuschange = true;
}
if(statuschange)
{
// update gumps with the new status
TeamLMSGump.RefreshAllGumps(this, false);
}
// it is possible that the game could end like this so check
CheckForGameEnd();
}
public override void CheckForGameEnd()
{
if(Participants == null || !GameInProgress) return;
ArrayList Remaining = new ArrayList();
// determine how many teams remain
foreach(IChallengeEntry entry in Participants)
{
if(entry.Status == ChallengeStatus.Active)
{
if(!Remaining.Contains(entry.Team))
{
Remaining.Add(entry.Team);
}
}
}
// and then check to see if this is the last team standing
if(Remaining.Count == 1)
{
// declare the winner and end the game
Winner = (int)Remaining[0];
GameBroadcast( 100414, Winner); // "Team {0} is the winner!"
AwardTeamWinnings(Winner, TotalPurse);
EndGame();
TeamLMSGump.RefreshAllGumps(this, true);
}
if(Remaining.Count < 1)
{
// declare a tie and keep the fees
GameBroadcast(100313); // "The match is a draw"
EndGame();
TeamLMSGump.RefreshAllGumps(this, true);
}
}
public override void OnPlayerKilled(Mobile killer, Mobile killed)
{
if(killed == null) return;
if(AutoRes)
{
// prepare the autores callback
Timer.DelayCall( RespawnTime, new TimerStateCallback( XmlPoints.AutoRes_Callback ),
new object[]{ killed, false } );
}
// find the player in the participants list and set their status to Dead
if(m_Participants != null)
{
foreach(IChallengeEntry entry in m_Participants)
{
if(entry.Participant == killed && entry.Status != ChallengeStatus.Forfeit)
{
entry.Status = ChallengeStatus.Dead;
// clear up their noto
RefreshSymmetricNoto(killed);
GameBroadcast(100314, killed.Name); // "{0} has been killed"
}
}
}
TeamLMSGump.RefreshAllGumps(this, true);
// see if the game is over
CheckForGameEnd();
}
public TeamLMSGauntlet(Mobile challenger) : base( 0x1414 )
{
m_Challenger = challenger;
m_Organizers.Add(challenger);
// check for points attachments
XmlPoints afrom = (XmlPoints)XmlAttach.FindAttachment(challenger, typeof(XmlPoints));
Movable = false;
Hue = 33;
if(challenger == null || afrom == null || afrom.Deleted)
{
Delete();
} else
{
Name = XmlPoints.SystemText(100413) + " " + String.Format(XmlPoints.SystemText(100315), challenger.Name); // "Challenge by {0}"
}
}
public TeamLMSGauntlet( Serial serial ) : base( serial )
{
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
writer.Write(m_Challenger);
writer.Write(m_GameLocked);
writer.Write(m_GameInProgress);
writer.Write(m_TotalPurse);
writer.Write(m_EntryFee);
writer.Write(m_ArenaSize);
writer.Write(m_Winner);
if(Participants != null)
{
writer.Write(Participants.Count);
foreach(ChallengeEntry entry in Participants)
{
writer.Write(entry.Participant);
writer.Write(entry.Status.ToString());
writer.Write(entry.Accepted);
writer.Write(entry.PageBeingViewed);
writer.Write(entry.Team);
}
} else
{
writer.Write((int)0);
}
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
switch(version)
{
case 0:
m_Challenger = reader.ReadMobile();
m_Organizers.Add(m_Challenger);
m_GameLocked = reader.ReadBool();
m_GameInProgress = reader.ReadBool();
m_TotalPurse = reader.ReadInt();
m_EntryFee = reader.ReadInt();
m_ArenaSize = reader.ReadInt();
m_Winner = reader.ReadInt();
int count = reader.ReadInt();
for(int i = 0;i<count;i++)
{
ChallengeEntry entry = new ChallengeEntry();
entry.Participant = reader.ReadMobile();
string sname = reader.ReadString();
// look up the enum by name
ChallengeStatus status = ChallengeStatus.None;
try{
status = (ChallengeStatus)Enum.Parse(typeof(ChallengeStatus), sname);
} catch{}
entry.Status = status;
entry.Accepted = reader.ReadBool();
entry.PageBeingViewed = reader.ReadInt();
entry.Team = reader.ReadInt();
Participants.Add(entry);
}
break;
}
if(GameCompleted)
Timer.DelayCall( PostGameDecayTime, new TimerCallback( Delete ) );
StartChallengeTimer();
SetNameHue();
}
public override void OnDelete()
{
ClearNameHue();
base.OnDelete();
}
public override void EndGame()
{
ClearNameHue();
base.EndGame();
}
public override void StartGame()
{
base.StartGame();
SetNameHue();
}
public override void OnDoubleClick( Mobile from )
{
from.SendGump( new TeamLMSGump( this, from ) );
}
}
}
| gpl-2.0 |
freedesktop-unofficial-mirror/gstreamer-sdk__gcc | libstdc++-v3/testsuite/27_io/basic_filebuf/open/char/1.cc | 2269 | // Copyright (C) 2001, 2002, 2003, 2009, 2010 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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 General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// 27.8.1.3 filebuf member functions
// @require@ %-*.tst %-*.txt
// @diff@ %-*.tst %-*.txt
// various tests for filebuf::open() and filebuf::close() including
// the non-portable functionality in the libstdc++-v3 IO library
// { dg-require-fileio "" }
#include <fstream>
#include <testsuite_hooks.h>
const char name_01[] = "filebuf_members-1.tst";
const char name_02[] = "filebuf_members-1.txt";
// Test member functions.
void test_01()
{
bool test __attribute__((unused)) = true;
const char* name_03 = "filebuf_members-3"; // empty file, need to create
std::filebuf fb_01; // in
std::filebuf fb_02; // out
std::filebuf fb_03; // in | out
// bool is_open()
VERIFY( !fb_01.is_open() );
VERIFY( !fb_02.is_open() );
VERIFY( !fb_03.is_open() );
// filebuf_type* open(const char* __s, ios_base::openmode __mode)
fb_01.open(name_01, std::ios_base::in | std::ios_base::ate);
VERIFY( fb_01.is_open() );
// Try to open two different files without closing the first:
// Should keep the old file attached, and disregard attempt to overthrow.
std::filebuf* f = fb_02.open(name_02, std::ios_base::in | std::ios_base::out
| std::ios_base::trunc);
VERIFY( f );
VERIFY( fb_02.is_open() );
f = fb_02.open(name_03, std::ios_base::in | std::ios_base::out);
VERIFY( !f );
VERIFY( fb_02.is_open() );
fb_03.open(name_03, std::ios_base::out | std::ios_base::trunc);
VERIFY( fb_03.is_open() );
}
int
main()
{
test_01();
return 0;
}
| gpl-2.0 |
irares/WirelessHart-Gateway | cpplib/trunk/boost_1_36_0/boost/tr1/memory.hpp | 2166 | // (C) Copyright John Maddock 2005.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_TR1_MEMORY_HPP_INCLUDED
# define BOOST_TR1_MEMORY_HPP_INCLUDED
# include <boost/tr1/detail/config.hpp>
# include <boost/detail/workaround.hpp>
# include <memory>
#ifndef BOOST_HAS_TR1_SHARED_PTR
//
// This header can get included by boost/shared_ptr.hpp which leads
// to cyclic dependencies, the workaround is to forward declare all
// the boost components, and then include the actual headers afterwards.
// This is fragile, but seems to work, and doesn't require modification
// of boost/shared_ptr.hpp.
//
namespace boost{
class bad_weak_ptr;
template<class T> class weak_ptr;
template<class T> class shared_ptr;
template<class T> void swap(weak_ptr<T> & a, weak_ptr<T> & b);
template<class T> void swap(shared_ptr<T> & a, shared_ptr<T> & b);
template<class T, class U> shared_ptr<T> static_pointer_cast(shared_ptr<U> const & r);
template<class T, class U> shared_ptr<T> dynamic_pointer_cast(shared_ptr<U> const & r);
template<class T, class U> shared_ptr<T> const_pointer_cast(shared_ptr<U> const & r);
template<class D, class T> D * get_deleter(shared_ptr<T> const & p);
template<class T> class enable_shared_from_this;
namespace detail{
class shared_count;
class weak_count;
}
}
namespace std{ namespace tr1{
using ::boost::bad_weak_ptr;
using ::boost::shared_ptr;
#if !BOOST_WORKAROUND(__BORLANDC__, < 0x0582)
using ::boost::swap;
#endif
using ::boost::static_pointer_cast;
using ::boost::dynamic_pointer_cast;
using ::boost::const_pointer_cast;
using ::boost::get_deleter;
using ::boost::weak_ptr;
using ::boost::enable_shared_from_this;
} }
#include <boost/shared_ptr.hpp>
#include <boost/weak_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#else
# ifdef BOOST_HAS_INCLUDE_NEXT
# include_next BOOST_TR1_HEADER(memory)
# else
# include <boost/tr1/detail/config_all.hpp>
# include BOOST_TR1_STD_HEADER(BOOST_TR1_PATH(memory))
# endif
#endif
#endif
| gpl-3.0 |
dNovo/shopware | engine/Shopware/Components/Migrations/AbstractMigration.php | 2890 | <?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* 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.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace Shopware\Components\Migrations;
/**
* @category Shopware
* @package Shopware\Components\Migrations
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
abstract class AbstractMigration
{
const MODUS_UPDATE = 'update';
const MODUS_INSTALL = 'install';
/**
* @var \PDO
*/
protected $connection;
/**
* @var array
*/
protected $sql = array();
/**
* @param \PDO $connection
*/
public function __construct(\PDO $connection)
{
$this->connection = $connection;
}
/**
* @param \PDO $connection
* @return AbstractMigration
*/
public function setConnection($connection)
{
$this->connection = $connection;
return $this;
}
/**
* @return \PDO
*/
public function getConnection()
{
return $this->connection;
}
/**
* @return string
*/
public function getLabel()
{
$result = array();
$regexPattern = '/[0-9]*-(.+)\.php$/i';
$rc = new \ReflectionClass(get_class($this));
$fileName = basename($rc->getFileName());
preg_match($regexPattern, $fileName, $result);
return $result[1];
}
/**
* @return int
*/
public function getVersion()
{
$result = array();
$regexPattern = '/[0-9]*$/i';
preg_match($regexPattern, get_class($this), $result);
return (int) $result[0];
}
/**
* @param string $modus
* @return void
*/
abstract public function up($modus);
/**
* @param string $sql
* @return AbstractMigration
*/
public function addSql($sql)
{
// assure statement ends with semicolon
$sql = rtrim($sql, ';');
$this->sql[] = $sql;
return $this;
}
/**
* @return array
*/
public function getSql()
{
return $this->sql;
}
}
| agpl-3.0 |
gaohoward/activemq-artemis | tests/activemq5-unit-tests/src/test/java/org/apache/activemq/transport/nio/NIOTransportBrokerTest.java | 1313 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.transport.nio;
import junit.framework.Test;
import junit.textui.TestRunner;
import org.apache.activemq.transport.TransportBrokerTestSupport;
public class NIOTransportBrokerTest extends TransportBrokerTestSupport {
@Override
protected String getBindLocation() {
return "nio://localhost:61616";
}
public static Test suite() {
return suite(NIOTransportBrokerTest.class);
}
public static void main(String[] args) {
TestRunner.run(suite());
}
}
| apache-2.0 |
MKrishtop/facebook-android-sdk | facebook/TestApp/src/com/facebook/sdk/StatusActivity.java | 949 | /**
* Copyright 2010-present Facebook.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.sdk;
import android.app.Activity;
import android.os.Bundle;
public class StatusActivity extends Activity
{
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
| apache-2.0 |
signed/intellij-community | java/java-tests/testData/codeInsight/parameterInfo/OverloadWithVarargsSingleArg.java | 118 | class Main {
static <T> void of(T t) {}
static <T> void of(T... t) {}
void foo(){
Main.of("<caret>");
}
} | apache-2.0 |
baslr/ArangoDB | 3rdParty/boost/1.62.0/libs/math/test/compile_test/sf_bernoulli_incl_test.cpp | 1092 | // Copyright John Maddock 2012.
// Use, modification and distribution are subject to the
// Boost Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Basic sanity check that header <boost/math/special_functions/bernoulli.hpp>
// #includes all the files that it needs to.
//
#include <boost/math/special_functions/bernoulli.hpp>
//
// Note this header includes no other headers, this is
// important if this test is to be meaningful:
//
#include "test_compile_result.hpp"
void compile_and_link_test()
{
check_result<float>(boost::math::bernoulli_b2n<float>(i));
check_result<double>(boost::math::bernoulli_b2n<double>(i));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
check_result<long double>(boost::math::bernoulli_b2n<long double>(i));
#endif
check_result<float>(boost::math::tangent_t2n<float>(i));
check_result<double>(boost::math::tangent_t2n<double>(i));
#ifndef BOOST_MATH_NO_LONG_DOUBLE_MATH_FUNCTIONS
check_result<long double>(boost::math::tangent_t2n<long double>(i));
#endif
}
| apache-2.0 |
adobe/chromium | base/i18n/icu_string_conversions_unittest.cc | 14063 | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <math.h>
#include <stdarg.h>
#include <limits>
#include <sstream>
#include "base/basictypes.h"
#include "base/format_macros.h"
#include "base/i18n/icu_string_conversions.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/string_piece.h"
#include "base/utf_string_conversions.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace base {
namespace {
// Given a null-terminated string of wchar_t with each wchar_t representing
// a UTF-16 code unit, returns a string16 made up of wchar_t's in the input.
// Each wchar_t should be <= 0xFFFF and a non-BMP character (> U+FFFF)
// should be represented as a surrogate pair (two UTF-16 units)
// *even* where wchar_t is 32-bit (Linux and Mac).
//
// This is to help write tests for functions with string16 params until
// the C++ 0x UTF-16 literal is well-supported by compilers.
string16 BuildString16(const wchar_t* s) {
#if defined(WCHAR_T_IS_UTF16)
return string16(s);
#elif defined(WCHAR_T_IS_UTF32)
string16 u16;
while (*s != 0) {
DCHECK_LE(static_cast<unsigned int>(*s), 0xFFFFu);
u16.push_back(*s++);
}
return u16;
#endif
}
const wchar_t* const kConvertRoundtripCases[] = {
L"Google Video",
// "网页 图片 资讯更多 »"
L"\x7f51\x9875\x0020\x56fe\x7247\x0020\x8d44\x8baf\x66f4\x591a\x0020\x00bb",
// "Παγκόσμιος Ιστός"
L"\x03a0\x03b1\x03b3\x03ba\x03cc\x03c3\x03bc\x03b9"
L"\x03bf\x03c2\x0020\x0399\x03c3\x03c4\x03cc\x03c2",
// "Поиск страниц на русском"
L"\x041f\x043e\x0438\x0441\x043a\x0020\x0441\x0442"
L"\x0440\x0430\x043d\x0438\x0446\x0020\x043d\x0430"
L"\x0020\x0440\x0443\x0441\x0441\x043a\x043e\x043c",
// "전체서비스"
L"\xc804\xccb4\xc11c\xbe44\xc2a4",
// Test characters that take more than 16 bits. This will depend on whether
// wchar_t is 16 or 32 bits.
#if defined(WCHAR_T_IS_UTF16)
L"\xd800\xdf00",
// ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
L"\xd807\xdd40\xd807\xdd41\xd807\xdd42\xd807\xdd43\xd807\xdd44",
#elif defined(WCHAR_T_IS_UTF32)
L"\x10300",
// ????? (Mathematical Alphanumeric Symbols (U+011d40 - U+011d44 : A,B,C,D,E)
L"\x11d40\x11d41\x11d42\x11d43\x11d44",
#endif
};
} // namespace
TEST(ICUStringConversionsTest, ConvertCodepageUTF8) {
// Make sure WideToCodepage works like WideToUTF8.
for (size_t i = 0; i < arraysize(kConvertRoundtripCases); ++i) {
SCOPED_TRACE(base::StringPrintf("Test[%" PRIuS "]: %ls",
i, kConvertRoundtripCases[i]));
std::string expected(WideToUTF8(kConvertRoundtripCases[i]));
std::string utf8;
EXPECT_TRUE(WideToCodepage(kConvertRoundtripCases[i], kCodepageUTF8,
OnStringConversionError::SKIP, &utf8));
EXPECT_EQ(expected, utf8);
}
}
// kConverterCodepageCases is not comprehensive. There are a number of cases
// to add if we really want to have a comprehensive coverage of various
// codepages and their 'idiosyncrasies'. Currently, the only implementation
// for CodepageTo* and *ToCodepage uses ICU, which has a very extensive
// set of tests for the charset conversion. So, we can get away with a
// relatively small number of cases listed below.
//
// Note about |u16_wide| in the following struct.
// On Windows, the field is always identical to |wide|. On Mac and Linux,
// it's identical as long as there's no character outside the
// BMP (<= U+FFFF). When there is, it is different from |wide| and
// is not a real wide string (UTF-32 string) in that each wchar_t in
// the string is a UTF-16 code unit zero-extended to be 32-bit
// even when the code unit belongs to a surrogate pair.
// For instance, a Unicode string (U+0041 U+010000) is represented as
// L"\x0041\xD800\xDC00" instead of L"\x0041\x10000".
// To avoid the clutter, |u16_wide| will be set to NULL
// if it's identical to |wide| on *all* platforms.
static const struct {
const char* codepage_name;
const char* encoded;
OnStringConversionError::Type on_error;
bool success;
const wchar_t* wide;
const wchar_t* u16_wide;
} kConvertCodepageCases[] = {
// Test a case where the input cannot be decoded, using SKIP, FAIL
// and SUBSTITUTE error handling rules. "A7 41" is valid, but "A6" isn't.
{"big5",
"\xA7\x41\xA6",
OnStringConversionError::FAIL,
false,
L"",
NULL},
{"big5",
"\xA7\x41\xA6",
OnStringConversionError::SKIP,
true,
L"\x4F60",
NULL},
{"big5",
"\xA7\x41\xA6",
OnStringConversionError::SUBSTITUTE,
true,
L"\x4F60\xFFFD",
NULL},
// Arabic (ISO-8859)
{"iso-8859-6",
"\xC7\xEE\xE4\xD3\xF1\xEE\xE4\xC7\xE5\xEF" " "
"\xD9\xEE\xE4\xEE\xEA\xF2\xE3\xEF\xE5\xF2",
OnStringConversionError::FAIL,
true,
L"\x0627\x064E\x0644\x0633\x0651\x064E\x0644\x0627\x0645\x064F" L" "
L"\x0639\x064E\x0644\x064E\x064A\x0652\x0643\x064F\x0645\x0652",
NULL},
// Chinese Simplified (GB2312)
{"gb2312",
"\xC4\xE3\xBA\xC3",
OnStringConversionError::FAIL,
true,
L"\x4F60\x597D",
NULL},
// Chinese (GB18030) : 4 byte sequences mapped to BMP characters
{"gb18030",
"\x81\x30\x84\x36\xA1\xA7",
OnStringConversionError::FAIL,
true,
L"\x00A5\x00A8",
NULL},
// Chinese (GB18030) : A 4 byte sequence mapped to plane 2 (U+20000)
{"gb18030",
"\x95\x32\x82\x36\xD2\xBB",
OnStringConversionError::FAIL,
true,
#if defined(WCHAR_T_IS_UTF16)
L"\xD840\xDC00\x4E00",
#elif defined(WCHAR_T_IS_UTF32)
L"\x20000\x4E00",
#endif
L"\xD840\xDC00\x4E00"},
{"big5",
"\xA7\x41\xA6\x6E",
OnStringConversionError::FAIL,
true,
L"\x4F60\x597D",
NULL},
// Greek (ISO-8859)
{"iso-8859-7",
"\xE3\xE5\xE9\xDC" " " "\xF3\xEF\xF5",
OnStringConversionError::FAIL,
true,
L"\x03B3\x03B5\x03B9\x03AC" L" " L"\x03C3\x03BF\x03C5",
NULL},
// Hebrew (Windows)
{"windows-1255",
"\xF9\xD1\xC8\xEC\xE5\xC9\xED",
OnStringConversionError::FAIL,
true,
L"\x05E9\x05C1\x05B8\x05DC\x05D5\x05B9\x05DD",
NULL},
// Hindi Devanagari (ISCII)
{"iscii-dev",
"\xEF\x42" "\xC6\xCC\xD7\xE8\xB3\xDA\xCF",
OnStringConversionError::FAIL,
true,
L"\x0928\x092E\x0938\x094D\x0915\x093E\x0930",
NULL},
// Korean (EUC)
{"euc-kr",
"\xBE\xC8\xB3\xE7\xC7\xCF\xBC\xBC\xBF\xE4",
OnStringConversionError::FAIL,
true,
L"\xC548\xB155\xD558\xC138\xC694",
NULL},
// Japanese (EUC)
{"euc-jp",
"\xA4\xB3\xA4\xF3\xA4\xCB\xA4\xC1\xA4\xCF\xB0\xEC\x8F\xB0\xA1\x8E\xA6",
OnStringConversionError::FAIL,
true,
L"\x3053\x3093\x306B\x3061\x306F\x4E00\x4E02\xFF66",
NULL},
// Japanese (ISO-2022)
{"iso-2022-jp",
"\x1B$B" "\x24\x33\x24\x73\x24\x4B\x24\x41\x24\x4F\x30\x6C" "\x1B(B"
"ab" "\x1B(J" "\x5C\x7E#$" "\x1B(B",
OnStringConversionError::FAIL,
true,
L"\x3053\x3093\x306B\x3061\x306F\x4E00" L"ab\x00A5\x203E#$",
NULL},
// Japanese (Shift-JIS)
{"sjis",
"\x82\xB1\x82\xF1\x82\xC9\x82\xBF\x82\xCD\x88\xEA\xA6",
OnStringConversionError::FAIL,
true,
L"\x3053\x3093\x306B\x3061\x306F\x4E00\xFF66",
NULL},
// Russian (KOI8)
{"koi8-r",
"\xDA\xC4\xD2\xC1\xD7\xD3\xD4\xD7\xD5\xCA\xD4\xC5",
OnStringConversionError::FAIL,
true,
L"\x0437\x0434\x0440\x0430\x0432\x0441\x0442\x0432"
L"\x0443\x0439\x0442\x0435",
NULL},
// Thai (windows-874)
{"windows-874",
"\xCA\xC7\xD1\xCA\xB4\xD5" "\xA4\xC3\xD1\xBA",
OnStringConversionError::FAIL,
true,
L"\x0E2A\x0E27\x0E31\x0E2A\x0E14\x0E35"
L"\x0E04\x0E23\x0e31\x0E1A",
NULL},
// Empty text
{"iscii-dev",
"",
OnStringConversionError::FAIL,
true,
L"",
NULL},
};
TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndWide) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertCodepageCases); ++i) {
SCOPED_TRACE(base::StringPrintf(
"Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i,
kConvertCodepageCases[i].encoded,
kConvertCodepageCases[i].codepage_name));
std::wstring wide;
bool success = CodepageToWide(kConvertCodepageCases[i].encoded,
kConvertCodepageCases[i].codepage_name,
kConvertCodepageCases[i].on_error,
&wide);
EXPECT_EQ(kConvertCodepageCases[i].success, success);
EXPECT_EQ(kConvertCodepageCases[i].wide, wide);
// When decoding was successful and nothing was skipped, we also check the
// reverse conversion. Not all conversions are round-trippable, but
// kConverterCodepageCases does not have any one-way conversion at the
// moment.
if (success &&
kConvertCodepageCases[i].on_error ==
OnStringConversionError::FAIL) {
std::string encoded;
success = WideToCodepage(wide, kConvertCodepageCases[i].codepage_name,
kConvertCodepageCases[i].on_error, &encoded);
EXPECT_EQ(kConvertCodepageCases[i].success, success);
EXPECT_EQ(kConvertCodepageCases[i].encoded, encoded);
}
}
// The above cases handled codepage->wide errors, but not wide->codepage.
// Test that here.
std::string encoded("Temp data"); // Make sure the string gets cleared.
// First test going to an encoding that can not represent that character.
EXPECT_FALSE(WideToCodepage(L"Chinese\xff27", "iso-8859-1",
OnStringConversionError::FAIL, &encoded));
EXPECT_TRUE(encoded.empty());
EXPECT_TRUE(WideToCodepage(L"Chinese\xff27", "iso-8859-1",
OnStringConversionError::SKIP, &encoded));
EXPECT_STREQ("Chinese", encoded.c_str());
// From Unicode, SUBSTITUTE is the same as SKIP for now.
EXPECT_TRUE(WideToCodepage(L"Chinese\xff27", "iso-8859-1",
OnStringConversionError::SUBSTITUTE,
&encoded));
EXPECT_STREQ("Chinese", encoded.c_str());
#if defined(WCHAR_T_IS_UTF16)
// When we're in UTF-16 mode, test an invalid UTF-16 character in the input.
EXPECT_FALSE(WideToCodepage(L"a\xd800z", "iso-8859-1",
OnStringConversionError::FAIL, &encoded));
EXPECT_TRUE(encoded.empty());
EXPECT_TRUE(WideToCodepage(L"a\xd800z", "iso-8859-1",
OnStringConversionError::SKIP, &encoded));
EXPECT_STREQ("az", encoded.c_str());
#endif // WCHAR_T_IS_UTF16
// Invalid characters should fail.
EXPECT_TRUE(WideToCodepage(L"a\xffffz", "iso-8859-1",
OnStringConversionError::SKIP, &encoded));
EXPECT_STREQ("az", encoded.c_str());
// Invalid codepages should fail.
EXPECT_FALSE(WideToCodepage(L"Hello, world", "awesome-8571-2",
OnStringConversionError::SKIP, &encoded));
}
TEST(ICUStringConversionsTest, ConvertBetweenCodepageAndUTF16) {
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertCodepageCases); ++i) {
SCOPED_TRACE(base::StringPrintf(
"Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i,
kConvertCodepageCases[i].encoded,
kConvertCodepageCases[i].codepage_name));
string16 utf16;
bool success = CodepageToUTF16(kConvertCodepageCases[i].encoded,
kConvertCodepageCases[i].codepage_name,
kConvertCodepageCases[i].on_error,
&utf16);
string16 utf16_expected;
if (kConvertCodepageCases[i].u16_wide == NULL)
utf16_expected = BuildString16(kConvertCodepageCases[i].wide);
else
utf16_expected = BuildString16(kConvertCodepageCases[i].u16_wide);
EXPECT_EQ(kConvertCodepageCases[i].success, success);
EXPECT_EQ(utf16_expected, utf16);
// When decoding was successful and nothing was skipped, we also check the
// reverse conversion. See also the corresponding comment in
// ConvertBetweenCodepageAndWide.
if (success &&
kConvertCodepageCases[i].on_error == OnStringConversionError::FAIL) {
std::string encoded;
success = UTF16ToCodepage(utf16, kConvertCodepageCases[i].codepage_name,
kConvertCodepageCases[i].on_error, &encoded);
EXPECT_EQ(kConvertCodepageCases[i].success, success);
EXPECT_EQ(kConvertCodepageCases[i].encoded, encoded);
}
}
}
static const struct {
const char* encoded;
const char* codepage_name;
bool expected_success;
const char* expected_value;
} kConvertAndNormalizeCases[] = {
{"foo-\xe4.html", "iso-8859-1", true, "foo-\xc3\xa4.html"},
{"foo-\xe4.html", "iso-8859-7", true, "foo-\xce\xb4.html"},
{"foo-\xe4.html", "foo-bar", false, ""},
{"foo-\xff.html", "ascii", false, ""},
{"foo.html", "ascii", true, "foo.html"},
{"foo-a\xcc\x88.html", "utf-8", true, "foo-\xc3\xa4.html"},
{"\x95\x32\x82\x36\xD2\xBB", "gb18030", true, "\xF0\xA0\x80\x80\xE4\xB8\x80"},
{"\xA7\x41\xA6\x6E", "big5", true, "\xE4\xBD\xA0\xE5\xA5\xBD"},
// Windows-1258 does have a combining character at xD2 (which is U+0309).
// The sequence of (U+00E2, U+0309) is also encoded as U+1EA9.
{"foo\xE2\xD2", "windows-1258", true, "foo\xE1\xBA\xA9"},
{"", "iso-8859-1", true, ""},
};
TEST(ICUStringConversionsTest, ConvertToUtf8AndNormalize) {
std::string result;
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kConvertAndNormalizeCases); ++i) {
SCOPED_TRACE(base::StringPrintf(
"Test[%" PRIuS "]: <encoded: %s> <codepage: %s>", i,
kConvertAndNormalizeCases[i].encoded,
kConvertAndNormalizeCases[i].codepage_name));
bool success = ConvertToUtf8AndNormalize(
kConvertAndNormalizeCases[i].encoded,
kConvertAndNormalizeCases[i].codepage_name, &result);
EXPECT_EQ(kConvertAndNormalizeCases[i].expected_success, success);
EXPECT_EQ(kConvertAndNormalizeCases[i].expected_value, result);
}
}
} // namespace base
| bsd-3-clause |
Jay5066/drupalDockerCompose | vendor/twig/twig/lib/Twig/Node/Expression/NullCoalesce.php | 1838 | <?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Twig_Node_Expression_NullCoalesce extends Twig_Node_Expression_Conditional
{
public function __construct(Twig_NodeInterface $left, Twig_NodeInterface $right, $lineno)
{
$test = new Twig_Node_Expression_Binary_And(
new Twig_Node_Expression_Test_Defined(clone $left, 'defined', new Twig_Node(), $left->getTemplateLine()),
new Twig_Node_Expression_Unary_Not(new Twig_Node_Expression_Test_Null($left, 'null', new Twig_Node(), $left->getTemplateLine()), $left->getTemplateLine()),
$left->getTemplateLine()
);
parent::__construct($test, $left, $right, $lineno);
}
public function compile(Twig_Compiler $compiler)
{
/*
* This optimizes only one case. PHP 7 also supports more complex expressions
* that can return null. So, for instance, if log is defined, log("foo") ?? "..." works,
* but log($a["foo"]) ?? "..." does not if $a["foo"] is not defined. More advanced
* cases might be implemented as an optimizer node visitor, but has not been done
* as benefits are probably not worth the added complexity.
*/
if (PHP_VERSION_ID >= 70000 && $this->getNode('expr2') instanceof Twig_Node_Expression_Name) {
$this->getNode('expr2')->setAttribute('always_defined', true);
$compiler
->raw('((')
->subcompile($this->getNode('expr2'))
->raw(') ?? (')
->subcompile($this->getNode('expr3'))
->raw('))')
;
} else {
parent::compile($compiler);
}
}
}
| gpl-2.0 |
amosdesigns/fmintroreact | node_modules/react-router-dom/es/Redirect.js | 51 | export { Redirect as default } from 'react-router'; | mit |
SonOfLilit/coffeescript | documentation/coffee/expressions_try.js | 204 | // Generated by CoffeeScript 1.9.3
var error;
alert((function() {
try {
return nonexistent / void 0;
} catch (_error) {
error = _error;
return "And the error is ... " + error;
}
})());
| mit |
prayuditb/tryout-01 | websocket/client/Client/node_modules/react-native/Libraries/PushNotificationIOS/PushNotificationIOS.js | 16951 | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PushNotificationIOS
* @flow
*/
'use strict';
const NativeEventEmitter = require('NativeEventEmitter');
const RCTPushNotificationManager = require('NativeModules').PushNotificationManager;
const invariant = require('fbjs/lib/invariant');
const PushNotificationEmitter = new NativeEventEmitter(RCTPushNotificationManager);
const _notifHandlers = new Map();
const DEVICE_NOTIF_EVENT = 'remoteNotificationReceived';
const NOTIF_REGISTER_EVENT = 'remoteNotificationsRegistered';
const NOTIF_REGISTRATION_ERROR_EVENT = 'remoteNotificationRegistrationError';
const DEVICE_LOCAL_NOTIF_EVENT = 'localNotificationReceived';
export type FetchResult = {
NewData: string,
NoData: string,
ResultFailed: string,
};
/**
* An event emitted by PushNotificationIOS.
*/
export type PushNotificationEventName = $Enum<{
/**
* Fired when a remote notification is received. The handler will be invoked
* with an instance of `PushNotificationIOS`.
*/
notification: string,
/**
* Fired when a local notification is received. The handler will be invoked
* with an instance of `PushNotificationIOS`.
*/
localNotification: string,
/**
* Fired when the user registers for remote notifications. The handler will be
* invoked with a hex string representing the deviceToken.
*/
register: string,
/**
* Fired when the user fails to register for remote notifications. Typically
* occurs when APNS is having issues, or the device is a simulator. The
* handler will be invoked with {message: string, code: number, details: any}.
*/
registrationError: string,
}>;
/**
* Handle push notifications for your app, including permission handling and
* icon badge number.
*
* To get up and running, [configure your notifications with Apple](https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW6)
* and your server-side system. To get an idea, [this is the Parse guide](https://parse.com/tutorials/ios-push-notifications).
*
* [Manually link](docs/linking-libraries-ios.html#manual-linking) the PushNotificationIOS library
*
* - Add the following to your Project: `node_modules/react-native/Libraries/PushNotificationIOS/RCTPushNotification.xcodeproj`
* - Add the following to `Link Binary With Libraries`: `libRCTPushNotification.a`
* - Add the following to your `Header Search Paths`:
* `$(SRCROOT)/../node_modules/react-native/Libraries/PushNotificationIOS` and set the search to `recursive`
*
* Finally, to enable support for `notification` and `register` events you need to augment your AppDelegate.
*
* At the top of your `AppDelegate.m`:
*
* `#import "RCTPushNotificationManager.h"`
*
* And then in your AppDelegate implementation add the following:
*
* ```
* // Required to register for notifications
* - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
* {
* [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
* }
* // Required for the register event.
* - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
* {
* [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
* }
* // Required for the notification event. You must call the completion handler after handling the remote notification.
* - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
* fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
* {
* [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
* }
* // Required for the registrationError event.
* - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
* {
* [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
* }
* // Required for the localNotification event.
* - (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
* {
* [RCTPushNotificationManager didReceiveLocalNotification:notification];
* }
* ```
*/
class PushNotificationIOS {
_data: Object;
_alert: string | Object;
_sound: string;
_badgeCount: number;
_notificationId: string;
_isRemote: boolean;
_remoteNotificationCompleteCalllbackCalled: boolean;
static FetchResult: FetchResult = {
NewData: 'UIBackgroundFetchResultNewData',
NoData: 'UIBackgroundFetchResultNoData',
ResultFailed: 'UIBackgroundFetchResultFailed',
};
/**
* Schedules the localNotification for immediate presentation.
*
* details is an object containing:
*
* - `alertBody` : The message displayed in the notification alert.
* - `alertAction` : The "action" displayed beneath an actionable notification. Defaults to "view";
* - `soundName` : The sound played when the notification is fired (optional).
* - `category` : The category of this notification, required for actionable notifications (optional).
* - `userInfo` : An optional object containing additional notification data.
* - `applicationIconBadgeNumber` (optional) : The number to display as the app's icon badge. The default value of this property is 0, which means that no badge is displayed.
*/
static presentLocalNotification(details: Object) {
RCTPushNotificationManager.presentLocalNotification(details);
}
/**
* Schedules the localNotification for future presentation.
*
* details is an object containing:
*
* - `fireDate` : The date and time when the system should deliver the notification.
* - `alertBody` : The message displayed in the notification alert.
* - `alertAction` : The "action" displayed beneath an actionable notification. Defaults to "view";
* - `soundName` : The sound played when the notification is fired (optional).
* - `category` : The category of this notification, required for actionable notifications (optional).
* - `userInfo` : An optional object containing additional notification data.
* - `applicationIconBadgeNumber` (optional) : The number to display as the app's icon badge. Setting the number to 0 removes the icon badge.
* - `repeatInterval` : The interval to repeat as a string. Possible values: `minute`, `hour`, `day`, `week`, `month`, `year`.
*/
static scheduleLocalNotification(details: Object) {
RCTPushNotificationManager.scheduleLocalNotification(details);
}
/**
* Cancels all scheduled localNotifications
*/
static cancelAllLocalNotifications() {
RCTPushNotificationManager.cancelAllLocalNotifications();
}
/**
* Sets the badge number for the app icon on the home screen
*/
static setApplicationIconBadgeNumber(number: number) {
RCTPushNotificationManager.setApplicationIconBadgeNumber(number);
}
/**
* Gets the current badge number for the app icon on the home screen
*/
static getApplicationIconBadgeNumber(callback: Function) {
RCTPushNotificationManager.getApplicationIconBadgeNumber(callback);
}
/**
* Cancel local notifications.
*
* Optionally restricts the set of canceled notifications to those
* notifications whose `userInfo` fields match the corresponding fields
* in the `userInfo` argument.
*/
static cancelLocalNotifications(userInfo: Object) {
RCTPushNotificationManager.cancelLocalNotifications(userInfo);
}
/**
* Gets the local notifications that are currently scheduled.
*/
static getScheduledLocalNotifications(callback: Function) {
RCTPushNotificationManager.getScheduledLocalNotifications(callback);
}
/**
* Attaches a listener to remote or local notification events while the app is running
* in the foreground or the background.
*
* Valid events are:
*
* - `notification` : Fired when a remote notification is received. The
* handler will be invoked with an instance of `PushNotificationIOS`.
* - `localNotification` : Fired when a local notification is received. The
* handler will be invoked with an instance of `PushNotificationIOS`.
* - `register`: Fired when the user registers for remote notifications. The
* handler will be invoked with a hex string representing the deviceToken.
* - `registrationError`: Fired when the user fails to register for remote
* notifications. Typically occurs when APNS is having issues, or the device
* is a simulator. The handler will be invoked with
* {message: string, code: number, details: any}.
*/
static addEventListener(type: PushNotificationEventName, handler: Function) {
invariant(
type === 'notification' || type === 'register' || type === 'registrationError' || type === 'localNotification',
'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events'
);
var listener;
if (type === 'notification') {
listener = PushNotificationEmitter.addListener(
DEVICE_NOTIF_EVENT,
(notifData) => {
handler(new PushNotificationIOS(notifData));
}
);
} else if (type === 'localNotification') {
listener = PushNotificationEmitter.addListener(
DEVICE_LOCAL_NOTIF_EVENT,
(notifData) => {
handler(new PushNotificationIOS(notifData));
}
);
} else if (type === 'register') {
listener = PushNotificationEmitter.addListener(
NOTIF_REGISTER_EVENT,
(registrationInfo) => {
handler(registrationInfo.deviceToken);
}
);
} else if (type === 'registrationError') {
listener = PushNotificationEmitter.addListener(
NOTIF_REGISTRATION_ERROR_EVENT,
(errorInfo) => {
handler(errorInfo);
}
);
}
_notifHandlers.set(type, listener);
}
/**
* Removes the event listener. Do this in `componentWillUnmount` to prevent
* memory leaks
*/
static removeEventListener(type: PushNotificationEventName, handler: Function) {
invariant(
type === 'notification' || type === 'register' || type === 'registrationError' || type === 'localNotification',
'PushNotificationIOS only supports `notification`, `register`, `registrationError`, and `localNotification` events'
);
var listener = _notifHandlers.get(type);
if (!listener) {
return;
}
listener.remove();
_notifHandlers.delete(type);
}
/**
* Requests notification permissions from iOS, prompting the user's
* dialog box. By default, it will request all notification permissions, but
* a subset of these can be requested by passing a map of requested
* permissions.
* The following permissions are supported:
*
* - `alert`
* - `badge`
* - `sound`
*
* If a map is provided to the method, only the permissions with truthy values
* will be requested.
* This method returns a promise that will resolve when the user accepts,
* rejects, or if the permissions were previously rejected. The promise
* resolves to the current state of the permission.
*/
static requestPermissions(permissions?: {
alert?: boolean,
badge?: boolean,
sound?: boolean
}): Promise<{
alert: boolean,
badge: boolean,
sound: boolean
}> {
var requestedPermissions = {};
if (permissions) {
requestedPermissions = {
alert: !!permissions.alert,
badge: !!permissions.badge,
sound: !!permissions.sound
};
} else {
requestedPermissions = {
alert: true,
badge: true,
sound: true
};
}
return RCTPushNotificationManager.requestPermissions(requestedPermissions);
}
/**
* Unregister for all remote notifications received via Apple Push Notification service.
*
* You should call this method in rare circumstances only, such as when a new version of
* the app removes support for all types of remote notifications. Users can temporarily
* prevent apps from receiving remote notifications through the Notifications section of
* the Settings app. Apps unregistered through this method can always re-register.
*/
static abandonPermissions() {
RCTPushNotificationManager.abandonPermissions();
}
/**
* See what push permissions are currently enabled. `callback` will be
* invoked with a `permissions` object:
*
* - `alert` :boolean
* - `badge` :boolean
* - `sound` :boolean
*/
static checkPermissions(callback: Function) {
invariant(
typeof callback === 'function',
'Must provide a valid callback'
);
RCTPushNotificationManager.checkPermissions(callback);
}
/**
* This method returns a promise that resolves to either the notification
* object if the app was launched by a push notification, or `null` otherwise.
*/
static getInitialNotification(): Promise<?PushNotificationIOS> {
return RCTPushNotificationManager.getInitialNotification().then(notification => {
return notification && new PushNotificationIOS(notification);
});
}
/**
* You will never need to instantiate `PushNotificationIOS` yourself.
* Listening to the `notification` event and invoking
* `getInitialNotification` is sufficient
*/
constructor(nativeNotif: Object) {
this._data = {};
this._remoteNotificationCompleteCalllbackCalled = false;
this._isRemote = nativeNotif.remote;
if (this._isRemote) {
this._notificationId = nativeNotif.notificationId;
}
if (nativeNotif.remote) {
// Extract data from Apple's `aps` dict as defined:
// https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
Object.keys(nativeNotif).forEach((notifKey) => {
var notifVal = nativeNotif[notifKey];
if (notifKey === 'aps') {
this._alert = notifVal.alert;
this._sound = notifVal.sound;
this._badgeCount = notifVal.badge;
} else {
this._data[notifKey] = notifVal;
}
});
} else {
// Local notifications aren't being sent down with `aps` dict.
this._badgeCount = nativeNotif.applicationIconBadgeNumber;
this._sound = nativeNotif.soundName;
this._alert = nativeNotif.alertBody;
this._data = nativeNotif.userInfo;
}
}
/**
* This method is available for remote notifications that have been received via:
* `application:didReceiveRemoteNotification:fetchCompletionHandler:`
* https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplicationDelegate_Protocol/#//apple_ref/occ/intfm/UIApplicationDelegate/application:didReceiveRemoteNotification:fetchCompletionHandler:
*
* Call this to execute when the remote notification handling is complete. When
* calling this block, pass in the fetch result value that best describes
* the results of your operation. You *must* call this handler and should do so
* as soon as possible. For a list of possible values, see `PushNotificationIOS.FetchResult`.
*
* If you do not call this method your background remote notifications could
* be throttled, to read more about it see the above documentation link.
*/
finish(fetchResult: FetchResult) {
if (!this._isRemote || !this._notificationId || this._remoteNotificationCompleteCalllbackCalled) {
return;
}
this._remoteNotificationCompleteCalllbackCalled = true;
RCTPushNotificationManager.onFinishRemoteNotification(this._notificationId, fetchResult);
}
/**
* An alias for `getAlert` to get the notification's main message string
*/
getMessage(): ?string | ?Object {
// alias because "alert" is an ambiguous name
return this._alert;
}
/**
* Gets the sound string from the `aps` object
*/
getSound(): ?string {
return this._sound;
}
/**
* Gets the notification's main message from the `aps` object
*/
getAlert(): ?string | ?Object {
return this._alert;
}
/**
* Gets the badge count number from the `aps` object
*/
getBadgeCount(): ?number {
return this._badgeCount;
}
/**
* Gets the data object on the notif
*/
getData(): ?Object {
return this._data;
}
}
module.exports = PushNotificationIOS;
| mit |
frnk94/material-ui | src/svg-icons/social/group.js | 612 | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialGroup = (props) => (
<SvgIcon {...props}>
<path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
</SvgIcon>
);
SocialGroup = pure(SocialGroup);
SocialGroup.displayName = 'SocialGroup';
SocialGroup.muiName = 'SvgIcon';
export default SocialGroup;
| mit |
ralzate/Nuevo-Aerosanidad | vendor/bundle/ruby/2.2.0/gems/fog-aws-0.7.6/lib/fog/aws/models/storage/version.rb | 1093 | module Fog
module Storage
class AWS
class Version < Fog::Model
identity :version, :aliases => 'VersionId'
attribute :key, :aliases => 'Key'
attribute :last_modified, :aliases => ['Last-Modified', 'LastModified']
attribute :latest, :aliases => 'IsLatest', :type => :boolean
attribute :content_length, :aliases => ['Content-Length', 'Size'], :type => :integer
attribute :delete_marker, :type => :boolean
def file
@file ||= if collection.file
collection.file.directory.files.get(key, 'versionId' => version)
else
collection.directory.files.get(key, 'versionId' => version)
end
end
def destroy
if collection.file
collection.service.delete_object(collection.file.directory.key, key, 'versionId' => version)
else
collection.service.delete_object(collection.directory.key, key, 'versionId' => version)
end
end
end
end
end
end
| mit |
rubengarcia0510/tienda | administrator/components/com_virtuemart/tables/rating_reviews.php | 1917 | <?php
/**
*
* Product reviews table
*
* @package VirtueMart
* @subpackage
* @author RolandD
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: ratings.php 3267 2011-05-16 22:51:49Z Milbo $
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
if(!class_exists('VmTable')) require(JPATH_VM_ADMINISTRATOR.DS.'helpers'.DS.'vmtable.php');
/**
* Product review table class
* The class is is used to manage the reviews in the shop.
*
* @package VirtueMart
* @author Max Milbers
*/
class TableRating_reviews extends VmTable {
/** @var int Primary key */
var $virtuemart_rating_review_id = 0;
/** @var int Product ID */
var $virtuemart_product_id = null;
/** @var string The user comment */
var $comment = null;
/** @var int The number of stars awared */
var $review_ok = null;
/** The rating of shoppers for the review*/
var $review_rates = null;
var $review_ratingcount = null;
var $review_rating = null;
var $review_editable = 1;
var $lastip = null;
/** @var int State of the review */
var $published = 0;
/**
* @author Max Milbers
* @param $db A database connector object
*/
function __construct(&$db) {
parent::__construct('#__virtuemart_rating_reviews', 'virtuemart_rating_review_id', $db);
$this->setPrimaryKey('virtuemart_rating_review_id');
$this->setObligatoryKeys('comment');
$this->setLoggable();
}
}
// pure php no closing tag
| gpl-2.0 |
robyrobot/LIRE | samples/liredemo/src/liredemo/ProgressMonitor.java | 1658 | package liredemo;
import javax.swing.*;
/*
* This file is part of the Caliph and Emir project: http://www.SemanticMetadata.net.
*
* Caliph & Emir 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.
*
* Caliph & Emir 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 Caliph & Emir; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Copyright statement:
* --------------------
* (c) 2002-2007 by Mathias Lux ([email protected])
* http://www.juggle.at, http://www.SemanticMetadata.net
*/
/**
* This file is part of the Caliph and Emir project: http://www.SemanticMetadata.net
*
* @author Mathias Lux, [email protected]
*/
public class ProgressMonitor {
JProgressBar pbar;
public ProgressMonitor(JProgressBar progressBar) {
pbar = progressBar;
pbar.setMinimum(0);
pbar.setMaximum(100);
}
public int getProgress() {
return pbar.getValue();
}
public void setProgress(int progress) {
progress = Math.max(0, progress);
progress = Math.min(100, progress);
pbar.setString(Math.round(progress) + "% finished");
pbar.setValue(progress);
}
}
| gpl-2.0 |
BackupGGCode/propgcc | gcc/gcc/testsuite/go.test/test/fixedbugs/bug116.go | 698 | // $G $D/$F.go && $L $F.$A && ./$A.out || echo BUG: bug116
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
func main() {
bad := false
if (-5 >> 1) != -3 {
println("-5>>1 =", -5>>1, "want -3")
bad = true
}
if (-4 >> 1) != -2 {
println("-4>>1 =", -4>>1, "want -2")
bad = true
}
if (-3 >> 1) != -2 {
println("-3>>1 =", -3>>1, "want -2")
bad = true
}
if (-2 >> 1) != -1 {
println("-2>>1 =", -2>>1, "want -1")
bad = true
}
if (-1 >> 1) != -1 {
println("-1>>1 =", -1>>1, "want -1")
bad = true
}
if bad {
println("errors")
panic("fail")
}
}
| gpl-3.0 |
rukhshanda/moodle-anmc | enrol/manual/edit_form.php | 3534 | <?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Adds new instance of enrol_manual to specified course
* or edits current instance.
*
* @package enrol_manual
* @copyright 2010 Petr Skoda {@link http://skodak.org}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once($CFG->libdir.'/formslib.php');
class enrol_manual_edit_form extends moodleform {
function definition() {
$mform = $this->_form;
list($instance, $plugin, $context) = $this->_customdata;
$mform->addElement('header', 'header', get_string('pluginname', 'enrol_manual'));
$options = array(ENROL_INSTANCE_ENABLED => get_string('yes'),
ENROL_INSTANCE_DISABLED => get_string('no'));
$mform->addElement('select', 'status', get_string('status', 'enrol_manual'), $options);
$mform->addHelpButton('status', 'status', 'enrol_manual');
$mform->setDefault('status', $plugin->get_config('status'));
if ($instance->id) {
$roles = get_default_enrol_roles($context, $instance->roleid);
} else {
$roles = get_default_enrol_roles($context, $plugin->get_config('roleid'));
}
$mform->addElement('select', 'roleid', get_string('defaultrole', 'role'), $roles);
$mform->setDefault('roleid', $plugin->get_config('roleid'));
$mform->addElement('duration', 'enrolperiod', get_string('defaultperiod', 'enrol_manual'), array('optional' => true, 'defaultunit' => 86400));
$mform->setDefault('enrolperiod', $plugin->get_config('enrolperiod'));
$mform->addHelpButton('enrolperiod', 'defaultperiod', 'enrol_manual');
$options = array(0 => get_string('no'), 1 => get_string('expirynotifyenroller', 'core_enrol'), 2 => get_string('expirynotifyall', 'core_enrol'));
$mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
$mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
$mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), array('optional' => false, 'defaultunit' => 86400));
$mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
$mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
$mform->addElement('hidden', 'courseid');
$this->add_action_buttons(true, ($instance->id ? null : get_string('addinstance', 'enrol')));
$this->set_data($instance);
}
function validation($data, $files) {
global $DB;
$errors = parent::validation($data, $files);
if ($data['expirynotify'] > 0 and $data['expirythreshold'] < 86400) {
$errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
}
return $errors;
}
}
| gpl-3.0 |
ic3fox/jawr-spring | jawr-spring-integration-test/src/main/webapp/js/inclusion/global/global_1.js | 25 | function globalFunc1(){ } | apache-2.0 |
ajperalt/jstorm | jstorm-utility/jstorm-rocket-mq/src/main/java/com/alibaba/aloha/meta/MetaConsumerFactory.java | 3550 | package com.alibaba.aloha.meta;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.log4j.Logger;
import com.alibaba.jstorm.utils.JStormUtils;
import com.alibaba.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import com.alibaba.rocketmq.common.consumer.ConsumeFromWhere;
import com.alibaba.rocketmq.common.protocol.heartbeat.MessageModel;
import com.taobao.metaq.client.MetaHelper;
import com.taobao.metaq.client.MetaPushConsumer;
public class MetaConsumerFactory {
private static final Logger LOG = Logger.getLogger(MetaConsumerFactory.class);
private static final long serialVersionUID = 4641537253577312163L;
public static Map<String, MetaPushConsumer> consumers =
new HashMap<String, MetaPushConsumer>();
public static synchronized MetaPushConsumer mkInstance(MetaClientConfig config,
MessageListenerConcurrently listener) throws Exception{
String topic = config.getTopic();
String groupId = config.getConsumerGroup();
String key = topic + "@" + groupId;
MetaPushConsumer consumer = consumers.get(key);
if (consumer != null) {
LOG.info("Consumer of " + key + " has been created, don't recreate it ");
//Attention, this place return null to info duplicated consumer
return null;
}
StringBuilder sb = new StringBuilder();
sb.append("Begin to init meta client \n");
sb.append(",configuration:").append(config);
LOG.info(sb.toString());
consumer = new MetaPushConsumer(config.getConsumerGroup());
String nameServer = config.getNameServer();
if ( nameServer != null) {
String namekey = "rocketmq.namesrv.domain";
String value = System.getProperty(namekey);
// this is for alipay
if (value == null) {
System.setProperty(namekey, nameServer);
} else if (value.equals(nameServer) == false) {
throw new Exception(
"Different nameserver address in the same worker "
+ value + ":" + nameServer);
}
}
String instanceName = groupId +"@" + JStormUtils.process_pid();
consumer.setInstanceName(instanceName);
consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_LAST_OFFSET);
consumer.subscribe(config.getTopic(), config.getSubExpress());
consumer.registerMessageListener(listener);
consumer.setPullThresholdForQueue(config.getQueueSize());
consumer.setConsumeMessageBatchMaxSize(config.getSendBatchSize());
consumer.setPullBatchSize(config.getPullBatchSize());
consumer.setPullInterval(config.getPullInterval());
consumer.setConsumeThreadMin(config.getPullThreadNum());
consumer.setConsumeThreadMax(config.getPullThreadNum());
Date date = config.getStartTimeStamp() ;
if ( date != null) {
LOG.info("Begin to reset meta offset to " + date);
try {
MetaHelper.resetOffsetByTimestamp(MessageModel.CLUSTERING,
instanceName, config.getConsumerGroup(),
config.getTopic(), date.getTime());
LOG.info("Successfully reset meta offset to " + date);
}catch(Exception e) {
LOG.error("Failed to reset meta offset to " + date);
}
}else {
LOG.info("Don't reset meta offset ");
}
consumer.start();
consumers.put(key, consumer);
LOG.info("Successfully create " + key + " consumer");
return consumer;
}
}
| apache-2.0 |
bizhao/kubernetes | pkg/kubelet/client/kubelet_client_test.go | 3233 | /*
Copyright 2014 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package client
import (
"net"
"net/http"
"net/http/httptest"
"net/http/httputil"
"net/url"
"strconv"
"testing"
restclient "k8s.io/client-go/rest"
)
func TestMakeTransportInvalid(t *testing.T) {
config := &KubeletClientConfig{
EnableHTTPS: true,
//Invalid certificate and key path
TLSClientConfig: restclient.TLSClientConfig{
CertFile: "../../client/testdata/mycertinvalid.cer",
KeyFile: "../../client/testdata/mycertinvalid.key",
CAFile: "../../client/testdata/myCA.cer",
},
}
rt, err := MakeTransport(config)
if err == nil {
t.Errorf("Expected an error")
}
if rt != nil {
t.Error("rt should be nil as we provided invalid cert file")
}
}
func TestMakeTransportValid(t *testing.T) {
config := &KubeletClientConfig{
Port: 1234,
EnableHTTPS: true,
TLSClientConfig: restclient.TLSClientConfig{
CertFile: "../../client/testdata/mycertvalid.cer",
// TLS Configuration, only applies if EnableHTTPS is true.
KeyFile: "../../client/testdata/mycertvalid.key",
// TLS Configuration, only applies if EnableHTTPS is true.
CAFile: "../../client/testdata/myCA.cer",
},
}
rt, err := MakeTransport(config)
if err != nil {
t.Errorf("Not expecting an error #%v", err)
}
if rt == nil {
t.Error("rt should not be nil")
}
}
func TestMakeInsecureTransport(t *testing.T) {
testServer := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer testServer.Close()
testURL, err := url.Parse(testServer.URL)
if err != nil {
t.Fatal(err)
}
_, portStr, err := net.SplitHostPort(testURL.Host)
if err != nil {
t.Fatal(err)
}
port, err := strconv.ParseUint(portStr, 10, 32)
if err != nil {
t.Fatal(err)
}
config := &KubeletClientConfig{
Port: uint(port),
EnableHTTPS: true,
TLSClientConfig: restclient.TLSClientConfig{
CertFile: "../../client/testdata/mycertvalid.cer",
// TLS Configuration, only applies if EnableHTTPS is true.
KeyFile: "../../client/testdata/mycertvalid.key",
// TLS Configuration, only applies if EnableHTTPS is true.
CAFile: "../../client/testdata/myCA.cer",
},
}
rt, err := MakeInsecureTransport(config)
if err != nil {
t.Errorf("Not expecting an error #%v", err)
}
if rt == nil {
t.Error("rt should not be nil")
}
req, err := http.NewRequest(http.MethodGet, testServer.URL, nil)
if err != nil {
t.Fatal(err)
}
response, err := rt.RoundTrip(req)
if err != nil {
t.Fatal(err)
}
if response.StatusCode != http.StatusOK {
dump, err := httputil.DumpResponse(response, true)
if err != nil {
t.Fatal(err)
}
t.Fatal(string(dump))
}
}
| apache-2.0 |
hackbuteer59/sakai | msgcntr/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/PrivateForumImpl.java | 2757 | /**********************************************************************************
* $URL: https://source.sakaiproject.org/svn/msgcntr/trunk/messageforums-hbm/src/java/org/sakaiproject/component/app/messageforums/dao/hibernate/PrivateForumImpl.java $
* $Id: PrivateForumImpl.java 9227 2006-05-15 15:02:42Z [email protected] $
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.component.app.messageforums.dao.hibernate;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.api.app.messageforums.PrivateForum;
public class PrivateForumImpl extends BaseForumImpl implements PrivateForum {
private static final Log LOG = LogFactory.getLog(PrivateForumImpl.class);
private String owner;
private Boolean autoForward;
private String autoForwardEmail;
private Boolean previewPaneEnabled;
// indecies for hibernate
//private int areaindex;
public Boolean getAutoForward() {
return autoForward;
}
public void setAutoForward(Boolean autoForward) {
this.autoForward = autoForward;
}
public String getAutoForwardEmail() {
return autoForwardEmail;
}
public void setAutoForwardEmail(String autoForwardEmail) {
this.autoForwardEmail = autoForwardEmail;
}
public Boolean getPreviewPaneEnabled() {
return previewPaneEnabled;
}
public void setPreviewPaneEnabled(Boolean previewPaneEnabled) {
this.previewPaneEnabled = previewPaneEnabled;
}
// public int getAreaindex() {
// try {
// return getArea().getPrivateForums().indexOf(this);
// } catch (Exception e) {
// return areaindex;
// }
// }
//
// public void setAreaindex(int areaindex) {
// this.areaindex = areaindex;
// }
public String getOwner()
{
return owner;
}
public void setOwner(String owner)
{
this.owner = owner;
}
}
| apache-2.0 |
menuka94/cdnjs | ajax/libs/parse/1.2.8/parse.js | 266631 | /*!
* Parse JavaScript SDK
* Version: 1.2.8
* Built: Fri Jul 05 2013 15:50:53
* http://parse.com
*
* Copyright 2013 Parse, Inc.
* The Parse JavaScript SDK is freely distributable under the MIT license.
*
* Includes: Underscore.js
* Copyright 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
* Released under the MIT license.
*/
(function(root) {
root.Parse = root.Parse || {};
root.Parse.VERSION = "js1.2.8";
}(this));
// Underscore.js 1.4.4
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore may be freely distributed under the MIT license.
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
// Export the Underscore object for **Node.js**, with
// backwards-compatibility for the old `require()` API. If we're in
// the browser, add `_` as a global object via a string identifier,
// for Closure Compiler "advanced" mode.
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root._ = _;
}
// Current version.
_.VERSION = '1.4.4';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = _.collect = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
var reduceError = 'Reduce of empty array with no initial value';
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError(reduceError);
return memo;
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
return _.filter(obj, function(value, index, list) {
return !iterator.call(context, value, index, list);
}, context);
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator || (iterator = _.identity);
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
// Determine if the array or object contains a given value (using `===`).
// Aliased as `include`.
_.contains = _.include = function(obj, target) {
if (obj == null) return false;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
return any(obj, function(value) {
return value === target;
});
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
return (isFunc ? method : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs, first) {
if (_.isEmpty(attrs)) return first ? null : [];
return _[first ? 'find' : 'filter'](obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
// Convenience version of a common use case of `find`: getting the first object
// containing specific `key:value` pairs.
_.findWhere = function(obj, attrs) {
return _.where(obj, attrs, true);
};
// Return the maximum element or (element-based computation).
// Can't optimize arrays of integers longer than 65,535 elements.
// See: https://bugs.webkit.org/show_bug.cgi?id=80797
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
var result = {computed : -Infinity, value: -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
var result = {computed : Infinity, value: Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Shuffle an array.
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj){ return obj[value]; };
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
index : index,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index < right.index ? -1 : 1;
}), 'value');
};
// An internal function used for aggregate "group by" operations.
var group = function(obj, value, context, behavior) {
var result = {};
var iterator = lookupIterator(value || _.identity);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
// Groups the object's values by a criterion. Pass either a string attribute
// to group by, or a function that returns the criterion.
_.groupBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = [])).push(value);
});
};
// Counts instances of an object that group by a certain criterion. Pass
// either a string attribute to count by, or a function that returns the
// criterion.
_.countBy = function(obj, value, context) {
return group(obj, value, context, function(result, key) {
if (!_.has(result, key)) result[key] = 0;
result[key]++;
});
};
// Use a comparator function to figure out the smallest index at which
// an object should be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(obj) {
if (!obj) return [];
if (_.isArray(obj)) return slice.call(obj);
if (obj.length === +obj.length) return _.map(obj, _.identity);
return _.values(obj);
};
// Return the number of elements in an object.
_.size = function(obj) {
if (obj == null) return 0;
return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head` and `take`. The **guard** check
// allows it to work with `_.map`.
_.first = _.head = _.take = function(array, n, guard) {
if (array == null) return void 0;
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the last entry of the array. Especially useful on
// the arguments object. Passing **n** will return all the values in
// the array, excluding the last N. The **guard** check allows it to work with
// `_.map`.
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
// Get the last element of an array. Passing **n** will return the last N
// values in the array. The **guard** check allows it to work with `_.map`.
_.last = function(array, n, guard) {
if (array == null) return void 0;
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
// Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
// Especially useful on the arguments object. Passing an **n** will return
// the rest N values in the array. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, _.identity);
};
// Internal implementation of a recursive `flatten` function.
var flatten = function(input, shallow, output) {
each(input, function(value) {
if (_.isArray(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
// Return a completely flattened version of an array.
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted, iterator, context) {
if (_.isFunction(isSorted)) {
context = iterator;
iterator = isSorted;
isSorted = false;
}
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(concat.apply(ArrayProto, arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays.
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and a number of other arrays.
// Only the elements present in just the first array will remain.
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value){ return !_.contains(rest, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) {
results[i] = _.pluck(args, "" + i);
}
return results;
};
// Converts lists into objects. Pass either a single array of `[key, value]`
// pairs, or two parallel arrays of the same length -- one of keys, and one of
// the corresponding values.
_.object = function(list, values) {
if (list == null) return {};
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0, l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
// available.
_.bind = function(func, context) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(context, args.concat(slice.call(arguments)));
};
};
// Partially apply a function by creating a version that has had some of its
// arguments pre-filled, without changing its dynamic `this` context.
_.partial = function(func) {
var args = slice.call(arguments, 1);
return function() {
return func.apply(this, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length === 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(null, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
var context, args, timeout, result;
var previous = 0;
var later = function() {
previous = new Date;
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
var values = [];
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
return values;
};
// Convert an object into a list of `[key, value]` pairs.
_.pairs = function(obj) {
var pairs = [];
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
return pairs;
};
// Invert the keys and values of an object. The values must be serializable.
_.invert = function(obj) {
var result = {};
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
return result;
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
// Return a copy of the object only containing the whitelisted properties.
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
// Return a copy of the object without the blacklisted properties.
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Internal recursive comparison function for `isEqual`.
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className == '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size == b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
_.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Is a given array, string, or object empty?
// An "empty" object has no enumerable own-properties.
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
// Define a fallback version of the method in browsers (ahem, IE), where
// there isn't any inspectable "Arguments" type.
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
// Optimize `isFunction` if appropriate.
if (typeof (/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
// Is a given object a finite number?
_.isFinite = function(obj) {
return isFinite(obj) && !isNaN(parseFloat(obj));
};
// Is the given value `NaN`? (NaN is the only number which does not equal itself).
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Shortcut function for checking if an object has a given property directly
// on itself (in other words, not on a prototype).
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function(n, iterator, context) {
var accum = Array(n);
for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
return accum;
};
// Return a random integer between min and max (inclusive).
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + Math.floor(Math.random() * (max - min + 1));
};
// List of HTML entities for escaping.
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
}
};
entityMap.unescape = _.invert(entityMap.escape);
// Regexes containing the keys and values listed immediately above.
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
};
// Functions for escaping and unescaping strings to/from HTML interpolation.
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
// If the value of the named property is a function then invoke it;
// otherwise, return it.
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
// Add your own custom functions to the Underscore object.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
// Add a "chain" function, which will delegate to the wrapper.
_.chain = function(obj) {
return _(obj).chain();
};
// OOP
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
// Helper function to continue chaining intermediate results.
var result = function(obj) {
return this._chain ? _(obj).chain() : obj;
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
// Start chaining a wrapped Underscore object.
chain: function() {
this._chain = true;
return this;
},
// Extracts the result from a wrapped and chained object.
value: function() {
return this._wrapped;
}
});
}).call(this);
/*global _: false, $: false, localStorage: false, process: true,
XMLHttpRequest: false, XDomainRequest: false, exports: false,
require: false */
(function(root) {
root.Parse = root.Parse || {};
/**
* Contains all Parse API classes and functions.
* @name Parse
* @namespace
*
* Contains all Parse API classes and functions.
*/
var Parse = root.Parse;
// Import Parse's local copy of underscore.
if (typeof(exports) !== "undefined" && exports._) {
// We're running in Node.js. Pull in the dependencies.
Parse._ = exports._.noConflict();
Parse.localStorage = require('localStorage');
Parse.XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
exports.Parse = Parse;
} else {
Parse._ = _.noConflict();
if (typeof(localStorage) !== "undefined") {
Parse.localStorage = localStorage;
}
if (typeof(XMLHttpRequest) !== "undefined") {
Parse.XMLHttpRequest = XMLHttpRequest;
}
}
// If jQuery or Zepto has been included, grab a reference to it.
if (typeof($) !== "undefined") {
Parse.$ = $;
}
// Helpers
// -------
// Shared empty constructor function to aid in prototype-chain creation.
var EmptyConstructor = function() {};
// TODO: fix this so that ParseObjects aren't all called "child" in debugger.
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
var inherits = function(parent, protoProps, staticProps) {
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
/** @ignore */
child = function(){ parent.apply(this, arguments); };
}
// Inherit class (static) properties from parent.
Parse._.extend(child, parent);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
EmptyConstructor.prototype = parent.prototype;
child.prototype = new EmptyConstructor();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) {
Parse._.extend(child.prototype, protoProps);
}
// Add static properties to the constructor function, if supplied.
if (staticProps) {
Parse._.extend(child, staticProps);
}
// Correctly set child's `prototype.constructor`.
child.prototype.constructor = child;
// Set a convenience property in case the parent's prototype is
// needed later.
child.__super__ = parent.prototype;
return child;
};
// Set the server for Parse to talk to.
Parse.serverURL = "https://api.parse.com";
// Check whether we are running in Node.js.
if (typeof(process) !== "undefined" &&
process.versions &&
process.versions.node) {
Parse._isNode = true;
}
/**
* Call this method first to set up your authentication tokens for Parse.
* You can get your keys from the Data Browser on parse.com.
* @param {String} applicationId Your Parse Application ID.
* @param {String} javaScriptKey Your Parse JavaScript Key.
* @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!)
*/
Parse.initialize = function(applicationId, javaScriptKey, masterKey) {
if (masterKey) {
throw "Parse.initialize() was passed a Master Key, which is only " +
"allowed from within Node.js.";
}
Parse._initialize(applicationId, javaScriptKey);
};
/**
* Call this method first to set up master authentication tokens for Parse.
* This method is for Parse's own private use.
* @param {String} applicationId Your Parse Application ID.
* @param {String} javaScriptKey Your Parse JavaScript Key.
* @param {String} masterKey Your Parse Master Key.
*/
Parse._initialize = function(applicationId, javaScriptKey, masterKey) {
Parse.applicationId = applicationId;
Parse.javaScriptKey = javaScriptKey;
Parse.masterKey = masterKey;
Parse._useMasterKey = false;
};
// If we're running in node.js, allow using the master key.
if (Parse._isNode) {
Parse.initialize = Parse._initialize;
Parse.Cloud = Parse.Cloud || {};
/**
* Switches the Parse SDK to using the Master key. The Master key grants
* priveleged access to the data in Parse and can be used to bypass ACLs and
* other restrictions that are applied to the client SDKs.
* <p><strong><em>Available in Cloud Code and Node.js only.</em></strong>
* </p>
*/
Parse.Cloud.useMasterKey = function() {
Parse._useMasterKey = true;
};
}
/**
* Returns prefix for localStorage keys used by this instance of Parse.
* @param {String} path The relative suffix to append to it.
* null or undefined is treated as the empty string.
* @return {String} The full key name.
*/
Parse._getParsePath = function(path) {
if (!Parse.applicationId) {
throw "You need to call Parse.initialize before using Parse.";
}
if (!path) {
path = "";
}
if (!Parse._.isString(path)) {
throw "Tried to get a localStorage path that wasn't a String.";
}
if (path[0] === "/") {
path = path.substring(1);
}
return "Parse/" + Parse.applicationId + "/" + path;
};
/**
* Returns the unique string for this app on this machine.
* Gets reset when localStorage is cleared.
*/
Parse._installationId = null;
Parse._getInstallationId = function() {
// See if it's cached in RAM.
if (Parse._installationId) {
return Parse._installationId;
}
// Try to get it from localStorage.
var path = Parse._getParsePath("installationId");
Parse._installationId = Parse.localStorage.getItem(path);
if (!Parse._installationId || Parse._installationId === "") {
// It wasn't in localStorage, so create a new one.
var hexOctet = function() {
return Math.floor((1+Math.random())*0x10000).toString(16).substring(1);
};
Parse._installationId = (
hexOctet() + hexOctet() + "-" +
hexOctet() + "-" +
hexOctet() + "-" +
hexOctet() + "-" +
hexOctet() + hexOctet() + hexOctet());
Parse.localStorage.setItem(path, Parse._installationId);
}
return Parse._installationId;
};
Parse._parseDate = function(iso8601) {
var regexp = new RegExp(
"^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})" + "T" +
"([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})" +
"(.([0-9]+))?" + "Z$");
var match = regexp.exec(iso8601);
if (!match) {
return null;
}
var year = match[1] || 0;
var month = (match[2] || 1) - 1;
var day = match[3] || 0;
var hour = match[4] || 0;
var minute = match[5] || 0;
var second = match[6] || 0;
var milli = match[8] || 0;
return new Date(Date.UTC(year, month, day, hour, minute, second, milli));
};
Parse._ajaxIE8 = function(method, url, data) {
var promise = new Parse.Promise();
var xdr = new XDomainRequest();
xdr.onload = function() {
var response;
try {
response = JSON.parse(xdr.responseText);
} catch (e) {
promise.reject(e);
}
if (response) {
promise.resolve(response);
}
};
xdr.onerror = xdr.ontimeout = function() {
promise.reject(xdr);
};
xdr.onprogress = function() {};
xdr.open(method, url);
xdr.send(data);
return promise;
};
// TODO(klimt): Get rid of success/error usage in website.
Parse._ajax = function(method, url, data, success, error) {
var options = {
success: success,
error: error
};
if (typeof(XDomainRequest) !== "undefined") {
return Parse._ajaxIE8(method, url, data)._thenRunCallbacks(options);
}
var promise = new Parse.Promise();
var handled = false;
var xhr = new Parse.XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
if (handled) {
return;
}
handled = true;
if (xhr.status >= 200 && xhr.status < 300) {
var response;
try {
response = JSON.parse(xhr.responseText);
} catch (e) {
promise.reject(e);
}
if (response) {
promise.resolve(response, xhr.status, xhr);
}
} else {
promise.reject(xhr);
}
}
};
xhr.open(method, url, true);
xhr.setRequestHeader("Content-Type", "text/plain"); // avoid pre-flight.
if (Parse._isNode) {
// Add a special user agent just for request from node.js.
xhr.setRequestHeader("User-Agent",
"Parse/" + Parse.VERSION +
" (NodeJS " + process.versions.node + ")");
}
xhr.send(data);
return promise._thenRunCallbacks(options);
};
// A self-propagating extend function.
Parse._extend = function(protoProps, classProps) {
var child = inherits(this, protoProps, classProps);
child.extend = this.extend;
return child;
};
/**
* route is classes, users, login, etc.
* objectId is null if there is no associated objectId.
* method is the http method for the REST API.
* dataObject is the payload as an object, or null if there is none.
* @ignore
*/
Parse._request = function(route, className, objectId, method, dataObject) {
if (!Parse.applicationId) {
throw "You must specify your applicationId using Parse.initialize";
}
if (!Parse.javaScriptKey && !Parse.masterKey) {
throw "You must specify a key using Parse.initialize";
}
// TODO: We can remove this check later, but it's useful for development.
if (route !== "batch" &&
route !== "classes" &&
route !== "files" &&
route !== "functions" &&
route !== "login" &&
route !== "push" &&
route !== "requestPasswordReset" &&
route !== "users") {
throw "Bad route: '" + route + "'.";
}
var url = Parse.serverURL;
if (url.charAt(url.length - 1) !== "/") {
url += "/";
}
url += "1/" + route;
if (className) {
url += "/" + className;
}
if (objectId) {
url += "/" + objectId;
}
dataObject = Parse._.clone(dataObject || {});
if (method !== "POST") {
dataObject._method = method;
method = "POST";
}
dataObject._ApplicationId = Parse.applicationId;
if (!Parse._useMasterKey) {
dataObject._JavaScriptKey = Parse.javaScriptKey;
} else {
dataObject._MasterKey = Parse.masterKey;
}
dataObject._ClientVersion = Parse.VERSION;
dataObject._InstallationId = Parse._getInstallationId();
// Pass the session token on every request.
var currentUser = Parse.User.current();
if (currentUser && currentUser._sessionToken) {
dataObject._SessionToken = currentUser._sessionToken;
}
var data = JSON.stringify(dataObject);
return Parse._ajax(method, url, data).then(null, function(response) {
// Transform the error into an instance of Parse.Error by trying to parse
// the error string as JSON.
var error;
if (response && response.responseText) {
try {
var errorJSON = JSON.parse(response.responseText);
if (errorJSON) {
error = new Parse.Error(errorJSON.code, errorJSON.error);
}
} catch (e) {
// If we fail to parse the error text, that's okay.
}
}
error = error || new Parse.Error(-1, response.responseText);
// By explicitly returning a rejected Promise, this will work with
// either jQuery or Promises/A semantics.
return Parse.Promise.error(error);
});
};
// Helper function to get a value from a Backbone object as a property
// or as a function.
Parse._getValue = function(object, prop) {
if (!(object && object[prop])) {
return null;
}
return Parse._.isFunction(object[prop]) ? object[prop]() : object[prop];
};
/**
* Converts a value in a Parse Object into the appropriate representation.
* This is the JS equivalent of Java's Parse.maybeReferenceAndEncode(Object)
* if seenObjects is falsey. Otherwise any Parse.Objects not in
* seenObjects will be fully embedded rather than encoded
* as a pointer. This array will be used to prevent going into an infinite
* loop because we have circular references. If seenObjects
* is set, then none of the Parse Objects that are serialized can be dirty.
*/
Parse._encode = function(value, seenObjects, disallowObjects) {
var _ = Parse._;
if (value instanceof Parse.Object) {
if (disallowObjects) {
throw "Parse.Objects not allowed here";
}
if (!seenObjects || _.include(seenObjects, value) || !value._hasData) {
return value._toPointer();
}
if (!value.dirty()) {
seenObjects = seenObjects.concat(value);
return Parse._encode(value._toFullJSON(seenObjects),
seenObjects,
disallowObjects);
}
throw "Tried to save an object with a pointer to a new, unsaved object.";
}
if (value instanceof Parse.ACL) {
return value.toJSON();
}
if (_.isDate(value)) {
return { "__type": "Date", "iso": value.toJSON() };
}
if (value instanceof Parse.GeoPoint) {
return value.toJSON();
}
if (_.isArray(value)) {
return _.map(value, function(x) {
return Parse._encode(x, seenObjects, disallowObjects);
});
}
if (_.isRegExp(value)) {
return value.source;
}
if (value instanceof Parse.Relation) {
return value.toJSON();
}
if (value instanceof Parse.Op) {
return value.toJSON();
}
if (value instanceof Parse.File) {
if (!value.url()) {
throw "Tried to save an object containing an unsaved file.";
}
return {
__type: "File",
name: value.name(),
url: value.url()
};
}
if (_.isObject(value)) {
var output = {};
Parse._objectEach(value, function(v, k) {
output[k] = Parse._encode(v, seenObjects, disallowObjects);
});
return output;
}
return value;
};
/**
* The inverse function of Parse._encode.
* TODO: make decode not mutate value.
*/
Parse._decode = function(key, value) {
var _ = Parse._;
if (!_.isObject(value)) {
return value;
}
if (_.isArray(value)) {
Parse._arrayEach(value, function(v, k) {
value[k] = Parse._decode(k, v);
});
return value;
}
if (value instanceof Parse.Object) {
return value;
}
if (value instanceof Parse.File) {
return value;
}
if (value instanceof Parse.Op) {
return value;
}
if (value.__op) {
return Parse.Op._decode(value);
}
if (value.__type === "Pointer") {
var pointer = Parse.Object._create(value.className);
pointer._finishFetch({ objectId: value.objectId }, false);
return pointer;
}
if (value.__type === "Object") {
// It's an Object included in a query result.
var className = value.className;
delete value.__type;
delete value.className;
var object = Parse.Object._create(className);
object._finishFetch(value, true);
return object;
}
if (value.__type === "Date") {
return Parse._parseDate(value.iso);
}
if (value.__type === "GeoPoint") {
return new Parse.GeoPoint({
latitude: value.latitude,
longitude: value.longitude
});
}
if (key === "ACL") {
if (value instanceof Parse.ACL) {
return value;
}
return new Parse.ACL(value);
}
if (value.__type === "Relation") {
var relation = new Parse.Relation(null, key);
relation.targetClassName = value.className;
return relation;
}
if (value.__type === "File") {
var file = new Parse.File(value.name);
file._url = value.url;
return file;
}
Parse._objectEach(value, function(v, k) {
value[k] = Parse._decode(k, v);
});
return value;
};
Parse._arrayEach = Parse._.each;
/**
* Does a deep traversal of every item in object, calling func on every one.
* @param {Object} object The object or array to traverse deeply.
* @param {Function} func The function to call for every item. It will
* be passed the item as an argument. If it returns a truthy value, that
* value will replace the item in its parent container.
* @returns {} the result of calling func on the top-level object itself.
*/
Parse._traverse = function(object, func, seen) {
if (object instanceof Parse.Object) {
seen = seen || [];
if (Parse._.indexOf(seen, object) >= 0) {
// We've already visited this object in this call.
return;
}
seen.push(object);
Parse._traverse(object.attributes, func, seen);
return func(object);
}
if (object instanceof Parse.Relation || object instanceof Parse.File) {
// Nothing needs to be done, but we don't want to recurse into the
// object's parent infinitely, so we catch this case.
return func(object);
}
if (Parse._.isArray(object)) {
Parse._.each(object, function(child, index) {
var newChild = Parse._traverse(child, func, seen);
if (newChild) {
object[index] = newChild;
}
});
return func(object);
}
if (Parse._.isObject(object)) {
Parse._each(object, function(child, key) {
var newChild = Parse._traverse(child, func, seen);
if (newChild) {
object[key] = newChild;
}
});
return func(object);
}
return func(object);
};
/**
* This is like _.each, except:
* * it doesn't work for so-called array-like objects,
* * it does work for dictionaries with a "length" attribute.
*/
Parse._objectEach = Parse._each = function(obj, callback) {
var _ = Parse._;
if (_.isObject(obj)) {
_.each(_.keys(obj), function(key) {
callback(obj[key], key);
});
} else {
_.each(obj, callback);
}
};
// Helper function to check null or undefined.
Parse._isNullOrUndefined = function(x) {
return Parse._.isNull(x) || Parse._.isUndefined(x);
};
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Constructs a new Parse.Error object with the given code and message.
* @param {Number} code An error code constant from <code>Parse.Error</code>.
* @param {String} message A detailed description of the error.
* @class
*
* <p>Class used for all objects passed to error callbacks.</p>
*/
Parse.Error = function(code, message) {
this.code = code;
this.message = message;
};
_.extend(Parse.Error, /** @lends Parse.Error */ {
/**
* Error code indicating some error other than those enumerated here.
* @constant
*/
OTHER_CAUSE: -1,
/**
* Error code indicating that something has gone wrong with the server.
* If you get this error code, it is Parse's fault. Contact us at
* https://parse.com/help
* @constant
*/
INTERNAL_SERVER_ERROR: 1,
/**
* Error code indicating the connection to the Parse servers failed.
* @constant
*/
CONNECTION_FAILED: 100,
/**
* Error code indicating the specified object doesn't exist.
* @constant
*/
OBJECT_NOT_FOUND: 101,
/**
* Error code indicating you tried to query with a datatype that doesn't
* support it, like exact matching an array or object.
* @constant
*/
INVALID_QUERY: 102,
/**
* Error code indicating a missing or invalid classname. Classnames are
* case-sensitive. They must start with a letter, and a-zA-Z0-9_ are the
* only valid characters.
* @constant
*/
INVALID_CLASS_NAME: 103,
/**
* Error code indicating an unspecified object id.
* @constant
*/
MISSING_OBJECT_ID: 104,
/**
* Error code indicating an invalid key name. Keys are case-sensitive. They
* must start with a letter, and a-zA-Z0-9_ are the only valid characters.
* @constant
*/
INVALID_KEY_NAME: 105,
/**
* Error code indicating a malformed pointer. You should not see this unless
* you have been mucking about changing internal Parse code.
* @constant
*/
INVALID_POINTER: 106,
/**
* Error code indicating that badly formed JSON was received upstream. This
* either indicates you have done something unusual with modifying how
* things encode to JSON, or the network is failing badly.
* @constant
*/
INVALID_JSON: 107,
/**
* Error code indicating that the feature you tried to access is only
* available internally for testing purposes.
* @constant
*/
COMMAND_UNAVAILABLE: 108,
/**
* You must call Parse.initialize before using the Parse library.
* @constant
*/
NOT_INITIALIZED: 109,
/**
* Error code indicating that a field was set to an inconsistent type.
* @constant
*/
INCORRECT_TYPE: 111,
/**
* Error code indicating an invalid channel name. A channel name is either
* an empty string (the broadcast channel) or contains only a-zA-Z0-9_
* characters and starts with a letter.
* @constant
*/
INVALID_CHANNEL_NAME: 112,
/**
* Error code indicating that push is misconfigured.
* @constant
*/
PUSH_MISCONFIGURED: 115,
/**
* Error code indicating that the object is too large.
* @constant
*/
OBJECT_TOO_LARGE: 116,
/**
* Error code indicating that the operation isn't allowed for clients.
* @constant
*/
OPERATION_FORBIDDEN: 119,
/**
* Error code indicating the result was not found in the cache.
* @constant
*/
CACHE_MISS: 120,
/**
* Error code indicating that an invalid key was used in a nested
* JSONObject.
* @constant
*/
INVALID_NESTED_KEY: 121,
/**
* Error code indicating that an invalid filename was used for ParseFile.
* A valid file name contains only a-zA-Z0-9_. characters and is between 1
* and 128 characters.
* @constant
*/
INVALID_FILE_NAME: 122,
/**
* Error code indicating an invalid ACL was provided.
* @constant
*/
INVALID_ACL: 123,
/**
* Error code indicating that the request timed out on the server. Typically
* this indicates that the request is too expensive to run.
* @constant
*/
TIMEOUT: 124,
/**
* Error code indicating that the email address was invalid.
* @constant
*/
INVALID_EMAIL_ADDRESS: 125,
/**
* Error code indicating a missing content type.
* @constant
*/
MISSING_CONTENT_TYPE: 126,
/**
* Error code indicating a missing content length.
* @constant
*/
MISSING_CONTENT_LENGTH: 127,
/**
* Error code indicating an invalid content length.
* @constant
*/
INVALID_CONTENT_LENGTH: 128,
/**
* Error code indicating a file that was too large.
* @constant
*/
FILE_TOO_LARGE: 129,
/**
* Error code indicating an error saving a file.
* @constant
*/
FILE_SAVE_ERROR: 130,
/**
* Error code indicating an error deleting a file.
* @constant
*/
FILE_DELETE_ERROR: 153,
/**
* Error code indicating that a unique field was given a value that is
* already taken.
* @constant
*/
DUPLICATE_VALUE: 137,
/**
* Error code indicating that a role's name is invalid.
* @constant
*/
INVALID_ROLE_NAME: 139,
/**
* Error code indicating that an application quota was exceeded. Upgrade to
* resolve.
* @constant
*/
EXCEEDED_QUOTA: 140,
/**
* Error code indicating that a Cloud Code script failed.
* @constant
*/
SCRIPT_FAILED: 141,
/**
* Error code indicating that a Cloud Code validation failed.
* @constant
*/
VALIDATION_ERROR: 142,
/**
* Error code indicating that invalid image data was provided.
* @constant
*/
INVALID_IMAGE_DATA: 150,
/**
* Error code indicating an unsaved file.
* @constant
*/
UNSAVED_FILE_ERROR: 151,
/**
* Error code indicating an invalid push time.
*/
INVALID_PUSH_TIME_ERROR: 152,
/**
* Error code indicating that the username is missing or empty.
* @constant
*/
USERNAME_MISSING: 200,
/**
* Error code indicating that the password is missing or empty.
* @constant
*/
PASSWORD_MISSING: 201,
/**
* Error code indicating that the username has already been taken.
* @constant
*/
USERNAME_TAKEN: 202,
/**
* Error code indicating that the email has already been taken.
* @constant
*/
EMAIL_TAKEN: 203,
/**
* Error code indicating that the email is missing, but must be specified.
* @constant
*/
EMAIL_MISSING: 204,
/**
* Error code indicating that a user with the specified email was not found.
* @constant
*/
EMAIL_NOT_FOUND: 205,
/**
* Error code indicating that a user object without a valid session could
* not be altered.
* @constant
*/
SESSION_MISSING: 206,
/**
* Error code indicating that a user can only be created through signup.
* @constant
*/
MUST_CREATE_USER_THROUGH_SIGNUP: 207,
/**
* Error code indicating that an an account being linked is already linked
* to another user.
* @constant
*/
ACCOUNT_ALREADY_LINKED: 208,
/**
* Error code indicating that a user cannot be linked to an account because
* that account's id could not be found.
* @constant
*/
LINKED_ID_MISSING: 250,
/**
* Error code indicating that a user with a linked (e.g. Facebook) account
* has an invalid session.
* @constant
*/
INVALID_LINKED_SESSION: 251,
/**
* Error code indicating that a service being linked (e.g. Facebook or
* Twitter) is unsupported.
* @constant
*/
UNSUPPORTED_SERVICE: 252
});
}(this));
/*global _: false */
(function() {
var root = this;
var Parse = (root.Parse || (root.Parse = {}));
var eventSplitter = /\s+/;
var slice = Array.prototype.slice;
/**
* @class
*
* <p>Parse.Events is a fork of Backbone's Events module, provided for your
* convenience.</p>
*
* <p>A module that can be mixed in to any object in order to provide
* it with custom events. You may bind callback functions to an event
* with `on`, or remove these functions with `off`.
* Triggering an event fires all callbacks in the order that `on` was
* called.
*
* <pre>
* var object = {};
* _.extend(object, Parse.Events);
* object.on('expand', function(){ alert('expanded'); });
* object.trigger('expand');</pre></p>
*
* <p>For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Events">Backbone
* documentation</a>.</p>
*/
Parse.Events = {
/**
* Bind one or more space separated events, `events`, to a `callback`
* function. Passing `"all"` will bind the callback to all events fired.
*/
on: function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) {
return this;
}
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
event = events.shift();
while (event) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = {tail: tail, next: list ? list.next : node};
event = events.shift();
}
return this;
},
/**
* Remove one or many callbacks. If `context` is null, removes all callbacks
* with that function. If `callback` is null, removes all callbacks for the
* event. If `events` is null, removes all bound callbacks for all events.
*/
off: function(events, callback, context) {
var event, calls, node, tail, cb, ctx;
// No events, or removing *all* events.
if (!(calls = this._callbacks)) {
return;
}
if (!(events || callback || context)) {
delete this._callbacks;
return this;
}
// Loop through the listed events and contexts, splicing them out of the
// linked list of callbacks if appropriate.
events = events ? events.split(eventSplitter) : _.keys(calls);
event = events.shift();
while (event) {
node = calls[event];
delete calls[event];
if (!node || !(callback || context)) {
continue;
}
// Create a new list, omitting the indicated callbacks.
tail = node.tail;
node = node.next;
while (node !== tail) {
cb = node.callback;
ctx = node.context;
if ((callback && cb !== callback) || (context && ctx !== context)) {
this.on(event, cb, ctx);
}
node = node.next;
}
event = events.shift();
}
return this;
},
/**
* Trigger one or many events, firing all bound callbacks. Callbacks are
* passed the same arguments as `trigger` is, apart from the event name
* (unless you're listening on `"all"`, which will cause your callback to
* receive the true name of the event as the first argument).
*/
trigger: function(events) {
var event, node, calls, tail, args, all, rest;
if (!(calls = this._callbacks)) {
return this;
}
all = calls.all;
events = events.split(eventSplitter);
rest = slice.call(arguments, 1);
// For each event, walk through the linked list of callbacks twice,
// first to trigger the event, then to trigger any `"all"` callbacks.
event = events.shift();
while (event) {
node = calls[event];
if (node) {
tail = node.tail;
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, rest);
}
}
node = all;
if (node) {
tail = node.tail;
args = [event].concat(rest);
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, args);
}
}
event = events.shift();
}
return this;
}
};
/**
* @function
*/
Parse.Events.bind = Parse.Events.on;
/**
* @function
*/
Parse.Events.unbind = Parse.Events.off;
}.call(this));
/*global navigator: false */
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Creates a new GeoPoint with any of the following forms:<br>
* <pre>
* new GeoPoint(otherGeoPoint)
* new GeoPoint(30, 30)
* new GeoPoint([30, 30])
* new GeoPoint({latitude: 30, longitude: 30})
* new GeoPoint() // defaults to (0, 0)
* </pre>
* @class
*
* <p>Represents a latitude / longitude point that may be associated
* with a key in a ParseObject or used as a reference point for geo queries.
* This allows proximity-based queries on the key.</p>
*
* <p>Only one key in a class may contain a GeoPoint.</p>
*
* <p>Example:<pre>
* var point = new Parse.GeoPoint(30.0, -20.0);
* var object = new Parse.Object("PlaceObject");
* object.set("location", point);
* object.save();</pre></p>
*/
Parse.GeoPoint = function(arg1, arg2) {
if (_.isArray(arg1)) {
Parse.GeoPoint._validate(arg1[0], arg1[1]);
this.latitude = arg1[0];
this.longitude = arg1[1];
} else if (_.isObject(arg1)) {
Parse.GeoPoint._validate(arg1.latitude, arg1.longitude);
this.latitude = arg1.latitude;
this.longitude = arg1.longitude;
} else if (_.isNumber(arg1) && _.isNumber(arg2)) {
Parse.GeoPoint._validate(arg1, arg2);
this.latitude = arg1;
this.longitude = arg2;
} else {
this.latitude = 0;
this.longitude = 0;
}
// Add properties so that anyone using Webkit or Mozilla will get an error
// if they try to set values that are out of bounds.
var self = this;
if (this.__defineGetter__ && this.__defineSetter__) {
// Use _latitude and _longitude to actually store the values, and add
// getters and setters for latitude and longitude.
this._latitude = this.latitude;
this._longitude = this.longitude;
this.__defineGetter__("latitude", function() {
return self._latitude;
});
this.__defineGetter__("longitude", function() {
return self._longitude;
});
this.__defineSetter__("latitude", function(val) {
Parse.GeoPoint._validate(val, self.longitude);
self._latitude = val;
});
this.__defineSetter__("longitude", function(val) {
Parse.GeoPoint._validate(self.latitude, val);
self._longitude = val;
});
}
};
/**
* @lends Parse.GeoPoint.prototype
* @property {float} latitude North-south portion of the coordinate, in range
* [-90, 90]. Throws an exception if set out of range in a modern browser.
* @property {float} longitude East-west portion of the coordinate, in range
* [-180, 180]. Throws if set out of range in a modern browser.
*/
/**
* Throws an exception if the given lat-long is out of bounds.
*/
Parse.GeoPoint._validate = function(latitude, longitude) {
if (latitude < -90.0) {
throw "Parse.GeoPoint latitude " + latitude + " < -90.0.";
}
if (latitude > 90.0) {
throw "Parse.GeoPoint latitude " + latitude + " > 90.0.";
}
if (longitude < -180.0) {
throw "Parse.GeoPoint longitude " + longitude + " < -180.0.";
}
if (longitude > 180.0) {
throw "Parse.GeoPoint longitude " + longitude + " > 180.0.";
}
};
/**
* Creates a GeoPoint with the user's current location, if available.
* Calls options.success with a new GeoPoint instance or calls options.error.
* @param {Object} options An object with success and error callbacks.
*/
Parse.GeoPoint.current = function(options) {
var promise = new Parse.Promise();
navigator.geolocation.getCurrentPosition(function(location) {
promise.resolve(new Parse.GeoPoint({
latitude: location.coords.latitude,
longitude: location.coords.longitude
}));
}, function(error) {
promise.reject(error);
});
return promise._thenRunCallbacks(options);
};
Parse.GeoPoint.prototype = {
/**
* Returns a JSON representation of the GeoPoint, suitable for Parse.
* @return {Object}
*/
toJSON: function() {
Parse.GeoPoint._validate(this.latitude, this.longitude);
return {
"__type": "GeoPoint",
latitude: this.latitude,
longitude: this.longitude
};
},
/**
* Returns the distance from this GeoPoint to another in radians.
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @return {Number}
*/
radiansTo: function(point) {
var d2r = Math.PI / 180.0;
var lat1rad = this.latitude * d2r;
var long1rad = this.longitude * d2r;
var lat2rad = point.latitude * d2r;
var long2rad = point.longitude * d2r;
var deltaLat = lat1rad - lat2rad;
var deltaLong = long1rad - long2rad;
var sinDeltaLatDiv2 = Math.sin(deltaLat / 2);
var sinDeltaLongDiv2 = Math.sin(deltaLong / 2);
// Square of half the straight line chord distance between both points.
var a = ((sinDeltaLatDiv2 * sinDeltaLatDiv2) +
(Math.cos(lat1rad) * Math.cos(lat2rad) *
sinDeltaLongDiv2 * sinDeltaLongDiv2));
a = Math.min(1.0, a);
return 2 * Math.asin(Math.sqrt(a));
},
/**
* Returns the distance from this GeoPoint to another in kilometers.
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @return {Number}
*/
kilometersTo: function(point) {
return this.radiansTo(point) * 6371.0;
},
/**
* Returns the distance from this GeoPoint to another in miles.
* @param {Parse.GeoPoint} point the other Parse.GeoPoint.
* @return {Number}
*/
milesTo: function(point) {
return this.radiansTo(point) * 3958.8;
}
};
}(this));
/*global navigator: false */
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
var PUBLIC_KEY = "*";
/**
* Creates a new ACL.
* If no argument is given, the ACL has no permissions for anyone.
* If the argument is a Parse.User, the ACL will have read and write
* permission for only that user.
* If the argument is any other JSON object, that object will be interpretted
* as a serialized ACL created with toJSON().
* @see Parse.Object#setACL
* @class
*
* <p>An ACL, or Access Control List can be added to any
* <code>Parse.Object</code> to restrict access to only a subset of users
* of your application.</p>
*/
Parse.ACL = function(arg1) {
var self = this;
self.permissionsById = {};
if (_.isObject(arg1)) {
if (arg1 instanceof Parse.User) {
self.setReadAccess(arg1, true);
self.setWriteAccess(arg1, true);
} else {
if (_.isFunction(arg1)) {
throw "Parse.ACL() called with a function. Did you forget ()?";
}
Parse._objectEach(arg1, function(accessList, userId) {
if (!_.isString(userId)) {
throw "Tried to create an ACL with an invalid userId.";
}
self.permissionsById[userId] = {};
Parse._objectEach(accessList, function(allowed, permission) {
if (permission !== "read" && permission !== "write") {
throw "Tried to create an ACL with an invalid permission type.";
}
if (!_.isBoolean(allowed)) {
throw "Tried to create an ACL with an invalid permission value.";
}
self.permissionsById[userId][permission] = allowed;
});
});
}
}
};
/**
* Returns a JSON-encoded version of the ACL.
* @return {Object}
*/
Parse.ACL.prototype.toJSON = function() {
return _.clone(this.permissionsById);
};
Parse.ACL.prototype._setAccess = function(accessType, userId, allowed) {
if (userId instanceof Parse.User) {
userId = userId.id;
} else if (userId instanceof Parse.Role) {
userId = "role:" + userId.getName();
}
if (!_.isString(userId)) {
throw "userId must be a string.";
}
if (!_.isBoolean(allowed)) {
throw "allowed must be either true or false.";
}
var permissions = this.permissionsById[userId];
if (!permissions) {
if (!allowed) {
// The user already doesn't have this permission, so no action needed.
return;
} else {
permissions = {};
this.permissionsById[userId] = permissions;
}
}
if (allowed) {
this.permissionsById[userId][accessType] = true;
} else {
delete permissions[accessType];
if (_.isEmpty(permissions)) {
delete permissions[userId];
}
}
};
Parse.ACL.prototype._getAccess = function(accessType, userId) {
if (userId instanceof Parse.User) {
userId = userId.id;
} else if (userId instanceof Parse.Role) {
userId = "role:" + userId.getName();
}
var permissions = this.permissionsById[userId];
if (!permissions) {
return false;
}
return permissions[accessType] ? true : false;
};
/**
* Set whether the given user is allowed to read this object.
* @param userId An instance of Parse.User or its objectId.
* @param {Boolean} allowed Whether that user should have read access.
*/
Parse.ACL.prototype.setReadAccess = function(userId, allowed) {
this._setAccess("read", userId, allowed);
};
/**
* Get whether the given user id is *explicitly* allowed to read this object.
* Even if this returns false, the user may still be able to access it if
* getPublicReadAccess returns true or a role that the user belongs to has
* write access.
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @return {Boolean}
*/
Parse.ACL.prototype.getReadAccess = function(userId) {
return this._getAccess("read", userId);
};
/**
* Set whether the given user id is allowed to write this object.
* @param userId An instance of Parse.User or its objectId, or a Parse.Role..
* @param {Boolean} allowed Whether that user should have write access.
*/
Parse.ACL.prototype.setWriteAccess = function(userId, allowed) {
this._setAccess("write", userId, allowed);
};
/**
* Get whether the given user id is *explicitly* allowed to write this object.
* Even if this returns false, the user may still be able to write it if
* getPublicWriteAccess returns true or a role that the user belongs to has
* write access.
* @param userId An instance of Parse.User or its objectId, or a Parse.Role.
* @return {Boolean}
*/
Parse.ACL.prototype.getWriteAccess = function(userId) {
return this._getAccess("write", userId);
};
/**
* Set whether the public is allowed to read this object.
* @param {Boolean} allowed
*/
Parse.ACL.prototype.setPublicReadAccess = function(allowed) {
this.setReadAccess(PUBLIC_KEY, allowed);
};
/**
* Get whether the public is allowed to read this object.
* @return {Boolean}
*/
Parse.ACL.prototype.getPublicReadAccess = function() {
return this.getReadAccess(PUBLIC_KEY);
};
/**
* Set whether the public is allowed to write this object.
* @param {Boolean} allowed
*/
Parse.ACL.prototype.setPublicWriteAccess = function(allowed) {
this.setWriteAccess(PUBLIC_KEY, allowed);
};
/**
* Get whether the public is allowed to write this object.
* @return {Boolean}
*/
Parse.ACL.prototype.getPublicWriteAccess = function() {
return this.getWriteAccess(PUBLIC_KEY);
};
/**
* Get whether users belonging to the given role are allowed
* to read this object. Even if this returns false, the role may
* still be able to write it if a parent role has read access.
*
* @param role The name of the role, or a Parse.Role object.
* @return {Boolean} true if the role has read access. false otherwise.
* @throws {String} If role is neither a Parse.Role nor a String.
*/
Parse.ACL.prototype.getRoleReadAccess = function(role) {
if (role instanceof Parse.Role) {
// Normalize to the String name
role = role.getName();
}
if (_.isString(role)) {
return this.getReadAccess("role:" + role);
}
throw "role must be a Parse.Role or a String";
};
/**
* Get whether users belonging to the given role are allowed
* to write this object. Even if this returns false, the role may
* still be able to write it if a parent role has write access.
*
* @param role The name of the role, or a Parse.Role object.
* @return {Boolean} true if the role has write access. false otherwise.
* @throws {String} If role is neither a Parse.Role nor a String.
*/
Parse.ACL.prototype.getRoleWriteAccess = function(role) {
if (role instanceof Parse.Role) {
// Normalize to the String name
role = role.getName();
}
if (_.isString(role)) {
return this.getWriteAccess("role:" + role);
}
throw "role must be a Parse.Role or a String";
};
/**
* Set whether users belonging to the given role are allowed
* to read this object.
*
* @param role The name of the role, or a Parse.Role object.
* @param {Boolean} allowed Whether the given role can read this object.
* @throws {String} If role is neither a Parse.Role nor a String.
*/
Parse.ACL.prototype.setRoleReadAccess = function(role, allowed) {
if (role instanceof Parse.Role) {
// Normalize to the String name
role = role.getName();
}
if (_.isString(role)) {
this.setReadAccess("role:" + role, allowed);
return;
}
throw "role must be a Parse.Role or a String";
};
/**
* Set whether users belonging to the given role are allowed
* to write this object.
*
* @param role The name of the role, or a Parse.Role object.
* @param {Boolean} allowed Whether the given role can write this object.
* @throws {String} If role is neither a Parse.Role nor a String.
*/
Parse.ACL.prototype.setRoleWriteAccess = function(role, allowed) {
if (role instanceof Parse.Role) {
// Normalize to the String name
role = role.getName();
}
if (_.isString(role)) {
this.setWriteAccess("role:" + role, allowed);
return;
}
throw "role must be a Parse.Role or a String";
};
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* @class
* A Parse.Op is an atomic operation that can be applied to a field in a
* Parse.Object. For example, calling <code>object.set("foo", "bar")</code>
* is an example of a Parse.Op.Set. Calling <code>object.unset("foo")</code>
* is a Parse.Op.Unset. These operations are stored in a Parse.Object and
* sent to the server as part of <code>object.save()</code> operations.
* Instances of Parse.Op should be immutable.
*
* You should not create subclasses of Parse.Op or instantiate Parse.Op
* directly.
*/
Parse.Op = function() {
this._initialize.apply(this, arguments);
};
Parse.Op.prototype = {
_initialize: function() {}
};
_.extend(Parse.Op, {
/**
* To create a new Op, call Parse.Op._extend();
*/
_extend: Parse._extend,
// A map of __op string to decoder function.
_opDecoderMap: {},
/**
* Registers a function to convert a json object with an __op field into an
* instance of a subclass of Parse.Op.
*/
_registerDecoder: function(opName, decoder) {
Parse.Op._opDecoderMap[opName] = decoder;
},
/**
* Converts a json object into an instance of a subclass of Parse.Op.
*/
_decode: function(json) {
var decoder = Parse.Op._opDecoderMap[json.__op];
if (decoder) {
return decoder(json);
} else {
return undefined;
}
}
});
/*
* Add a handler for Batch ops.
*/
Parse.Op._registerDecoder("Batch", function(json) {
var op = null;
Parse._arrayEach(json.ops, function(nextOp) {
nextOp = Parse.Op._decode(nextOp);
op = nextOp._mergeWithPrevious(op);
});
return op;
});
/**
* @class
* A Set operation indicates that either the field was changed using
* Parse.Object.set, or it is a mutable container that was detected as being
* changed.
*/
Parse.Op.Set = Parse.Op._extend(/** @lends Parse.Op.Set.prototype */ {
_initialize: function(value) {
this._value = value;
},
/**
* Returns the new value of this field after the set.
*/
value: function() {
return this._value;
},
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
return Parse._encode(this.value());
},
_mergeWithPrevious: function(previous) {
return this;
},
_estimate: function(oldValue) {
return this.value();
}
});
/**
* A sentinel value that is returned by Parse.Op.Unset._estimate to
* indicate the field should be deleted. Basically, if you find _UNSET as a
* value in your object, you should remove that key.
*/
Parse.Op._UNSET = {};
/**
* @class
* An Unset operation indicates that this field has been deleted from the
* object.
*/
Parse.Op.Unset = Parse.Op._extend(/** @lends Parse.Op.Unset.prototype */ {
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
return { __op: "Delete" };
},
_mergeWithPrevious: function(previous) {
return this;
},
_estimate: function(oldValue) {
return Parse.Op._UNSET;
}
});
Parse.Op._registerDecoder("Delete", function(json) {
return new Parse.Op.Unset();
});
/**
* @class
* An Increment is an atomic operation where the numeric value for the field
* will be increased by a given amount.
*/
Parse.Op.Increment = Parse.Op._extend(
/** @lends Parse.Op.Increment.prototype */ {
_initialize: function(amount) {
this._amount = amount;
},
/**
* Returns the amount to increment by.
* @return {Number} the amount to increment by.
*/
amount: function() {
return this._amount;
},
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
return { __op: "Increment", amount: this._amount };
},
_mergeWithPrevious: function(previous) {
if (!previous) {
return this;
} else if (previous instanceof Parse.Op.Unset) {
return new Parse.Op.Set(this.amount());
} else if (previous instanceof Parse.Op.Set) {
return new Parse.Op.Set(previous.value() + this.amount());
} else if (previous instanceof Parse.Op.Increment) {
return new Parse.Op.Increment(this.amount() + previous.amount());
} else {
throw "Op is invalid after previous op.";
}
},
_estimate: function(oldValue) {
if (!oldValue) {
return this.amount();
}
return oldValue + this.amount();
}
});
Parse.Op._registerDecoder("Increment", function(json) {
return new Parse.Op.Increment(json.amount);
});
/**
* @class
* Add is an atomic operation where the given objects will be appended to the
* array that is stored in this field.
*/
Parse.Op.Add = Parse.Op._extend(/** @lends Parse.Op.Add.prototype */ {
_initialize: function(objects) {
this._objects = objects;
},
/**
* Returns the objects to be added to the array.
* @return {Array} The objects to be added to the array.
*/
objects: function() {
return this._objects;
},
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
return { __op: "Add", objects: Parse._encode(this.objects()) };
},
_mergeWithPrevious: function(previous) {
if (!previous) {
return this;
} else if (previous instanceof Parse.Op.Unset) {
return new Parse.Op.Set(this.objects());
} else if (previous instanceof Parse.Op.Set) {
return new Parse.Op.Set(this._estimate(previous.value()));
} else if (previous instanceof Parse.Op.Add) {
return new Parse.Op.Add(previous.objects().concat(this.objects()));
} else {
throw "Op is invalid after previous op.";
}
},
_estimate: function(oldValue) {
if (!oldValue) {
return _.clone(this.objects());
} else {
return oldValue.concat(this.objects());
}
}
});
Parse.Op._registerDecoder("Add", function(json) {
return new Parse.Op.Add(Parse._decode(undefined, json.objects));
});
/**
* @class
* AddUnique is an atomic operation where the given items will be appended to
* the array that is stored in this field only if they were not already
* present in the array.
*/
Parse.Op.AddUnique = Parse.Op._extend(
/** @lends Parse.Op.AddUnique.prototype */ {
_initialize: function(objects) {
this._objects = _.uniq(objects);
},
/**
* Returns the objects to be added to the array.
* @return {Array} The objects to be added to the array.
*/
objects: function() {
return this._objects;
},
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
return { __op: "AddUnique", objects: Parse._encode(this.objects()) };
},
_mergeWithPrevious: function(previous) {
if (!previous) {
return this;
} else if (previous instanceof Parse.Op.Unset) {
return new Parse.Op.Set(this.objects());
} else if (previous instanceof Parse.Op.Set) {
return new Parse.Op.Set(this._estimate(previous.value()));
} else if (previous instanceof Parse.Op.AddUnique) {
return new Parse.Op.AddUnique(this._estimate(previous.objects()));
} else {
throw "Op is invalid after previous op.";
}
},
_estimate: function(oldValue) {
if (!oldValue) {
return _.clone(this.objects());
} else {
// We can't just take the _.uniq(_.union(...)) of oldValue and
// this.objects, because the uniqueness may not apply to oldValue
// (especially if the oldValue was set via .set())
var newValue = _.clone(oldValue);
Parse._arrayEach(this.objects(), function(obj) {
if (obj instanceof Parse.Object && obj.id) {
var matchingObj = _.find(newValue, function(anObj) {
return (anObj instanceof Parse.Object) && (anObj.id === obj.id);
});
if (!matchingObj) {
newValue.push(obj);
} else {
var index = _.indexOf(newValue, matchingObj);
newValue[index] = obj;
}
} else if (!_.contains(newValue, obj)) {
newValue.push(obj);
}
});
return newValue;
}
}
});
Parse.Op._registerDecoder("AddUnique", function(json) {
return new Parse.Op.AddUnique(Parse._decode(undefined, json.objects));
});
/**
* @class
* Remove is an atomic operation where the given objects will be removed from
* the array that is stored in this field.
*/
Parse.Op.Remove = Parse.Op._extend(/** @lends Parse.Op.Remove.prototype */ {
_initialize: function(objects) {
this._objects = _.uniq(objects);
},
/**
* Returns the objects to be removed from the array.
* @return {Array} The objects to be removed from the array.
*/
objects: function() {
return this._objects;
},
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
return { __op: "Remove", objects: Parse._encode(this.objects()) };
},
_mergeWithPrevious: function(previous) {
if (!previous) {
return this;
} else if (previous instanceof Parse.Op.Unset) {
return previous;
} else if (previous instanceof Parse.Op.Set) {
return new Parse.Op.Set(this._estimate(previous.value()));
} else if (previous instanceof Parse.Op.Remove) {
return new Parse.Op.Remove(_.union(previous.objects(), this.objects()));
} else {
throw "Op is invalid after previous op.";
}
},
_estimate: function(oldValue) {
if (!oldValue) {
return [];
} else {
var newValue = _.difference(oldValue, this.objects());
// If there are saved Parse Objects being removed, also remove them.
Parse._arrayEach(this.objects(), function(obj) {
if (obj instanceof Parse.Object && obj.id) {
newValue = _.reject(newValue, function(other) {
return (other instanceof Parse.Object) && (other.id === obj.id);
});
}
});
return newValue;
}
}
});
Parse.Op._registerDecoder("Remove", function(json) {
return new Parse.Op.Remove(Parse._decode(undefined, json.objects));
});
/**
* @class
* A Relation operation indicates that the field is an instance of
* Parse.Relation, and objects are being added to, or removed from, that
* relation.
*/
Parse.Op.Relation = Parse.Op._extend(
/** @lends Parse.Op.Relation.prototype */ {
_initialize: function(adds, removes) {
this._targetClassName = null;
var self = this;
var pointerToId = function(object) {
if (object instanceof Parse.Object) {
if (!object.id) {
throw "You can't add an unsaved Parse.Object to a relation.";
}
if (!self._targetClassName) {
self._targetClassName = object.className;
}
if (self._targetClassName !== object.className) {
throw "Tried to create a Parse.Relation with 2 different types: " +
self._targetClassName + " and " + object.className + ".";
}
return object.id;
}
return object;
};
this.relationsToAdd = _.uniq(_.map(adds, pointerToId));
this.relationsToRemove = _.uniq(_.map(removes, pointerToId));
},
/**
* Returns an array of unfetched Parse.Object that are being added to the
* relation.
* @return {Array}
*/
added: function() {
var self = this;
return _.map(this.relationsToAdd, function(objectId) {
var object = Parse.Object._create(self._targetClassName);
object.id = objectId;
return object;
});
},
/**
* Returns an array of unfetched Parse.Object that are being removed from
* the relation.
* @return {Array}
*/
removed: function() {
var self = this;
return _.map(this.relationsToRemove, function(objectId) {
var object = Parse.Object._create(self._targetClassName);
object.id = objectId;
return object;
});
},
/**
* Returns a JSON version of the operation suitable for sending to Parse.
* @return {Object}
*/
toJSON: function() {
var adds = null;
var removes = null;
var self = this;
var idToPointer = function(id) {
return { __type: 'Pointer',
className: self._targetClassName,
objectId: id };
};
var pointers = null;
if (this.relationsToAdd.length > 0) {
pointers = _.map(this.relationsToAdd, idToPointer);
adds = { "__op": "AddRelation", "objects": pointers };
}
if (this.relationsToRemove.length > 0) {
pointers = _.map(this.relationsToRemove, idToPointer);
removes = { "__op": "RemoveRelation", "objects": pointers };
}
if (adds && removes) {
return { "__op": "Batch", "ops": [adds, removes]};
}
return adds || removes || {};
},
_mergeWithPrevious: function(previous) {
if (!previous) {
return this;
} else if (previous instanceof Parse.Op.Unset) {
throw "You can't modify a relation after deleting it.";
} else if (previous instanceof Parse.Op.Relation) {
if (previous._targetClassName &&
previous._targetClassName !== this._targetClassName) {
throw "Related object must be of class " + previous._targetClassName +
", but " + this._targetClassName + " was passed in.";
}
var newAdd = _.union(_.difference(previous.relationsToAdd,
this.relationsToRemove),
this.relationsToAdd);
var newRemove = _.union(_.difference(previous.relationsToRemove,
this.relationsToAdd),
this.relationsToRemove);
var newRelation = new Parse.Op.Relation(newAdd, newRemove);
newRelation._targetClassName = this._targetClassName;
return newRelation;
} else {
throw "Op is invalid after previous op.";
}
},
_estimate: function(oldValue, object, key) {
if (!oldValue) {
var relation = new Parse.Relation(object, key);
relation.targetClassName = this._targetClassName;
} else if (oldValue instanceof Parse.Relation) {
if (this._targetClassName) {
if (oldValue.targetClassName) {
if (oldValue.targetClassName !== this._targetClassName) {
throw "Related object must be a " + oldValue.targetClassName +
", but a " + this._targetClassName + " was passed in.";
}
} else {
oldValue.targetClassName = this._targetClassName;
}
}
return oldValue;
} else {
throw "Op is invalid after previous op.";
}
}
});
Parse.Op._registerDecoder("AddRelation", function(json) {
return new Parse.Op.Relation(Parse._decode(undefined, json.objects), []);
});
Parse.Op._registerDecoder("RemoveRelation", function(json) {
return new Parse.Op.Relation([], Parse._decode(undefined, json.objects));
});
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Creates a new Relation for the given parent object and key. This
* constructor should rarely be used directly, but rather created by
* Parse.Object.relation.
* @param {Parse.Object} parent The parent of this relation.
* @param {String} key The key for this relation on the parent.
* @see Parse.Object#relation
* @class
*
* <p>
* A class that is used to access all of the children of a many-to-many
* relationship. Each instance of Parse.Relation is associated with a
* particular parent object and key.
* </p>
*/
Parse.Relation = function(parent, key) {
this.parent = parent;
this.key = key;
this.targetClassName = null;
};
Parse.Relation.prototype = {
/**
* Makes sure that this relation has the right parent and key.
*/
_ensureParentAndKey: function(parent, key) {
this.parent = this.parent || parent;
this.key = this.key || key;
if (this.parent !== parent) {
throw "Internal Error. Relation retrieved from two different Objects.";
}
if (this.key !== key) {
throw "Internal Error. Relation retrieved from two different keys.";
}
},
/**
* Adds a Parse.Object or an array of Parse.Objects to the relation.
* @param {} objects The item or items to add.
*/
add: function(objects) {
if (!_.isArray(objects)) {
objects = [objects];
}
var change = new Parse.Op.Relation(objects, []);
this.parent.set(this.key, change);
this.targetClassName = change._targetClassName;
},
/**
* Removes a Parse.Object or an array of Parse.Objects from this relation.
* @param {} objects The item or items to remove.
*/
remove: function(objects) {
if (!_.isArray(objects)) {
objects = [objects];
}
var change = new Parse.Op.Relation([], objects);
this.parent.set(this.key, change);
this.targetClassName = change._targetClassName;
},
/**
* Returns a JSON version of the object suitable for saving to disk.
* @return {Object}
*/
toJSON: function() {
return { "__type": "Relation", "className": this.targetClassName };
},
/**
* Returns a Parse.Query that is limited to objects in this
* relation.
* @return {Parse.Query}
*/
query: function() {
var targetClass;
var query;
if (!this.targetClassName) {
targetClass = Parse.Object._getSubclass(this.parent.className);
query = new Parse.Query(targetClass);
query._extraOptions.redirectClassNameForKey = this.key;
} else {
targetClass = Parse.Object._getSubclass(this.targetClassName);
query = new Parse.Query(targetClass);
}
query._addCondition("$relatedTo", "object", this.parent._toPointer());
query._addCondition("$relatedTo", "key", this.key);
return query;
}
};
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* A Promise is returned by async methods as a hook to provide callbacks to be
* called when the async task is fulfilled.
*
* <p>Typical usage would be like:<pre>
* query.findAsync().then(function(results) {
* results[0].set("foo", "bar");
* return results[0].saveAsync();
* }).then(function(result) {
* console.log("Updated " + result.id);
* });
* </pre></p>
*
* @see Parse.Promise.prototype.next
* @class
*/
Parse.Promise = function() {
this._resolved = false;
this._rejected = false;
this._resolvedCallbacks = [];
this._rejectedCallbacks = [];
};
_.extend(Parse.Promise, /** @lends Parse.Promise */ {
/**
* Returns true iff the given object fulfils the Promise interface.
* @return {Boolean}
*/
is: function(promise) {
return promise && promise.then && _.isFunction(promise.then);
},
/**
* Returns a new promise that is resolved with a given value.
* @return {Parse.Promise} the new promise.
*/
as: function() {
var promise = new Parse.Promise();
promise.resolve.apply(promise, arguments);
return promise;
},
/**
* Returns a new promise that is rejected with a given error.
* @return {Parse.Promise} the new promise.
*/
error: function() {
var promise = new Parse.Promise();
promise.reject.apply(promise, arguments);
return promise;
},
/**
* Returns a new promise that is fulfilled when all of the input promises
* are resolved. If any promise in the list fails, then the returned promise
* will fail with the last error. If they all succeed, then the returned
* promise will succeed, with the result being an array with the results of
* all the input promises.
* @param {Array} promises a list of promises to wait for.
* @return {Parse.Promise} the new promise.
*/
when: function(promises) {
// Allow passing in Promises as separate arguments instead of an Array.
var objects;
if (promises && Parse._isNullOrUndefined(promises.length)) {
objects = arguments;
} else {
objects = promises;
}
var total = objects.length;
var hadError = false;
var results = [];
var errors = [];
results.length = objects.length;
errors.length = objects.length;
if (total === 0) {
return Parse.Promise.as.apply(this, results);
}
var promise = new Parse.Promise();
var resolveOne = function() {
total = total - 1;
if (total === 0) {
if (hadError) {
promise.reject(errors);
} else {
promise.resolve.apply(promise, results);
}
}
};
Parse._arrayEach(objects, function(object, i) {
if (Parse.Promise.is(object)) {
object.then(function(result) {
results[i] = result;
resolveOne();
}, function(error) {
errors[i] = error;
hadError = true;
resolveOne();
});
} else {
results[i] = object;
resolveOne();
}
});
return promise;
},
/**
* Runs the given asyncFunction repeatedly, as long as the predicate
* function returns a truthy value. Stops repeating if asyncFunction returns
* a rejected promise.
* @param {Function} predicate should return false when ready to stop.
* @param {Function} asyncFunction should return a Promise.
*/
_continueWhile: function(predicate, asyncFunction) {
if (predicate()) {
return asyncFunction().then(function() {
return Parse.Promise._continueWhile(predicate, asyncFunction);
});
}
return Parse.Promise.as();
}
});
_.extend(Parse.Promise.prototype, /** @lends Parse.Promise.prototype */ {
/**
* Marks this promise as fulfilled, firing any callbacks waiting on it.
* @param {Object} result the result to pass to the callbacks.
*/
resolve: function(result) {
if (this._resolved || this._rejected) {
throw "A promise was resolved even though it had already been " +
(this._resolved ? "resolved" : "rejected") + ".";
}
this._resolved = true;
this._result = arguments;
var results = arguments;
Parse._arrayEach(this._resolvedCallbacks, function(resolvedCallback) {
resolvedCallback.apply(this, results);
});
this._resolvedCallbacks = [];
this._rejectedCallbacks = [];
},
/**
* Marks this promise as fulfilled, firing any callbacks waiting on it.
* @param {Object} error the error to pass to the callbacks.
*/
reject: function(error) {
if (this._resolved || this._rejected) {
throw "A promise was rejected even though it had already been " +
(this._resolved ? "resolved" : "rejected") + ".";
}
this._rejected = true;
this._error = error;
Parse._arrayEach(this._rejectedCallbacks, function(rejectedCallback) {
rejectedCallback(error);
});
this._resolvedCallbacks = [];
this._rejectedCallbacks = [];
},
/**
* Adds callbacks to be called when this promise is fulfilled. Returns a new
* Promise that will be fulfilled when the callback is complete. It allows
* chaining. If the callback itself returns a Promise, then the one returned
* by "then" will not be fulfilled until that one returned by the callback
* is fulfilled.
* @param {Function} resolvedCallback Function that is called when this
* Promise is resolved. Once the callback is complete, then the Promise
* returned by "then" will also be fulfilled.
* @param {Function} rejectedCallback Function that is called when this
* Promise is rejected with an error. Once the callback is complete, then
* the promise returned by "then" with be resolved successfully. If
* rejectedCallback is null, or it returns a rejected Promise, then the
* Promise returned by "then" will be rejected with that error.
* @return {Parse.Promise} A new Promise that will be fulfilled after this
* Promise is fulfilled and either callback has completed. If the callback
* returned a Promise, then this Promise will not be fulfilled until that
* one is.
*/
then: function(resolvedCallback, rejectedCallback) {
var promise = new Parse.Promise();
var wrappedResolvedCallback = function() {
var result = arguments;
if (resolvedCallback) {
result = [resolvedCallback.apply(this, result)];
}
if (result.length === 1 && Parse.Promise.is(result[0])) {
result[0].then(function() {
promise.resolve.apply(promise, arguments);
}, function(error) {
promise.reject(error);
});
} else {
promise.resolve.apply(promise, result);
}
};
var wrappedRejectedCallback = function(error) {
var result = [];
if (rejectedCallback) {
result = [rejectedCallback(error)];
if (result.length === 1 && Parse.Promise.is(result[0])) {
result[0].then(function() {
promise.resolve.apply(promise, arguments);
}, function(error) {
promise.reject(error);
});
} else {
// A Promises/A+ compliant implementation would call:
// promise.resolve.apply(promise, result);
promise.reject(result[0]);
}
} else {
promise.reject(error);
}
};
if (this._resolved) {
wrappedResolvedCallback.apply(this, this._result);
} else if (this._rejected) {
wrappedRejectedCallback(this._error);
} else {
this._resolvedCallbacks.push(wrappedResolvedCallback);
this._rejectedCallbacks.push(wrappedRejectedCallback);
}
return promise;
},
/**
* Run the given callbacks after this promise is fulfilled.
* @param optionsOrCallback {} A Backbone-style options callback, or a
* callback function. If this is an options object and contains a "model"
* attributes, that will be passed to error callbacks as the first argument.
* @param model {} If truthy, this will be passed as the first result of
* error callbacks. This is for Backbone-compatability.
* @return {Parse.Promise} A promise that will be resolved after the
* callbacks are run, with the same result as this.
*/
_thenRunCallbacks: function(optionsOrCallback, model) {
var options;
if (_.isFunction(optionsOrCallback)) {
var callback = optionsOrCallback;
options = {
success: function(result) {
callback(result, null);
},
error: function(error) {
callback(null, error);
}
};
} else {
options = _.clone(optionsOrCallback);
}
options = options || {};
return this.then(function(result) {
if (options.success) {
options.success.apply(this, arguments);
} else if (model) {
// When there's no callback, a sync event should be triggered.
model.trigger('sync', model, result, options);
}
return Parse.Promise.as.apply(Parse.Promise, arguments);
}, function(error) {
if (options.error) {
if (!_.isUndefined(model)) {
options.error(model, error);
} else {
options.error(error);
}
} else if (model) {
// When there's no error callback, an error event should be triggered.
model.trigger('error', model, error, options);
}
// By explicitly returning a rejected Promise, this will work with
// either jQuery or Promises/A semantics.
return Parse.Promise.error(error);
});
},
/**
* Adds a callback function that should be called regardless of whether
* this promise failed or succeeded. The callback will be given either the
* array of results for its first argument, or the error as its second,
* depending on whether this Promise was rejected or resolved. Returns a
* new Promise, like "then" would.
* @param {Function} continuation the callback.
*/
_continueWith: function(continuation) {
return this.then(function() {
return continuation(arguments, null);
}, function(error) {
return continuation(null, error);
});
}
});
}(this));
/*jshint bitwise:false *//*global FileReader: true, File: true */
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
var b64Digit = function(number) {
if (number < 26) {
return String.fromCharCode(65 + number);
}
if (number < 52) {
return String.fromCharCode(97 + (number - 26));
}
if (number < 62) {
return String.fromCharCode(48 + (number - 52));
}
if (number === 62) {
return "+";
}
if (number === 63) {
return "/";
}
throw "Tried to encode large digit " + number + " in base64.";
};
var encodeBase64 = function(array) {
var chunks = [];
chunks.length = Math.ceil(array.length / 3);
_.times(chunks.length, function(i) {
var b1 = array[i * 3];
var b2 = array[i * 3 + 1] || 0;
var b3 = array[i * 3 + 2] || 0;
var has2 = (i * 3 + 1) < array.length;
var has3 = (i * 3 + 2) < array.length;
chunks[i] = [
b64Digit((b1 >> 2) & 0x3F),
b64Digit(((b1 << 4) & 0x30) | ((b2 >> 4) & 0x0F)),
has2 ? b64Digit(((b2 << 2) & 0x3C) | ((b3 >> 6) & 0x03)) : "=",
has3 ? b64Digit(b3 & 0x3F) : "="
].join("");
});
return chunks.join("");
};
// TODO(klimt): Move this list to the server.
// A list of file extensions to mime types as found here:
// http://stackoverflow.com/questions/58510/using-net-how-can-you-find-the-
// mime-type-of-a-file-based-on-the-file-signature
var mimeTypes = {
ai: "application/postscript",
aif: "audio/x-aiff",
aifc: "audio/x-aiff",
aiff: "audio/x-aiff",
asc: "text/plain",
atom: "application/atom+xml",
au: "audio/basic",
avi: "video/x-msvideo",
bcpio: "application/x-bcpio",
bin: "application/octet-stream",
bmp: "image/bmp",
cdf: "application/x-netcdf",
cgm: "image/cgm",
"class": "application/octet-stream",
cpio: "application/x-cpio",
cpt: "application/mac-compactpro",
csh: "application/x-csh",
css: "text/css",
dcr: "application/x-director",
dif: "video/x-dv",
dir: "application/x-director",
djv: "image/vnd.djvu",
djvu: "image/vnd.djvu",
dll: "application/octet-stream",
dmg: "application/octet-stream",
dms: "application/octet-stream",
doc: "application/msword",
docx: "application/vnd.openxmlformats-officedocument.wordprocessingml." +
"document",
dotx: "application/vnd.openxmlformats-officedocument.wordprocessingml." +
"template",
docm: "application/vnd.ms-word.document.macroEnabled.12",
dotm: "application/vnd.ms-word.template.macroEnabled.12",
dtd: "application/xml-dtd",
dv: "video/x-dv",
dvi: "application/x-dvi",
dxr: "application/x-director",
eps: "application/postscript",
etx: "text/x-setext",
exe: "application/octet-stream",
ez: "application/andrew-inset",
gif: "image/gif",
gram: "application/srgs",
grxml: "application/srgs+xml",
gtar: "application/x-gtar",
hdf: "application/x-hdf",
hqx: "application/mac-binhex40",
htm: "text/html",
html: "text/html",
ice: "x-conference/x-cooltalk",
ico: "image/x-icon",
ics: "text/calendar",
ief: "image/ief",
ifb: "text/calendar",
iges: "model/iges",
igs: "model/iges",
jnlp: "application/x-java-jnlp-file",
jp2: "image/jp2",
jpe: "image/jpeg",
jpeg: "image/jpeg",
jpg: "image/jpeg",
js: "application/x-javascript",
kar: "audio/midi",
latex: "application/x-latex",
lha: "application/octet-stream",
lzh: "application/octet-stream",
m3u: "audio/x-mpegurl",
m4a: "audio/mp4a-latm",
m4b: "audio/mp4a-latm",
m4p: "audio/mp4a-latm",
m4u: "video/vnd.mpegurl",
m4v: "video/x-m4v",
mac: "image/x-macpaint",
man: "application/x-troff-man",
mathml: "application/mathml+xml",
me: "application/x-troff-me",
mesh: "model/mesh",
mid: "audio/midi",
midi: "audio/midi",
mif: "application/vnd.mif",
mov: "video/quicktime",
movie: "video/x-sgi-movie",
mp2: "audio/mpeg",
mp3: "audio/mpeg",
mp4: "video/mp4",
mpe: "video/mpeg",
mpeg: "video/mpeg",
mpg: "video/mpeg",
mpga: "audio/mpeg",
ms: "application/x-troff-ms",
msh: "model/mesh",
mxu: "video/vnd.mpegurl",
nc: "application/x-netcdf",
oda: "application/oda",
ogg: "application/ogg",
pbm: "image/x-portable-bitmap",
pct: "image/pict",
pdb: "chemical/x-pdb",
pdf: "application/pdf",
pgm: "image/x-portable-graymap",
pgn: "application/x-chess-pgn",
pic: "image/pict",
pict: "image/pict",
png: "image/png",
pnm: "image/x-portable-anymap",
pnt: "image/x-macpaint",
pntg: "image/x-macpaint",
ppm: "image/x-portable-pixmap",
ppt: "application/vnd.ms-powerpoint",
pptx: "application/vnd.openxmlformats-officedocument.presentationml." +
"presentation",
potx: "application/vnd.openxmlformats-officedocument.presentationml." +
"template",
ppsx: "application/vnd.openxmlformats-officedocument.presentationml." +
"slideshow",
ppam: "application/vnd.ms-powerpoint.addin.macroEnabled.12",
pptm: "application/vnd.ms-powerpoint.presentation.macroEnabled.12",
potm: "application/vnd.ms-powerpoint.template.macroEnabled.12",
ppsm: "application/vnd.ms-powerpoint.slideshow.macroEnabled.12",
ps: "application/postscript",
qt: "video/quicktime",
qti: "image/x-quicktime",
qtif: "image/x-quicktime",
ra: "audio/x-pn-realaudio",
ram: "audio/x-pn-realaudio",
ras: "image/x-cmu-raster",
rdf: "application/rdf+xml",
rgb: "image/x-rgb",
rm: "application/vnd.rn-realmedia",
roff: "application/x-troff",
rtf: "text/rtf",
rtx: "text/richtext",
sgm: "text/sgml",
sgml: "text/sgml",
sh: "application/x-sh",
shar: "application/x-shar",
silo: "model/mesh",
sit: "application/x-stuffit",
skd: "application/x-koan",
skm: "application/x-koan",
skp: "application/x-koan",
skt: "application/x-koan",
smi: "application/smil",
smil: "application/smil",
snd: "audio/basic",
so: "application/octet-stream",
spl: "application/x-futuresplash",
src: "application/x-wais-source",
sv4cpio: "application/x-sv4cpio",
sv4crc: "application/x-sv4crc",
svg: "image/svg+xml",
swf: "application/x-shockwave-flash",
t: "application/x-troff",
tar: "application/x-tar",
tcl: "application/x-tcl",
tex: "application/x-tex",
texi: "application/x-texinfo",
texinfo: "application/x-texinfo",
tif: "image/tiff",
tiff: "image/tiff",
tr: "application/x-troff",
tsv: "text/tab-separated-values",
txt: "text/plain",
ustar: "application/x-ustar",
vcd: "application/x-cdlink",
vrml: "model/vrml",
vxml: "application/voicexml+xml",
wav: "audio/x-wav",
wbmp: "image/vnd.wap.wbmp",
wbmxl: "application/vnd.wap.wbxml",
wml: "text/vnd.wap.wml",
wmlc: "application/vnd.wap.wmlc",
wmls: "text/vnd.wap.wmlscript",
wmlsc: "application/vnd.wap.wmlscriptc",
wrl: "model/vrml",
xbm: "image/x-xbitmap",
xht: "application/xhtml+xml",
xhtml: "application/xhtml+xml",
xls: "application/vnd.ms-excel",
xml: "application/xml",
xpm: "image/x-xpixmap",
xsl: "application/xml",
xlsx: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
xltx: "application/vnd.openxmlformats-officedocument.spreadsheetml." +
"template",
xlsm: "application/vnd.ms-excel.sheet.macroEnabled.12",
xltm: "application/vnd.ms-excel.template.macroEnabled.12",
xlam: "application/vnd.ms-excel.addin.macroEnabled.12",
xlsb: "application/vnd.ms-excel.sheet.binary.macroEnabled.12",
xslt: "application/xslt+xml",
xul: "application/vnd.mozilla.xul+xml",
xwd: "image/x-xwindowdump",
xyz: "chemical/x-xyz",
zip: "application/zip"
};
/**
* Reads a File using a FileReader.
* @param file {File} the File to read.
* @param type {String} (optional) the mimetype to override with.
* @return {Parse.Promise} A Promise that will be fulfilled with a
* base64-encoded string of the data and its mime type.
*/
var readAsync = function(file, type) {
var promise = new Parse.Promise();
if (typeof(FileReader) === "undefined") {
return Parse.Promise.error(new Parse.Error(
-1, "Attempted to use a FileReader on an unsupported browser."));
}
var reader = new FileReader();
reader.onloadend = function() {
if (reader.readyState !== 2) {
promise.reject(new Parse.Error(-1, "Error reading file."));
return;
}
var dataURL = reader.result;
var matches = /^data:([^;]*);base64,(.*)$/.exec(dataURL);
if (!matches) {
promise.reject(
new Parse.Error(-1, "Unable to interpret data URL: " + dataURL));
return;
}
promise.resolve(matches[2], type || matches[1]);
};
reader.readAsDataURL(file);
return promise;
};
/**
* A Parse.File is a local representation of a file that is saved to the Parse
* cloud.
* @param name {String} The file's name. This will change to a unique value
* once the file has finished saving.
* @param data {Array} The data for the file, as either:
* 1. an Array of byte value Numbers, or
* 2. an Object like { base64: "..." } with a base64-encoded String.
* 3. a File object selected with a file upload control. (3) only works
* in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+.
* For example:<pre>
* var fileUploadControl = $("#profilePhotoFileUpload")[0];
* if (fileUploadControl.files.length > 0) {
* var file = fileUploadControl.files[0];
* var name = "photo.jpg";
* var parseFile = new Parse.File(name, file);
* parseFile.save().then(function() {
* // The file has been saved to Parse.
* }, function(error) {
* // The file either could not be read, or could not be saved to Parse.
* });
* }</pre>
* @param type {String} Optional Content-Type header to use for the file. If
* this is omitted, the content type will be inferred from the name's
* extension.
*/
Parse.File = function(name, data, type) {
this._name = name;
// Guess the content type from the extension if we need to.
var extension = /\.([^.]*)$/.exec(name);
if (extension) {
extension = extension[1].toLowerCase();
}
var guessedType = type || mimeTypes[extension] || "text/plain";
if (_.isArray(data)) {
this._source = Parse.Promise.as(encodeBase64(data), guessedType);
} else if (data && data.base64) {
this._source = Parse.Promise.as(data.base64, guessedType);
} else if (typeof(File) !== "undefined" && data instanceof File) {
this._source = readAsync(data, type);
} else if (_.isString(data)) {
throw "Creating a Parse.File from a String is not yet supported.";
}
};
Parse.File.prototype = {
/**
* Gets the name of the file. Before save is called, this is the filename
* given by the user. After save is called, that name gets prefixed with a
* unique identifier.
*/
name: function() {
return this._name;
},
/**
* Gets the url of the file. It is only available after you save the file or
* after you get the file from a Parse.Object.
* @return {String}
*/
url: function() {
return this._url;
},
/**
* Saves the file to the Parse cloud.
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} Promise that is resolved when the save finishes.
*/
save: function(options) {
var self = this;
if (!self._previousSave) {
self._previousSave = self._source.then(function(base64, type) {
var data = {
base64: base64,
_ContentType: type
};
return Parse._request("files", self._name, null, 'POST', data);
}).then(function(response) {
self._name = response.name;
self._url = response.url;
return self;
});
}
return self._previousSave._thenRunCallbacks(options);
}
};
}(this));
// Parse.Object is analogous to the Java ParseObject.
// It also implements the same interface as a Backbone model.
// TODO: multiple dispatch for callbacks
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Creates a new model with defined attributes. A client id (cid) is
* automatically generated and assigned for you.
*
* <p>You won't normally call this method directly. It is recommended that
* you use a subclass of <code>Parse.Object</code> instead, created by calling
* <code>extend</code>.</p>
*
* <p>However, if you don't want to use a subclass, or aren't sure which
* subclass is appropriate, you can use this form:<pre>
* var object = new Parse.Object("ClassName");
* </pre>
* That is basically equivalent to:<pre>
* var MyClass = Parse.Object.extend("ClassName");
* var object = new MyClass();
* </pre></p>
*
* @param {Object} attributes The initial set of data to store in the object.
* @param {Object} options A set of Backbone-like options for creating the
* object. The only option currently supported is "collection".
* @see Parse.Object.extend
*
* @class
*
* <p>The fundamental unit of Parse data, which implements the Backbone Model
* interface.</p>
*/
Parse.Object = function(attributes, options) {
// Allow new Parse.Object("ClassName") as a shortcut to _create.
if (_.isString(attributes)) {
return Parse.Object._create.apply(this, arguments);
}
attributes = attributes || {};
if (options && options.parse) {
attributes = this.parse(attributes);
}
var defaults = Parse._getValue(this, 'defaults');
if (defaults) {
attributes = _.extend({}, defaults, attributes);
}
if (options && options.collection) {
this.collection = options.collection;
}
this._serverData = {}; // The last known data for this object from cloud.
this._opSetQueue = [{}]; // List of sets of changes to the data.
this.attributes = {}; // The best estimate of this's current data.
this._hashedJSON = {}; // Hash of values of containers at last save.
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
if (!this.set(attributes, {silent: true})) {
throw new Error("Can't create an invalid Parse.Object");
}
this.changed = {};
this._silent = {};
this._pending = {};
this._hasData = true;
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
/**
* @lends Parse.Object.prototype
* @property {String} id The objectId of the Parse Object.
*/
/**
* Saves the given list of Parse.Object.
* If any error is encountered, stops and calls the error handler.
* There are two ways you can call this function.
*
* The Backbone way:<pre>
* Parse.Object.saveAll([object1, object2, ...], {
* success: function(list) {
* // All the objects were saved.
* },
* error: function(error) {
* // An error occurred while saving one of the objects.
* },
* });
* </pre>
* A simplified syntax:<pre>
* Parse.Object.saveAll([object1, object2, ...], function(list, error) {
* if (list) {
* // All the objects were saved.
* } else {
* // An error occurred.
* }
* });
* </pre>
*
* @param {Array} list A list of <code>Parse.Object</code>.
* @param {Object} options A Backbone-style callback object.
*/
Parse.Object.saveAll = function(list, options) {
return Parse.Object._deepSaveAsync(list)._thenRunCallbacks(options);
};
// Attach all inheritable methods to the Parse.Object prototype.
_.extend(Parse.Object.prototype, Parse.Events,
/** @lends Parse.Object.prototype */ {
_existed: false,
/**
* Initialize is an empty function by default. Override it with your own
* initialization logic.
*/
initialize: function(){},
/**
* Returns a JSON version of the object suitable for saving to Parse.
* @return {Object}
*/
toJSON: function() {
var json = this._toFullJSON();
Parse._arrayEach(["__type", "className"],
function(key) { delete json[key]; });
return json;
},
_toFullJSON: function(seenObjects) {
var json = _.clone(this.attributes);
Parse._objectEach(json, function(val, key) {
json[key] = Parse._encode(val, seenObjects);
});
Parse._objectEach(this._operations, function(val, key) {
json[key] = val;
});
if (_.has(this, "id")) {
json.objectId = this.id;
}
if (_.has(this, "createdAt")) {
if (_.isDate(this.createdAt)) {
json.createdAt = this.createdAt.toJSON();
} else {
json.createdAt = this.createdAt;
}
}
if (_.has(this, "updatedAt")) {
if (_.isDate(this.updatedAt)) {
json.updatedAt = this.updatedAt.toJSON();
} else {
json.updatedAt = this.updatedAt;
}
}
json.__type = "Object";
json.className = this.className;
return json;
},
/**
* Updates _hashedJSON to reflect the current state of this object.
* Adds any changed hash values to the set of pending changes.
*/
_refreshCache: function() {
var self = this;
if (self._refreshingCache) {
return;
}
self._refreshingCache = true;
Parse._objectEach(this.attributes, function(value, key) {
if (value instanceof Parse.Object) {
value._refreshCache();
} else if (_.isObject(value)) {
if (self._resetCacheForKey(key)) {
self.set(key, new Parse.Op.Set(value), { silent: true });
}
}
});
delete self._refreshingCache;
},
/**
* Returns true if this object has been modified since its last
* save/refresh. If an attribute is specified, it returns true only if that
* particular attribute has been modified since the last save/refresh.
* @param {String} attr An attribute name (optional).
* @return {Boolean}
*/
dirty: function(attr) {
this._refreshCache();
var currentChanges = _.last(this._opSetQueue);
if (attr) {
return (currentChanges[attr] ? true : false);
}
if (!this.id) {
return true;
}
if (_.keys(currentChanges).length > 0) {
return true;
}
return false;
},
/**
* Gets a Pointer referencing this Object.
*/
_toPointer: function() {
if (!this.id) {
throw new Error("Can't serialize an unsaved Parse.Object");
}
return { __type: "Pointer",
className: this.className,
objectId: this.id };
},
/**
* Gets the value of an attribute.
* @param {String} attr The string name of an attribute.
*/
get: function(attr) {
return this.attributes[attr];
},
/**
* Gets a relation on the given class for the attribute.
* @param String attr The attribute to get the relation for.
*/
relation: function(attr) {
var value = this.get(attr);
if (value) {
if (!(value instanceof Parse.Relation)) {
throw "Called relation() on non-relation field " + attr;
}
value._ensureParentAndKey(this, attr);
return value;
} else {
return new Parse.Relation(this, attr);
}
},
/**
* Gets the HTML-escaped value of an attribute.
*/
escape: function(attr) {
var html = this._escapedAttributes[attr];
if (html) {
return html;
}
var val = this.attributes[attr];
var escaped;
if (Parse._isNullOrUndefined(val)) {
escaped = '';
} else {
escaped = _.escape(val.toString());
}
this._escapedAttributes[attr] = escaped;
return escaped;
},
/**
* Returns <code>true</code> if the attribute contains a value that is not
* null or undefined.
* @param {String} attr The string name of the attribute.
* @return {Boolean}
*/
has: function(attr) {
return !Parse._isNullOrUndefined(this.attributes[attr]);
},
/**
* Pulls "special" fields like objectId, createdAt, etc. out of attrs
* and puts them on "this" directly. Removes them from attrs.
* @param attrs - A dictionary with the data for this Parse.Object.
*/
_mergeMagicFields: function(attrs) {
// Check for changes of magic fields.
var model = this;
var specialFields = ["id", "objectId", "createdAt", "updatedAt"];
Parse._arrayEach(specialFields, function(attr) {
if (attrs[attr]) {
if (attr === "objectId") {
model.id = attrs[attr];
} else if ((attr === "createdAt" || attr === "updatedAt") &&
!_.isDate(attrs[attr])) {
model[attr] = Parse._parseDate(attrs[attr]);
} else {
model[attr] = attrs[attr];
}
delete attrs[attr];
}
});
},
/**
* Returns the json to be sent to the server.
*/
_startSave: function() {
this._opSetQueue.push({});
},
/**
* Called when a save fails because of an error. Any changes that were part
* of the save need to be merged with changes made after the save. This
* might throw an exception is you do conflicting operations. For example,
* if you do:
* object.set("foo", "bar");
* object.set("invalid field name", "baz");
* object.save();
* object.increment("foo");
* then this will throw when the save fails and the client tries to merge
* "bar" with the +1.
*/
_cancelSave: function() {
var self = this;
var failedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
var nextChanges = _.first(this._opSetQueue);
Parse._objectEach(failedChanges, function(op, key) {
var op1 = failedChanges[key];
var op2 = nextChanges[key];
if (op1 && op2) {
nextChanges[key] = op2._mergeWithPrevious(op1);
} else if (op1) {
nextChanges[key] = op1;
}
});
this._saving = this._saving - 1;
},
/**
* Called when a save completes successfully. This merges the changes that
* were saved into the known server data, and overrides it with any data
* sent directly from the server.
*/
_finishSave: function(serverData) {
// Grab a copy of any object referenced by this object. These instances
// may have already been fetched, and we don't want to lose their data.
// Note that doing it like this means we will unify separate copies of the
// same object, but that's a risk we have to take.
var fetchedObjects = {};
Parse._traverse(this.attributes, function(object) {
if (object instanceof Parse.Object && object.id && object._hasData) {
fetchedObjects[object.id] = object;
}
});
var savedChanges = _.first(this._opSetQueue);
this._opSetQueue = _.rest(this._opSetQueue);
this._applyOpSet(savedChanges, this._serverData);
this._mergeMagicFields(serverData);
var self = this;
Parse._objectEach(serverData, function(value, key) {
self._serverData[key] = Parse._decode(key, value);
// Look for any objects that might have become unfetched and fix them
// by replacing their values with the previously observed values.
var fetched = Parse._traverse(self._serverData[key], function(object) {
if (object instanceof Parse.Object && fetchedObjects[object.id]) {
return fetchedObjects[object.id];
}
});
if (fetched) {
self._serverData[key] = fetched;
}
});
this._rebuildAllEstimatedData();
this._saving = this._saving - 1;
},
/**
* Called when a fetch or login is complete to set the known server data to
* the given object.
*/
_finishFetch: function(serverData, hasData) {
// Clear out any changes the user might have made previously.
this._opSetQueue = [{}];
// Bring in all the new server data.
this._mergeMagicFields(serverData);
var self = this;
Parse._objectEach(serverData, function(value, key) {
self._serverData[key] = Parse._decode(key, value);
});
// Refresh the attributes.
this._rebuildAllEstimatedData();
// Clear out the cache of mutable containers.
this._refreshCache();
this._opSetQueue = [{}];
this._hasData = hasData;
},
/**
* Applies the set of Parse.Op in opSet to the object target.
*/
_applyOpSet: function(opSet, target) {
var self = this;
Parse._objectEach(opSet, function(change, key) {
target[key] = change._estimate(target[key], self, key);
if (target[key] === Parse.Op._UNSET) {
delete target[key];
}
});
},
/**
* Replaces the cached value for key with the current value.
* Returns true if the new value is different than the old value.
*/
_resetCacheForKey: function(key) {
var value = this.attributes[key];
if (_.isObject(value) &&
!(value instanceof Parse.Object) &&
!(value instanceof Parse.File)) {
value = value.toJSON ? value.toJSON() : value;
var json = JSON.stringify(value);
if (this._hashedJSON[key] !== json) {
this._hashedJSON[key] = json;
return true;
}
}
return false;
},
/**
* Populates attributes[key] by starting with the last known data from the
* server, and applying all of the local changes that have been made to that
* key since then.
*/
_rebuildEstimatedDataForKey: function(key) {
var self = this;
delete this.attributes[key];
if (this._serverData[key]) {
this.attributes[key] = this._serverData[key];
}
Parse._arrayEach(this._opSetQueue, function(opSet) {
var op = opSet[key];
if (op) {
self.attributes[key] = op._estimate(self.attributes[key], self, key);
if (self.attributes[key] === Parse.Op._UNSET) {
delete self.attributes[key];
} else {
self._resetCacheForKey(key);
}
}
});
},
/**
* Populates attributes by starting with the last known data from the
* server, and applying all of the local changes that have been made since
* then.
*/
_rebuildAllEstimatedData: function() {
var self = this;
var previousAttributes = _.clone(this.attributes);
this.attributes = _.clone(this._serverData);
Parse._arrayEach(this._opSetQueue, function(opSet) {
self._applyOpSet(opSet, self.attributes);
Parse._objectEach(opSet, function(op, key) {
self._resetCacheForKey(key);
});
});
// Trigger change events for anything that changed because of the fetch.
Parse._objectEach(previousAttributes, function(oldValue, key) {
if (self.attributes[key] !== oldValue) {
self.trigger('change:' + key, self, self.attributes[key], {});
}
});
Parse._objectEach(this.attributes, function(newValue, key) {
if (!_.has(previousAttributes, key)) {
self.trigger('change:' + key, self, newValue, {});
}
});
},
/**
* Sets a hash of model attributes on the object, firing
* <code>"change"</code> unless you choose to silence it.
*
* <p>You can call it with an object containing keys and values, or with one
* key and value. For example:<pre>
* gameTurn.set({
* player: player1,
* diceRoll: 2
* }, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("currentPlayer", player2, {
* error: function(gameTurnAgain, error) {
* // The set failed validation.
* }
* });
*
* game.set("finished", true);</pre></p>
*
* @param {String} key The key to set.
* @param {} value The value to give it.
* @param {Object} options A set of Backbone-like options for the set.
* The only supported options are <code>silent</code>,
* <code>error</code>, and <code>promise</code>.
* @return {Boolean} true if the set succeeded.
* @see Parse.Object#validate
* @see Parse.Error
*/
set: function(key, value, options) {
var attrs, attr;
if (_.isObject(key) || Parse._isNullOrUndefined(key)) {
attrs = key;
Parse._objectEach(attrs, function(v, k) {
attrs[k] = Parse._decode(k, v);
});
options = value;
} else {
attrs = {};
attrs[key] = Parse._decode(key, value);
}
// Extract attributes and options.
options = options || {};
if (!attrs) {
return this;
}
if (attrs instanceof Parse.Object) {
attrs = attrs.attributes;
}
// If the unset option is used, every attribute should be a Unset.
if (options.unset) {
Parse._objectEach(attrs, function(unused_value, key) {
attrs[key] = new Parse.Op.Unset();
});
}
// Apply all the attributes to get the estimated values.
var dataToValidate = _.clone(attrs);
var self = this;
Parse._objectEach(dataToValidate, function(value, key) {
if (value instanceof Parse.Op) {
dataToValidate[key] = value._estimate(self.attributes[key],
self, key);
if (dataToValidate[key] === Parse.Op._UNSET) {
delete dataToValidate[key];
}
}
});
// Run validation.
if (!this._validate(attrs, options)) {
return false;
}
this._mergeMagicFields(attrs);
options.changes = {};
var escaped = this._escapedAttributes;
var prev = this._previousAttributes || {};
// Update attributes.
Parse._arrayEach(_.keys(attrs), function(attr) {
var val = attrs[attr];
// If this is a relation object we need to set the parent correctly,
// since the location where it was parsed does not have access to
// this object.
if (val instanceof Parse.Relation) {
val.parent = self;
}
if (!(val instanceof Parse.Op)) {
val = new Parse.Op.Set(val);
}
// See if this change will actually have any effect.
var isRealChange = true;
if (val instanceof Parse.Op.Set &&
_.isEqual(self.attributes[attr], val.value)) {
isRealChange = false;
}
if (isRealChange) {
delete escaped[attr];
if (options.silent) {
self._silent[attr] = true;
} else {
options.changes[attr] = true;
}
}
var currentChanges = _.last(self._opSetQueue);
currentChanges[attr] = val._mergeWithPrevious(currentChanges[attr]);
self._rebuildEstimatedDataForKey(attr);
if (isRealChange) {
self.changed[attr] = self.attributes[attr];
if (!options.silent) {
self._pending[attr] = true;
}
} else {
delete self.changed[attr];
delete self._pending[attr];
}
});
if (!options.silent) {
this.change(options);
}
return this;
},
/**
* Remove an attribute from the model, firing <code>"change"</code> unless
* you choose to silence it. This is a noop if the attribute doesn't
* exist.
*/
unset: function(attr, options) {
options = options || {};
options.unset = true;
return this.set(attr, null, options);
},
/**
* Atomically increments the value of the given attribute the next time the
* object is saved. If no amount is specified, 1 is used by default.
*
* @param attr {String} The key.
* @param amount {Number} The amount to increment by.
*/
increment: function(attr, amount) {
if (_.isUndefined(amount) || _.isNull(amount)) {
amount = 1;
}
return this.set(attr, new Parse.Op.Increment(amount));
},
/**
* Atomically add an object to the end of the array associated with a given
* key.
* @param attr {String} The key.
* @param item {} The item to add.
*/
add: function(attr, item) {
return this.set(attr, new Parse.Op.Add([item]));
},
/**
* Atomically add an object to the array associated with a given key, only
* if it is not already present in the array. The position of the insert is
* not guaranteed.
*
* @param attr {String} The key.
* @param item {} The object to add.
*/
addUnique: function(attr, item) {
return this.set(attr, new Parse.Op.AddUnique([item]));
},
/**
* Atomically remove all instances of an object from the array associated
* with a given key.
*
* @param attr {String} The key.
* @param item {} The object to remove.
*/
remove: function(attr, item) {
return this.set(attr, new Parse.Op.Remove([item]));
},
/**
* Returns an instance of a subclass of Parse.Op describing what kind of
* modification has been performed on this field since the last time it was
* saved. For example, after calling object.increment("x"), calling
* object.op("x") would return an instance of Parse.Op.Increment.
*
* @param attr {String} The key.
* @returns {Parse.Op} The operation, or undefined if none.
*/
op: function(attr) {
return _.last(this._opSetQueue)[attr];
},
/**
* Clear all attributes on the model, firing <code>"change"</code> unless
* you choose to silence it.
*/
clear: function(options) {
options = options || {};
options.unset = true;
var keysToClear = _.extend(this.attributes, this._operations);
return this.set(keysToClear, options);
},
/**
* Returns a JSON-encoded set of operations to be sent with the next save
* request.
*/
_getSaveJSON: function() {
var json = _.clone(_.first(this._opSetQueue));
Parse._objectEach(json, function(op, key) {
json[key] = op.toJSON();
});
return json;
},
/**
* Returns true if this object can be serialized for saving.
*/
_canBeSerialized: function() {
return Parse.Object._canBeSerializedAsValue(this.attributes);
},
/**
* Fetch the model from the server. If the server's representation of the
* model differs from its current attributes, they will be overriden,
* triggering a <code>"change"</code> event.
* @return {Parse.Promise} A promise that is fulfilled when the fetch
* completes.
*/
fetch: function(options) {
var self = this;
var request = Parse._request("classes", this.className, this.id, 'GET');
return request.then(function(response, status, xhr) {
self._finishFetch(self.parse(response, status, xhr), true);
return self;
})._thenRunCallbacks(options, this);
},
/**
* Set a hash of model attributes, and save the model to the server.
* updatedAt will be updated when the request returns.
* You can either call it as:<pre>
* object.save();</pre>
* or<pre>
* object.save(null, options);</pre>
* or<pre>
* object.save(attrs, options);</pre>
* or<pre>
* object.save(key, value, options);</pre>
*
* For example, <pre>
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }, {
* success: function(gameTurnAgain) {
* // The save was successful.
* },
* error: function(gameTurnAgain, error) {
* // The save failed. Error is an instance of Parse.Error.
* }
* });</pre>
* or with promises:<pre>
* gameTurn.save({
* player: "Jake Cutter",
* diceRoll: 2
* }).then(function(gameTurnAgain) {
* // The save was successful.
* }, function(error) {
* // The save failed. Error is an instance of Parse.Error.
* });</pre>
*
* @return {Parse.Promise} A promise that is fulfilled when the save
* completes.
* @see Parse.Error
*/
save: function(arg1, arg2, arg3) {
var i, attrs, current, options, saved;
if (_.isObject(arg1) || Parse._isNullOrUndefined(arg1)) {
attrs = arg1;
options = arg2;
} else {
attrs = {};
attrs[arg1] = arg2;
options = arg3;
}
// Make save({ success: function() {} }) work.
if (!options && attrs) {
var extra_keys = _.reject(attrs, function(value, key) {
return _.include(["success", "error", "wait"], key);
});
if (extra_keys.length === 0) {
var all_functions = true;
if (_.has(attrs, "success") && !_.isFunction(attrs.success)) {
all_functions = false;
}
if (_.has(attrs, "error") && !_.isFunction(attrs.error)) {
all_functions = false;
}
if (all_functions) {
// This attrs object looks like it's really an options object,
// and there's no other options object, so let's just use it.
return this.save(null, attrs);
}
}
}
options = _.clone(options) || {};
if (options.wait) {
current = _.clone(this.attributes);
}
var setOptions = _.clone(options) || {};
if (setOptions.wait) {
setOptions.silent = true;
}
var setError;
setOptions.error = function(model, error) {
setError = error;
};
if (attrs && !this.set(attrs, setOptions)) {
return Parse.Promise.error(setError)._thenRunCallbacks(options, this);
}
var model = this;
// If there is any unsaved child, save it first.
model._refreshCache();
// TODO(klimt): Refactor this so that the save starts now, not later.
var unsavedChildren = [];
var unsavedFiles = [];
Parse.Object._findUnsavedChildren(model.attributes,
unsavedChildren,
unsavedFiles);
if (unsavedChildren.length + unsavedFiles.length > 0) {
return Parse.Object._deepSaveAsync(this.attributes).then(function() {
return model.save(null, options);
}, function(error) {
return Parse.Promise.error(error)._thenRunCallbacks(options, model);
});
}
this._startSave();
this._saving = (this._saving || 0) + 1;
this._allPreviousSaves = this._allPreviousSaves || Parse.Promise.as();
this._allPreviousSaves = this._allPreviousSaves._continueWith(function() {
var method = model.id ? 'PUT' : 'POST';
var json = model._getSaveJSON();
var route = "classes";
var className = model.className;
if (model.className === "_User" && !model.id) {
// Special-case user sign-up.
route = "users";
className = null;
}
var request = Parse._request(route, className, model.id, method, json);
request = request.then(function(resp, status, xhr) {
var serverAttrs = model.parse(resp, status, xhr);
if (options.wait) {
serverAttrs = _.extend(attrs || {}, serverAttrs);
}
model._finishSave(serverAttrs);
if (options.wait) {
model.set(current, setOptions);
}
return model;
}, function(error) {
model._cancelSave();
return Parse.Promise.error(error);
})._thenRunCallbacks(options, model);
return request;
});
return this._allPreviousSaves;
},
/**
* Destroy this model on the server if it was already persisted.
* Optimistically removes the model from its collection, if it has one.
* If `wait: true` is passed, waits for the server to respond
* before removal.
*
* @return {Parse.Promise} A promise that is fulfilled when the destroy
* completes.
*/
destroy: function(options) {
options = options || {};
var model = this;
var triggerDestroy = function() {
model.trigger('destroy', model, model.collection, options);
};
if (!this.id) {
return triggerDestroy();
}
if (!options.wait) {
triggerDestroy();
}
var request =
Parse._request("classes", this.className, this.id, 'DELETE');
return request.then(function() {
if (options.wait) {
triggerDestroy();
}
return model;
})._thenRunCallbacks(options, this);
},
/**
* Converts a response into the hash of attributes to be set on the model.
* @ignore
*/
parse: function(resp, status, xhr) {
var output = _.clone(resp);
_(["createdAt", "updatedAt"]).each(function(key) {
if (output[key]) {
output[key] = Parse._parseDate(output[key]);
}
});
if (!output.updatedAt) {
output.updatedAt = output.createdAt;
}
if (status) {
this._existed = (status !== 201);
}
return output;
},
/**
* Creates a new model with identical attributes to this one.
* @return {Parse.Object}
*/
clone: function() {
return new this.constructor(this.attributes);
},
/**
* Returns true if this object has never been saved to Parse.
* @return {Boolean}
*/
isNew: function() {
return !this.id;
},
/**
* Call this method to manually fire a `"change"` event for this model and
* a `"change:attribute"` event for each changed attribute.
* Calling this will cause all objects observing the model to update.
*/
change: function(options) {
options = options || {};
var changing = this._changing;
this._changing = true;
// Silent changes become pending changes.
var self = this;
Parse._objectEach(this._silent, function(attr) {
self._pending[attr] = true;
});
// Silent changes are triggered.
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
Parse._objectEach(changes, function(unused_value, attr) {
self.trigger('change:' + attr, self, self.get(attr), options);
});
if (changing) {
return this;
}
// This is to get around lint not letting us make a function in a loop.
var deleteChanged = function(value, attr) {
if (!self._pending[attr] && !self._silent[attr]) {
delete self.changed[attr];
}
};
// Continue firing `"change"` events while there are pending changes.
while (!_.isEmpty(this._pending)) {
this._pending = {};
this.trigger('change', this, options);
// Pending and silent changes still remain.
Parse._objectEach(this.changed, deleteChanged);
self._previousAttributes = _.clone(this.attributes);
}
this._changing = false;
return this;
},
/**
* Returns true if this object was created by the Parse server when the
* object might have already been there (e.g. in the case of a Facebook
* login)
*/
existed: function() {
return this._existed;
},
/**
* Determine if the model has changed since the last <code>"change"</code>
* event. If you specify an attribute name, determine if that attribute
* has changed.
* @param {String} attr Optional attribute name
* @return {Boolean}
*/
hasChanged: function(attr) {
if (!arguments.length) {
return !_.isEmpty(this.changed);
}
return this.changed && _.has(this.changed, attr);
},
/**
* Returns an object containing all the attributes that have changed, or
* false if there are no changed attributes. Useful for determining what
* parts of a view need to be updated and/or what attributes need to be
* persisted to the server. Unset attributes will be set to undefined.
* You can also pass an attributes object to diff against the model,
* determining if there *would be* a change.
*/
changedAttributes: function(diff) {
if (!diff) {
return this.hasChanged() ? _.clone(this.changed) : false;
}
var changed = {};
var old = this._previousAttributes;
Parse._objectEach(diff, function(diffVal, attr) {
if (!_.isEqual(old[attr], diffVal)) {
changed[attr] = diffVal;
}
});
return changed;
},
/**
* Gets the previous value of an attribute, recorded at the time the last
* <code>"change"</code> event was fired.
* @param {String} attr Name of the attribute to get.
*/
previous: function(attr) {
if (!arguments.length || !this._previousAttributes) {
return null;
}
return this._previousAttributes[attr];
},
/**
* Gets all of the attributes of the model at the time of the previous
* <code>"change"</code> event.
* @return {Object}
*/
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
/**
* Checks if the model is currently in a valid state. It's only possible to
* get into an *invalid* state if you're using silent changes.
* @return {Boolean}
*/
isValid: function() {
return !this.validate(this.attributes);
},
/**
* You should not call this function directly unless you subclass
* <code>Parse.Object</code>, in which case you can override this method
* to provide additional validation on <code>set</code> and
* <code>save</code>. Your implementation should return
*
* @param {Object} attrs The current data to validate.
* @param {Object} options A Backbone-like options object.
* @return {} False if the data is valid. An error object otherwise.
* @see Parse.Object#set
*/
validate: function(attrs, options) {
if (_.has(attrs, "ACL") && !(attrs.ACL instanceof Parse.ACL)) {
return new Parse.Error(Parse.Error.OTHER_CAUSE,
"ACL must be a Parse.ACL.");
}
return false;
},
/**
* Run validation against a set of incoming attributes, returning `true`
* if all is well. If a specific `error` callback has been passed,
* call that instead of firing the general `"error"` event.
*/
_validate: function(attrs, options) {
if (options.silent || !this.validate) {
return true;
}
attrs = _.extend({}, this.attributes, attrs);
var error = this.validate(attrs, options);
if (!error) {
return true;
}
if (options && options.error) {
options.error(this, error, options);
} else {
this.trigger('error', this, error, options);
}
return false;
},
/**
* Returns the ACL for this object.
* @returns {Parse.ACL} An instance of Parse.ACL.
* @see Parse.Object#get
*/
getACL: function() {
return this.get("ACL");
},
/**
* Sets the ACL to be used for this object.
* @param {Parse.ACL} acl An instance of Parse.ACL.
* @param {Object} options Optional Backbone-like options object to be
* passed in to set.
* @return {Boolean} Whether the set passed validation.
* @see Parse.Object#set
*/
setACL: function(acl, options) {
return this.set("ACL", acl, options);
}
});
/**
* Returns the appropriate subclass for making new instances of the given
* className string.
*/
Parse.Object._getSubclass = function(className) {
if (!_.isString(className)) {
throw "Parse.Object._getSubclass requires a string argument.";
}
var ObjectClass = Parse.Object._classMap[className];
if (!ObjectClass) {
ObjectClass = Parse.Object.extend(className);
Parse.Object._classMap[className] = ObjectClass;
}
return ObjectClass;
};
/**
* Creates an instance of a subclass of Parse.Object for the given classname.
*/
Parse.Object._create = function(className, attributes, options) {
var ObjectClass = Parse.Object._getSubclass(className);
return new ObjectClass(attributes, options);
};
// Set up a map of className to class so that we can create new instances of
// Parse Objects from JSON automatically.
Parse.Object._classMap = {};
Parse.Object._extend = Parse._extend;
/**
* Creates a new subclass of Parse.Object for the given Parse class name.
*
* <p>Every extension of a Parse class will inherit from the most recent
* previous extension of that class. When a Parse.Object is automatically
* created by parsing JSON, it will use the most recent extension of that
* class.</p>
*
* <p>You should call either:<pre>
* var MyClass = Parse.Object.extend("MyClass", {
* <i>Instance properties</i>
* }, {
* <i>Class properties</i>
* });</pre>
* or, for Backbone compatibility:<pre>
* var MyClass = Parse.Object.extend({
* className: "MyClass",
* <i>Other instance properties</i>
* }, {
* <i>Class properties</i>
* });</pre></p>
*
* @param {String} className The name of the Parse class backing this model.
* @param {Object} protoProps Instance properties to add to instances of the
* class returned from this method.
* @param {Object} classProps Class properties to add the class returned from
* this method.
* @return {Class} A new subclass of Parse.Object.
*/
Parse.Object.extend = function(className, protoProps, classProps) {
// Handle the case with only two args.
if (!_.isString(className)) {
if (className && _.has(className, "className")) {
return Parse.Object.extend(className.className, className, protoProps);
} else {
throw new Error(
"Parse.Object.extend's first argument should be the className.");
}
}
// If someone tries to subclass "User", coerce it to the right type.
if (className === "User") {
className = "_User";
}
var NewClassObject = null;
if (_.has(Parse.Object._classMap, className)) {
var OldClassObject = Parse.Object._classMap[className];
// This new subclass has been told to extend both from "this" and from
// OldClassObject. This is multiple inheritance, which isn't supported.
// For now, let's just pick one.
NewClassObject = OldClassObject._extend(protoProps, classProps);
} else {
protoProps = protoProps || {};
protoProps.className = className;
NewClassObject = this._extend(protoProps, classProps);
}
// Extending a subclass should reuse the classname automatically.
NewClassObject.extend = function(arg0) {
if (_.isString(arg0) || (arg0 && _.has(arg0, "className"))) {
return Parse.Object.extend.apply(NewClassObject, arguments);
}
var newArguments = [className].concat(Parse._.toArray(arguments));
return Parse.Object.extend.apply(NewClassObject, newArguments);
};
Parse.Object._classMap[className] = NewClassObject;
return NewClassObject;
};
Parse.Object._findUnsavedChildren = function(object, children, files) {
Parse._traverse(object, function(object) {
if (object instanceof Parse.Object) {
object._refreshCache();
if (object.dirty()) {
children.push(object);
}
return;
}
if (object instanceof Parse.File) {
if (!object.url()) {
files.push(object);
}
return;
}
});
};
Parse.Object._canBeSerializedAsValue = function(object) {
var canBeSerializedAsValue = true;
if (object instanceof Parse.Object) {
canBeSerializedAsValue = !!object.id;
} else if (_.isArray(object)) {
Parse._arrayEach(object, function(child) {
if (!Parse.Object._canBeSerializedAsValue(child)) {
canBeSerializedAsValue = false;
}
});
} else if (_.isObject(object)) {
Parse._objectEach(object, function(child) {
if (!Parse.Object._canBeSerializedAsValue(child)) {
canBeSerializedAsValue = false;
}
});
}
return canBeSerializedAsValue;
};
Parse.Object._deepSaveAsync = function(object) {
var unsavedChildren = [];
var unsavedFiles = [];
Parse.Object._findUnsavedChildren(object, unsavedChildren, unsavedFiles);
var promise = Parse.Promise.as();
_.each(unsavedFiles, function(file) {
promise = promise.then(function() {
return file.save();
});
});
var objects = _.uniq(unsavedChildren);
var remaining = _.uniq(objects);
return promise.then(function() {
return Parse.Promise._continueWhile(function() {
return remaining.length > 0;
}, function() {
// Gather up all the objects that can be saved in this batch.
var batch = [];
var newRemaining = [];
Parse._arrayEach(remaining, function(object) {
// Limit batches to 20 objects.
if (batch.length > 20) {
newRemaining.push(object);
return;
}
if (object._canBeSerialized()) {
batch.push(object);
} else {
newRemaining.push(object);
}
});
remaining = newRemaining;
// If we can't save any objects, there must be a circular reference.
if (batch.length === 0) {
return Parse.Promise.error(
new Parse.Error(Parse.Error.OTHER_CAUSE,
"Tried to save a batch with a cycle."));
}
// Reserve a spot in every object's save queue.
var readyToStart = Parse.Promise.when(_.map(batch, function(object) {
return object._allPreviousSaves || Parse.Promise.as();
}));
var batchFinished = new Parse.Promise();
Parse._arrayEach(batch, function(object) {
object._allPreviousSaves = batchFinished;
});
// Save a single batch, whether previous saves succeeded or failed.
return readyToStart._continueWith(function() {
return Parse._request("batch", null, null, "POST", {
requests: _.map(batch, function(object) {
var json = object._getSaveJSON();
var method = "POST";
var path = "/1/classes/" + object.className;
if (object.id) {
path = path + "/" + object.id;
method = "PUT";
}
object._startSave();
return {
method: method,
path: path,
body: json
};
})
}).then(function(response, status, xhr) {
var error;
Parse._arrayEach(batch, function(object, i) {
if (response[i].success) {
object._finishSave(
object.parse(response[i].success, status, xhr));
} else {
error = error || response[i].error;
object._cancelSave();
}
});
if (error) {
return Parse.Promise.error(
new Parse.Error(error.code, error.error));
}
}).then(function(results) {
batchFinished.resolve(results);
return results;
}, function(error) {
batchFinished.reject(error);
return Parse.Promise.error(error);
});
});
});
}).then(function() {
return object;
});
};
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Represents a Role on the Parse server. Roles represent groupings of
* Users for the purposes of granting permissions (e.g. specifying an ACL
* for an Object). Roles are specified by their sets of child users and
* child roles, all of which are granted any permissions that the parent
* role has.
*
* <p>Roles must have a name (which cannot be changed after creation of the
* role), and must specify an ACL.</p>
* @class
* A Parse.Role is a local representation of a role persisted to the Parse
* cloud.
*/
Parse.Role = Parse.Object.extend("_Role", /** @lends Parse.Role.prototype */ {
// Instance Methods
/**
* Constructs a new ParseRole with the given name and ACL.
*
* @param {String} name The name of the Role to create.
* @param {Parse.ACL} acl The ACL for this role. Roles must have an ACL.
*/
constructor: function(name, acl) {
if (_.isString(name) && (acl instanceof Parse.ACL)) {
Parse.Object.prototype.constructor.call(this, null, null);
this.setName(name);
this.setACL(acl);
} else {
Parse.Object.prototype.constructor.call(this, name, acl);
}
},
/**
* Gets the name of the role. You can alternatively call role.get("name")
*
* @return {String} the name of the role.
*/
getName: function() {
return this.get("name");
},
/**
* Sets the name for a role. This value must be set before the role has
* been saved to the server, and cannot be set once the role has been
* saved.
*
* <p>
* A role's name can only contain alphanumeric characters, _, -, and
* spaces.
* </p>
*
* <p>This is equivalent to calling role.set("name", name)</p>
*
* @param {String} name The name of the role.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
setName: function(name, options) {
return this.set("name", name, options);
},
/**
* Gets the Parse.Relation for the Parse.Users that are direct
* children of this role. These users are granted any privileges that this
* role has been granted (e.g. read or write access through ACLs). You can
* add or remove users from the role through this relation.
*
* <p>This is equivalent to calling role.relation("users")</p>
*
* @return {Parse.Relation} the relation for the users belonging to this
* role.
*/
getUsers: function() {
return this.relation("users");
},
/**
* Gets the Parse.Relation for the Parse.Roles that are direct
* children of this role. These roles' users are granted any privileges that
* this role has been granted (e.g. read or write access through ACLs). You
* can add or remove child roles from this role through this relation.
*
* <p>This is equivalent to calling role.relation("roles")</p>
*
* @return {Parse.Relation} the relation for the roles belonging to this
* role.
*/
getRoles: function() {
return this.relation("roles");
},
/**
* @ignore
*/
validate: function(attrs, options) {
if ("name" in attrs && attrs.name !== this.getName()) {
var newName = attrs.name;
if (this.id && this.id !== attrs.objectId) {
// Check to see if the objectId being set matches this.id.
// This happens during a fetch -- the id is set before calling fetch.
// Let the name be set in this case.
return new Parse.Error(Parse.Error.OTHER_CAUSE,
"A role's name can only be set before it has been saved.");
}
if (!_.isString(newName)) {
return new Parse.Error(Parse.Error.OTHER_CAUSE,
"A role's name must be a String.");
}
if (!(/^[0-9a-zA-Z\-_ ]+$/).test(newName)) {
return new Parse.Error(Parse.Error.OTHER_CAUSE,
"A role's name can only contain alphanumeric characters, _," +
" -, and spaces.");
}
}
if (Parse.Object.prototype.validate) {
return Parse.Object.prototype.validate.call(this, attrs, options);
}
return false;
}
});
}(this));
/*global _: false */
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Creates a new instance with the given models and options. Typically, you
* will not call this method directly, but will instead make a subclass using
* <code>Parse.Collection.extend</code>.
*
* @param {Array} models An array of instances of <code>Parse.Object</code>.
*
* @param {Object} options An optional object with Backbone-style options.
* Valid options are:<ul>
* <li>model: The Parse.Object subclass that this collection contains.
* <li>query: An instance of Parse.Query to use when fetching items.
* <li>comparator: A string property name or function to sort by.
* </ul>
*
* @see Parse.Collection.extend
*
* @class
*
* <p>Provides a standard collection class for our sets of models, ordered
* or unordered. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Collection">Backbone
* documentation</a>.</p>
*/
Parse.Collection = function(models, options) {
options = options || {};
if (options.comparator) {
this.comparator = options.comparator;
}
if (options.model) {
this.model = options.model;
}
if (options.query) {
this.query = options.query;
}
this._reset();
this.initialize.apply(this, arguments);
if (models) {
this.reset(models, {silent: true, parse: options.parse});
}
};
// Define the Collection's inheritable methods.
_.extend(Parse.Collection.prototype, Parse.Events,
/** @lends Parse.Collection.prototype */ {
// The default model for a collection is just a Parse.Object.
// This should be overridden in most cases.
// TODO: think harder. this is likely to be weird.
model: Parse.Object,
/**
* Initialize is an empty function by default. Override it with your own
* initialization logic.
*/
initialize: function(){},
/**
* The JSON representation of a Collection is an array of the
* models' attributes.
*/
toJSON: function() {
return this.map(function(model){ return model.toJSON(); });
},
/**
* Add a model, or list of models to the set. Pass **silent** to avoid
* firing the `add` event for every new model.
*/
add: function(models, options) {
var i, index, length, model, cid, id, cids = {}, ids = {};
options = options || {};
models = _.isArray(models) ? models.slice() : [models];
// Begin by turning bare objects into model references, and preventing
// invalid models or duplicate models from being added.
for (i = 0, length = models.length; i < length; i++) {
models[i] = this._prepareModel(models[i], options);
model = models[i];
if (!model) {
throw new Error("Can't add an invalid model to a collection");
}
cid = model.cid;
if (cids[cid] || this._byCid[cid]) {
throw new Error("Duplicate cid: can't add the same model " +
"to a collection twice");
}
id = model.id;
if (!Parse._isNullOrUndefined(id) && (ids[id] || this._byId[id])) {
throw new Error("Duplicate id: can't add the same model " +
"to a collection twice");
}
ids[id] = model;
cids[cid] = model;
}
// Listen to added models' events, and index models for lookup by
// `id` and by `cid`.
for (i = 0; i < length; i++) {
(model = models[i]).on('all', this._onModelEvent, this);
this._byCid[model.cid] = model;
if (model.id) {
this._byId[model.id] = model;
}
}
// Insert models into the collection, re-sorting if needed, and triggering
// `add` events unless silenced.
this.length += length;
index = Parse._isNullOrUndefined(options.at) ?
this.models.length : options.at;
this.models.splice.apply(this.models, [index, 0].concat(models));
if (this.comparator) {
this.sort({silent: true});
}
if (options.silent) {
return this;
}
for (i = 0, length = this.models.length; i < length; i++) {
model = this.models[i];
if (cids[model.cid]) {
options.index = i;
model.trigger('add', model, this, options);
}
}
return this;
},
/**
* Remove a model, or a list of models from the set. Pass silent to avoid
* firing the <code>remove</code> event for every model removed.
*/
remove: function(models, options) {
var i, l, index, model;
options = options || {};
models = _.isArray(models) ? models.slice() : [models];
for (i = 0, l = models.length; i < l; i++) {
model = this.getByCid(models[i]) || this.get(models[i]);
if (!model) {
continue;
}
delete this._byId[model.id];
delete this._byCid[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
/**
* Gets a model from the set by id.
*/
get: function(id) {
return id && this._byId[id.id || id];
},
/**
* Gets a model from the set by client id.
*/
getByCid: function(cid) {
return cid && this._byCid[cid.cid || cid];
},
/**
* Gets the model at the given index.
*/
at: function(index) {
return this.models[index];
},
/**
* Forces the collection to re-sort itself. You don't need to call this
* under normal circumstances, as the set will maintain sort order as each
* item is added.
*/
sort: function(options) {
options = options || {};
if (!this.comparator) {
throw new Error('Cannot sort a set without a comparator');
}
var boundComparator = _.bind(this.comparator, this);
if (this.comparator.length === 1) {
this.models = this.sortBy(boundComparator);
} else {
this.models.sort(boundComparator);
}
if (!options.silent) {
this.trigger('reset', this, options);
}
return this;
},
/**
* Plucks an attribute from each model in the collection.
*/
pluck: function(attr) {
return _.map(this.models, function(model){ return model.get(attr); });
},
/**
* When you have more items than you want to add or remove individually,
* you can reset the entire set with a new list of models, without firing
* any `add` or `remove` events. Fires `reset` when finished.
*/
reset: function(models, options) {
var self = this;
models = models || [];
options = options || {};
Parse._arrayEach(this.models, function(model) {
self._removeReference(model);
});
this._reset();
this.add(models, {silent: true, parse: options.parse});
if (!options.silent) {
this.trigger('reset', this, options);
}
return this;
},
/**
* Fetches the default set of models for this collection, resetting the
* collection when they arrive. If `add: true` is passed, appends the
* models to the collection instead of resetting.
*/
fetch: function(options) {
options = _.clone(options) || {};
if (options.parse === undefined) {
options.parse = true;
}
var collection = this;
var query = this.query || new Parse.Query(this.model);
return query.find().then(function(results) {
if (options.add) {
collection.add(results, options);
} else {
collection.reset(results, options);
}
return collection;
})._thenRunCallbacks(options, this);
},
/**
* Creates a new instance of a model in this collection. Add the model to
* the collection immediately, unless `wait: true` is passed, in which case
* we wait for the server to agree.
*/
create: function(model, options) {
var coll = this;
options = options ? _.clone(options) : {};
model = this._prepareModel(model, options);
if (!model) {
return false;
}
if (!options.wait) {
coll.add(model, options);
}
var success = options.success;
options.success = function(nextModel, resp, xhr) {
if (options.wait) {
coll.add(nextModel, options);
}
if (success) {
success(nextModel, resp);
} else {
nextModel.trigger('sync', model, resp, options);
}
};
model.save(null, options);
return model;
},
/**
* Converts a response into a list of models to be added to the collection.
* The default implementation is just to pass it through.
* @ignore
*/
parse: function(resp, xhr) {
return resp;
},
/**
* Proxy to _'s chain. Can't be proxied the same way the rest of the
* underscore methods are proxied because it relies on the underscore
* constructor.
*/
chain: function() {
return _(this.models).chain();
},
/**
* Reset all internal state. Called when the collection is reset.
*/
_reset: function(options) {
this.length = 0;
this.models = [];
this._byId = {};
this._byCid = {};
},
/**
* Prepare a model or hash of attributes to be added to this collection.
*/
_prepareModel: function(model, options) {
if (!(model instanceof Parse.Object)) {
var attrs = model;
options.collection = this;
model = new this.model(attrs, options);
if (!model._validate(model.attributes, options)) {
model = false;
}
} else if (!model.collection) {
model.collection = this;
}
return model;
},
/**
* Internal method to remove a model's ties to a collection.
*/
_removeReference: function(model) {
if (this === model.collection) {
delete model.collection;
}
model.off('all', this._onModelEvent, this);
},
/**
* Internal method called every time a model in the set fires an event.
* Sets need to update their indexes when models change ids. All other
* events simply proxy through. "add" and "remove" events that originate
* in other collections are ignored.
*/
_onModelEvent: function(ev, model, collection, options) {
if ((ev === 'add' || ev === 'remove') && collection !== this) {
return;
}
if (ev === 'destroy') {
this.remove(model, options);
}
if (model && ev === 'change:objectId') {
delete this._byId[model.previous("objectId")];
this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
// Underscore methods that we want to implement on the Collection.
var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find',
'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any',
'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex',
'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf',
'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
// Mix in each Underscore method as a proxy to `Collection#models`.
Parse._arrayEach(methods, function(method) {
Parse.Collection.prototype[method] = function() {
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});
/**
* Creates a new subclass of <code>Parse.Collection</code>. For example,<pre>
* var MyCollection = Parse.Collection.extend({
* // Instance properties
*
* model: MyClass,
* query: MyQuery,
*
* getFirst: function() {
* return this.at(0);
* }
* }, {
* // Class properties
*
* makeOne: function() {
* return new MyCollection();
* }
* });
*
* var collection = new MyCollection();
* </pre>
*
* @function
* @param {Object} instanceProps Instance properties for the collection.
* @param {Object} classProps Class properies for the collection.
* @return {Class} A new subclass of <code>Parse.Collection</code>.
*/
Parse.Collection.extend = Parse._extend;
}(this));
/*global _: false, document: false */
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Creating a Parse.View creates its initial element outside of the DOM,
* if an existing element is not provided...
* @class
*
* <p>A fork of Backbone.View, provided for your convenience. If you use this
* class, you must also include jQuery, or another library that provides a
* jQuery-compatible $ function. For more information, see the
* <a href="http://documentcloud.github.com/backbone/#View">Backbone
* documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
Parse.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
// Cached regex to split keys for `delegate`.
var eventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
// TODO: include objectId, createdAt, updatedAt?
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes',
'className', 'tagName'];
// Set up all inheritable **Parse.View** properties and methods.
_.extend(Parse.View.prototype, Parse.Events,
/** @lends Parse.View.prototype */ {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
/**
* jQuery delegate for element lookup, scoped to DOM elements within the
* current view. This should be prefered to global lookups where possible.
*/
$: function(selector) {
return this.$el.find(selector);
},
/**
* Initialize is an empty function by default. Override it with your own
* initialization logic.
*/
initialize: function(){},
/**
* The core function that your view should override, in order
* to populate its element (`this.el`), with the appropriate HTML. The
* convention is for **render** to always return `this`.
*/
render: function() {
return this;
},
/**
* Remove this view from the DOM. Note that the view isn't present in the
* DOM by default, so calling this method may be a no-op.
*/
remove: function() {
this.$el.remove();
return this;
},
/**
* For small amounts of DOM Elements, where a full-blown template isn't
* needed, use **make** to manufacture elements, one at a time.
* <pre>
* var el = this.make('li', {'class': 'row'},
* this.model.escape('title'));</pre>
*/
make: function(tagName, attributes, content) {
var el = document.createElement(tagName);
if (attributes) {
Parse.$(el).attr(attributes);
}
if (content) {
Parse.$(el).html(content);
}
return el;
},
/**
* Changes the view's element (`this.el` property), including event
* re-delegation.
*/
setElement: function(element, delegate) {
this.$el = Parse.$(element);
this.el = this.$el[0];
if (delegate !== false) {
this.delegateEvents();
}
return this;
},
/**
* Set callbacks. <code>this.events</code> is a hash of
* <pre>
* *{"event selector": "callback"}*
*
* {
* 'mousedown .title': 'edit',
* 'click .button': 'save'
* 'click .open': function(e) { ... }
* }
* </pre>
* pairs. Callbacks will be bound to the view, with `this` set properly.
* Uses event delegation for efficiency.
* Omitting the selector binds the event to `this.el`.
* This only works for delegate-able events: not `focus`, `blur`, and
* not `change`, `submit`, and `reset` in Internet Explorer.
*/
delegateEvents: function(events) {
events = events || Parse._getValue(this, 'events');
if (!events) {
return;
}
this.undelegateEvents();
var self = this;
Parse._objectEach(events, function(method, key) {
if (!_.isFunction(method)) {
method = self[events[key]];
}
if (!method) {
throw new Error('Event "' + events[key] + '" does not exist');
}
var match = key.match(eventSplitter);
var eventName = match[1], selector = match[2];
method = _.bind(method, self);
eventName += '.delegateEvents' + self.cid;
if (selector === '') {
self.$el.bind(eventName, method);
} else {
self.$el.delegate(selector, eventName, method);
}
});
},
/**
* Clears all callbacks previously bound to the view with `delegateEvents`.
* You usually don't need to use this, but may wish to if you have multiple
* Backbone views attached to the same DOM element.
*/
undelegateEvents: function() {
this.$el.unbind('.delegateEvents' + this.cid);
},
/**
* Performs the initial configuration of a View with a set of options.
* Keys with special meaning *(model, collection, id, className)*, are
* attached directly to the view.
*/
_configure: function(options) {
if (this.options) {
options = _.extend({}, this.options, options);
}
var self = this;
_.each(viewOptions, function(attr) {
if (options[attr]) {
self[attr] = options[attr];
}
});
this.options = options;
},
/**
* Ensure that the View has a DOM element to render into.
* If `this.el` is a string, pass it through `$()`, take the first
* matching element, and re-assign it to `el`. Otherwise, create
* an element from the `id`, `className` and `tagName` properties.
*/
_ensureElement: function() {
if (!this.el) {
var attrs = Parse._getValue(this, 'attributes') || {};
if (this.id) {
attrs.id = this.id;
}
if (this.className) {
attrs['class'] = this.className;
}
this.setElement(this.make(this.tagName, attrs), false);
} else {
this.setElement(this.el, false);
}
}
});
/**
* @function
* @param {Object} instanceProps Instance properties for the view.
* @param {Object} classProps Class properies for the view.
* @return {Class} A new subclass of <code>Parse.View</code>.
*/
Parse.View.extend = Parse._extend;
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* @class
*
* <p>A Parse.User object is a local representation of a user persisted to the
* Parse cloud. This class is a subclass of a Parse.Object, and retains the
* same functionality of a Parse.Object, but also extends it with various
* user specific methods, like authentication, signing up, and validation of
* uniqueness.</p>
*/
Parse.User = Parse.Object.extend("_User", /** @lends Parse.User.prototype */ {
// Instance Variables
_isCurrentUser: false,
// Instance Methods
/**
* Internal method to handle special fields in a _User response.
*/
_mergeMagicFields: function(attrs) {
if (attrs.sessionToken) {
this._sessionToken = attrs.sessionToken;
delete attrs.sessionToken;
}
Parse.User.__super__._mergeMagicFields.call(this, attrs);
},
/**
* Removes null values from authData (which exist temporarily for
* unlinking)
*/
_cleanupAuthData: function() {
if (!this.isCurrent()) {
return;
}
var authData = this.get('authData');
if (!authData) {
return;
}
Parse._objectEach(this.get('authData'), function(value, key) {
if (!authData[key]) {
delete authData[key];
}
});
},
/**
* Synchronizes authData for all providers.
*/
_synchronizeAllAuthData: function() {
var authData = this.get('authData');
if (!authData) {
return;
}
var self = this;
Parse._objectEach(this.get('authData'), function(value, key) {
self._synchronizeAuthData(key);
});
},
/**
* Synchronizes auth data for a provider (e.g. puts the access token in the
* right place to be used by the Facebook SDK).
*/
_synchronizeAuthData: function(provider) {
if (!this.isCurrent()) {
return;
}
var authType;
if (_.isString(provider)) {
authType = provider;
provider = Parse.User._authProviders[authType];
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData');
if (!authData || !provider) {
return;
}
var success = provider.restoreAuthentication(authData[authType]);
if (!success) {
this._unlinkFrom(provider);
}
},
_handleSaveResult: function(makeCurrent) {
// Clean up and synchronize the authData object, removing any unset values
if (makeCurrent) {
this._isCurrentUser = true;
}
this._cleanupAuthData();
this._synchronizeAllAuthData();
// Don't keep the password around.
delete this._serverData.password;
this._rebuildEstimatedDataForKey("password");
this._refreshCache();
if (makeCurrent || this.isCurrent()) {
Parse.User._saveCurrentUser(this);
}
},
/**
* Unlike in the Android/iOS SDKs, logInWith is unnecessary, since you can
* call linkWith on the user (even if it doesn't exist yet on the server).
*/
_linkWith: function(provider, options) {
var authType;
if (_.isString(provider)) {
authType = provider;
provider = Parse.User._authProviders[provider];
} else {
authType = provider.getAuthType();
}
if (_.has(options, 'authData')) {
var authData = this.get('authData') || {};
authData[authType] = options.authData;
this.set('authData', authData);
// Overridden so that the user can be made the current user.
var newOptions = _.clone(options) || {};
newOptions.success = function(model) {
model._handleSaveResult(true);
if (options.success) {
options.success.apply(this, arguments);
}
};
return this.save({'authData': authData}, newOptions);
} else {
var self = this;
var promise = new Parse.Promise();
provider.authenticate({
success: function(provider, result) {
self._linkWith(provider, {
authData: result,
success: options.success,
error: options.error
}).then(function() {
promise.resolve(self);
});
},
error: function(provider, error) {
if (options.error) {
options.error(self, error);
}
promise.reject(error);
}
});
return promise;
}
},
/**
* Unlinks a user from a service.
*/
_unlinkFrom: function(provider, options) {
var authType;
if (_.isString(provider)) {
authType = provider;
provider = Parse.User._authProviders[provider];
} else {
authType = provider.getAuthType();
}
var newOptions = _.clone(options);
var self = this;
newOptions.authData = null;
newOptions.success = function(model) {
self._synchronizeAuthData(provider);
if (options.success) {
options.success.apply(this, arguments);
}
};
return this._linkWith(provider, newOptions);
},
/**
* Checks whether a user is linked to a service.
*/
_isLinked: function(provider) {
var authType;
if (_.isString(provider)) {
authType = provider;
} else {
authType = provider.getAuthType();
}
var authData = this.get('authData') || {};
return !!authData[authType];
},
/**
* Deauthenticates all providers.
*/
_logOutWithAll: function() {
var authData = this.get('authData');
if (!authData) {
return;
}
var self = this;
Parse._objectEach(this.get('authData'), function(value, key) {
self._logOutWith(key);
});
},
/**
* Deauthenticates a single provider (e.g. removing access tokens from the
* Facebook SDK).
*/
_logOutWith: function(provider) {
if (!this.isCurrent()) {
return;
}
if (_.isString(provider)) {
provider = Parse.User._authProviders[provider];
}
if (provider && provider.deauthenticate) {
provider.deauthenticate();
}
},
/**
* Signs up a new user. You should call this instead of save for
* new Parse.Users. This will create a new Parse.User on the server, and
* also persist the session on disk so that you can access the user using
* <code>current</code>.
*
* <p>A username and password must be set before calling signUp.</p>
*
* <p>Calls options.success or options.error on completion.</p>
*
* @param {Object} attrs Extra fields to set on the new user, or null.
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is fulfilled when the signup
* finishes.
* @see Parse.User.signUp
*/
signUp: function(attrs, options) {
var error;
options = options || {};
var username = (attrs && attrs.username) || this.get("username");
if (!username || (username === "")) {
error = new Parse.Error(
Parse.Error.OTHER_CAUSE,
"Cannot sign up user with an empty name.");
if (options && options.error) {
options.error(this, error);
}
return Parse.Promise.error(error);
}
var password = (attrs && attrs.password) || this.get("password");
if (!password || (password === "")) {
error = new Parse.Error(
Parse.Error.OTHER_CAUSE,
"Cannot sign up user with an empty password.");
if (options && options.error) {
options.error(this, error);
}
return Parse.Promise.error(error);
}
// Overridden so that the user can be made the current user.
var newOptions = _.clone(options);
newOptions.success = function(model) {
model._handleSaveResult(true);
if (options.success) {
options.success.apply(this, arguments);
}
};
return this.save(attrs, newOptions);
},
/**
* Logs in a Parse.User. On success, this saves the session to localStorage,
* so you can retrieve the currently logged in user using
* <code>current</code>.
*
* <p>A username and password must be set before calling logIn.</p>
*
* <p>Calls options.success or options.error on completion.</p>
*
* @param {Object} options A Backbone-style options object.
* @see Parse.User.logIn
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the login is complete.
*/
logIn: function(options) {
var model = this;
var request = Parse._request("login", null, null, "GET", this.toJSON());
return request.then(function(resp, status, xhr) {
var serverAttrs = model.parse(resp, status, xhr);
model._finishFetch(serverAttrs);
model._handleSaveResult(true);
return model;
})._thenRunCallbacks(options, this);
},
/**
* @see Parse.Object#save
*/
save: function(arg1, arg2, arg3) {
var i, attrs, current, options, saved;
if (_.isObject(arg1) || _.isNull(arg1) || _.isUndefined(arg1)) {
attrs = arg1;
options = arg2;
} else {
attrs = {};
attrs[arg1] = arg2;
options = arg3;
}
options = options || {};
var newOptions = _.clone(options);
newOptions.success = function(model) {
model._handleSaveResult(false);
if (options.success) {
options.success.apply(this, arguments);
}
};
return Parse.Object.prototype.save.call(this, attrs, newOptions);
},
/**
* @see Parse.Object#fetch
*/
fetch: function(options) {
var newOptions = options ? _.clone(options) : {};
newOptions.success = function(model) {
model._handleSaveResult(false);
if (options && options.success) {
options.success.apply(this, arguments);
}
};
return Parse.Object.prototype.fetch.call(this, newOptions);
},
/**
* Returns true if <code>current</code> would return this user.
* @see Parse.User#current
*/
isCurrent: function() {
return this._isCurrentUser;
},
/**
* Returns get("username").
* @return {String}
* @see Parse.Object#get
*/
getUsername: function() {
return this.get("username");
},
/**
* Calls set("username", username, options) and returns the result.
* @param {String} username
* @param {Object} options A Backbone-style options object.
* @return {Boolean}
* @see Parse.Object.set
*/
setUsername: function(username, options) {
return this.set("username", username, options);
},
/**
* Calls set("password", password, options) and returns the result.
* @param {String} password
* @param {Object} options A Backbone-style options object.
* @return {Boolean}
* @see Parse.Object.set
*/
setPassword: function(password, options) {
return this.set("password", password, options);
},
/**
* Returns get("email").
* @return {String}
* @see Parse.Object#get
*/
getEmail: function() {
return this.get("email");
},
/**
* Calls set("email", email, options) and returns the result.
* @param {String} email
* @param {Object} options A Backbone-style options object.
* @return {Boolean}
* @see Parse.Object.set
*/
setEmail: function(email, options) {
return this.set("email", email, options);
},
/**
* Checks whether this user is the current user and has been authenticated.
* @return (Boolean) whether this user is the current user and is logged in.
*/
authenticated: function() {
return !!this._sessionToken &&
(Parse.User.current() && Parse.User.current().id === this.id);
}
}, /** @lends Parse.User */ {
// Class Variables
// The currently logged-in user.
_currentUser: null,
// Whether currentUser is known to match the serialized version on disk.
// This is useful for saving a localstorage check if you try to load
// _currentUser frequently while there is none stored.
_currentUserMatchesDisk: false,
// The localStorage key suffix that the current user is stored under.
_CURRENT_USER_KEY: "currentUser",
// The mapping of auth provider names to actual providers
_authProviders: {},
// Class Methods
/**
* Signs up a new user with a username (or email) and password.
* This will create a new Parse.User on the server, and also persist the
* session in localStorage so that you can access the user using
* {@link #current}.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @param {String} username The username (or email) to sign up with.
* @param {String} password The password to sign up with.
* @param {Object} attrs Extra fields to set on the new user.
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the signup completes.
* @see Parse.User#signUp
*/
signUp: function(username, password, attrs, options) {
attrs = attrs || {};
attrs.username = username;
attrs.password = password;
var user = Parse.Object._create("_User");
return user.signUp(attrs, options);
},
/**
* Logs in a user with a username (or email) and password. On success, this
* saves the session to disk, so you can retrieve the currently logged in
* user using <code>current</code>.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @param {String} username The username (or email) to log in with.
* @param {String} password The password to log in with.
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is fulfilled with the user when
* the login completes.
* @see Parse.User#logIn
*/
logIn: function(username, password, options) {
var user = Parse.Object._create("_User");
user._finishFetch({ username: username, password: password });
return user.logIn(options);
},
/**
* Logs out the currently logged in user session. This will remove the
* session from disk, log out of linked services, and future calls to
* <code>current</code> will return <code>null</code>.
*/
logOut: function() {
if (Parse.User._currentUser !== null) {
Parse.User._currentUser._logOutWithAll();
Parse.User._currentUser._isCurrentUser = false;
}
Parse.User._currentUserMatchesDisk = true;
Parse.User._currentUser = null;
Parse.localStorage.removeItem(
Parse._getParsePath(Parse.User._CURRENT_USER_KEY));
},
/**
* Requests a password reset email to be sent to the specified email address
* associated with the user account. This email allows the user to securely
* reset their password on the Parse site.
*
* <p>Calls options.success or options.error on completion.</p>
*
* @param {String} email The email address associated with the user that
* forgot their password.
* @param {Object} options A Backbone-style options object.
*/
requestPasswordReset: function(email, options) {
var json = { email: email };
var request = Parse._request("requestPasswordReset", null, null, "POST",
json);
return request._thenRunCallbacks(options);
},
/**
* Retrieves the currently logged in ParseUser with a valid session,
* either from memory or localStorage, if necessary.
* @return {Parse.Object} The currently logged in Parse.User.
*/
current: function() {
if (Parse.User._currentUser) {
return Parse.User._currentUser;
}
if (Parse.User._currentUserMatchesDisk) {
// TODO: Lazily log in anonymous user.
return Parse.User._currentUser;
}
// Load the user from local storage.
Parse.User._currentUserMatchesDisk = true;
var userData = Parse.localStorage.getItem(Parse._getParsePath(
Parse.User._CURRENT_USER_KEY));
if (!userData) {
// TODO: Lazily log in anonymous user.
return null;
}
Parse.User._currentUser = Parse.Object._create("_User");
Parse.User._currentUser._isCurrentUser = true;
var json = JSON.parse(userData);
Parse.User._currentUser.id = json._id;
delete json._id;
Parse.User._currentUser._sessionToken = json._sessionToken;
delete json._sessionToken;
Parse.User._currentUser.set(json);
Parse.User._currentUser._synchronizeAllAuthData();
Parse.User._currentUser._refreshCache();
Parse.User._currentUser._opSetQueue = [{}];
return Parse.User._currentUser;
},
/**
* Persists a user as currentUser to localStorage, and into the singleton.
*/
_saveCurrentUser: function(user) {
if (Parse.User._currentUser !== user) {
Parse.User.logOut();
}
user._isCurrentUser = true;
Parse.User._currentUser = user;
Parse.User._currentUserMatchesDisk = true;
var json = user.toJSON();
json._id = user.id;
json._sessionToken = user._sessionToken;
Parse.localStorage.setItem(
Parse._getParsePath(Parse.User._CURRENT_USER_KEY),
JSON.stringify(json));
},
_registerAuthenticationProvider: function(provider) {
Parse.User._authProviders[provider.getAuthType()] = provider;
// Synchronize the current user with the auth provider.
if (Parse.User.current()) {
Parse.User.current()._synchronizeAuthData(provider.getAuthType());
}
},
_logInWith: function(provider, options) {
var user = Parse.Object._create("_User");
return user._linkWith(provider, options);
}
});
}(this));
// Parse.Query is a way to create a list of Parse.Objects.
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Creates a new parse Parse.Query for the given Parse.Object subclass.
* @param objectClass -
* An instance of a subclass of Parse.Object, or a Parse className string.
* @class
*
* <p>Parse.Query defines a query that is used to fetch Parse.Objects. The
* most common use case is finding all objects that match a query through the
* <code>find</code> method. For example, this sample code fetches all objects
* of class <code>MyClass</code>. It calls a different function depending on
* whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.find({
* success: function(results) {
* // results is an array of Parse.Object.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to retrieve a single object whose id is
* known, through the get method. For example, this sample code fetches an
* object of class <code>MyClass</code> and id <code>myId</code>. It calls a
* different function depending on whether the fetch succeeded or not.
*
* <pre>
* var query = new Parse.Query(MyClass);
* query.get(myId, {
* success: function(object) {
* // object is an instance of Parse.Object.
* },
*
* error: function(object, error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*
* <p>A Parse.Query can also be used to count the number of objects that match
* the query without retrieving all of those objects. For example, this
* sample code counts the number of objects of the class <code>MyClass</code>
* <pre>
* var query = new Parse.Query(MyClass);
* query.count({
* success: function(number) {
* // There are number instances of MyClass.
* },
*
* error: function(error) {
* // error is an instance of Parse.Error.
* }
* });</pre></p>
*/
Parse.Query = function(objectClass) {
if (_.isString(objectClass)) {
objectClass = Parse.Object._getSubclass(objectClass);
}
this.objectClass = objectClass;
this.className = objectClass.prototype.className;
this._where = {};
this._include = [];
this._limit = -1; // negative limit means, do not send a limit
this._skip = 0;
this._extraOptions = {};
};
/**
* Constructs a Parse.Query that is the OR of the passed in queries. For
* example:
* <pre>var compoundQuery = Parse.Query.or(query1, query2, query3);</pre>
*
* will create a compoundQuery that is an or of the query1, query2, and
* query3.
* @param {...Parse.Query} var_args The list of queries to OR.
* @return {Parse.Query} The query that is the OR of the passed in queries.
*/
Parse.Query.or = function() {
var queries = _.toArray(arguments);
var className = null;
Parse._arrayEach(queries, function(q) {
if (_.isNull(className)) {
className = q.className;
}
if (className !== q.className) {
throw "All queries must be for the same class";
}
});
var query = new Parse.Query(className);
query._orQuery(queries);
return query;
};
Parse.Query.prototype = {
/**
* Constructs a Parse.Object whose id is already known by fetching data from
* the server. Either options.success or options.error is called when the
* find completes.
*
* @param {} objectId The id of the object to be fetched.
* @param {Object} options A Backbone-style options object.
*/
get: function(objectId, options) {
var self = this;
self.equalTo('objectId', objectId);
return self.first().then(function(response) {
if (response) {
return response;
}
var errorObject = new Parse.Error(Parse.Error.OBJECT_NOT_FOUND,
"Object not found.");
return Parse.Promise.error(errorObject);
})._thenRunCallbacks(options, null);
},
/**
* Returns a JSON representation of this query.
* @return {Object}
*/
toJSON: function() {
var params = {
where: this._where
};
if (this._include.length > 0) {
params.include = this._include.join(",");
}
if (this._select) {
params.keys = this._select.join(",");
}
if (this._limit >= 0) {
params.limit = this._limit;
}
if (this._skip > 0) {
params.skip = this._skip;
}
if (this._order !== undefined) {
params.order = this._order;
}
Parse._objectEach(this._extraOptions, function(v, k) {
params[k] = v;
});
return params;
},
/**
* Retrieves a list of ParseObjects that satisfy this query.
* Either options.success or options.error is called when the find
* completes.
*
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is resolved with the results when
* the query completes.
*/
find: function(options) {
var self = this;
var request = Parse._request("classes", this.className, null, "GET",
this.toJSON());
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj;
if (response.className) {
obj = new Parse.Object(response.className);
} else {
obj = new self.objectClass();
}
obj._finishFetch(json, true);
return obj;
});
})._thenRunCallbacks(options);
},
/**
* Counts the number of objects that match this query.
* Either options.success or options.error is called when the count
* completes.
*
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is resolved with the count when
* the query completes.
*/
count: function(options) {
var params = this.toJSON();
params.limit = 0;
params.count = 1;
var request = Parse._request("classes", this.className, null, "GET",
params);
return request.then(function(response) {
return response.count;
})._thenRunCallbacks(options);
},
/**
* Retrieves at most one Parse.Object that satisfies this query.
*
* Either options.success or options.error is called when it completes.
* success is passed the object if there is one. otherwise, undefined.
*
* @param {Object} options A Backbone-style options object.
* @return {Parse.Promise} A promise that is resolved with the object when
* the query completes.
*/
first: function(options) {
var self = this;
var params = this.toJSON();
params.limit = 1;
var request = Parse._request("classes", this.className, null, "GET",
params);
return request.then(function(response) {
return _.map(response.results, function(json) {
var obj = new self.objectClass();
obj._finishFetch(json, true);
return obj;
})[0];
})._thenRunCallbacks(options);
},
/**
* Returns a new instance of Parse.Collection backed by this query.
* @return {Parse.Collection}
*/
collection: function(items, options) {
options = options || {};
return new Parse.Collection(items, _.extend(options, {
model: this.objectClass,
query: this
}));
},
/**
* Sets the number of results to skip before returning any results.
* This is useful for pagination.
* Default is to skip zero results.
* @param {Number} n the number of results to skip.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
skip: function(n) {
this._skip = n;
return this;
},
/**
* Sets the limit of the number of results to return. The default limit is
* 100, with a maximum of 1000 results being returned at a time.
* @param {Number} n the number of results to limit to.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
limit: function(n) {
this._limit = n;
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be equal to the provided value.
* @param {String} key The key to check.
* @param value The value that the Parse.Object must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
equalTo: function(key, value) {
this._where[key] = Parse._encode(value);
return this;
},
/**
* Helper for condition queries
*/
_addCondition: function(key, condition, value) {
// Check if we already have a condition
if (!this._where[key]) {
this._where[key] = {};
}
this._where[key][condition] = Parse._encode(value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be not equal to the provided value.
* @param {String} key The key to check.
* @param value The value that must not be equalled.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
notEqualTo: function(key, value) {
this._addCondition(key, "$ne", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be less than the provided value.
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
lessThan: function(key, value) {
this._addCondition(key, "$lt", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be greater than the provided value.
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThan: function(key, value) {
this._addCondition(key, "$gt", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be less than or equal to the provided value.
* @param {String} key The key to check.
* @param value The value that provides an upper bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
lessThanOrEqualTo: function(key, value) {
this._addCondition(key, "$lte", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be greater than or equal to the provided value.
* @param {String} key The key to check.
* @param value The value that provides an lower bound.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
greaterThanOrEqualTo: function(key, value) {
this._addCondition(key, "$gte", value);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* be contained in the provided list of values.
* @param {String} key The key to check.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
containedIn: function(key, values) {
this._addCondition(key, "$in", values);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* not be contained in the provided list of values.
* @param {String} key The key to check.
* @param {Array} values The values that will not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
notContainedIn: function(key, values) {
this._addCondition(key, "$nin", values);
return this;
},
/**
* Add a constraint to the query that requires a particular key's value to
* contain each one of the provided list of values.
* @param {String} key The key to check. This key's value must be an array.
* @param {Array} values The values that will match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
containsAll: function(key, values) {
this._addCondition(key, "$all", values);
return this;
},
/**
* Add a constraint for finding objects that contain the given key.
* @param {String} key The key that should exist.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
exists: function(key) {
this._addCondition(key, "$exists", true);
return this;
},
/**
* Add a constraint for finding objects that do not contain a given key.
* @param {String} key The key that should not exist
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotExist: function(key) {
this._addCondition(key, "$exists", false);
return this;
},
/**
* Add a regular expression constraint for finding string values that match
* the provided regular expression.
* This may be slow for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {RegExp} regex The regular expression pattern to match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matches: function(key, regex, modifiers) {
this._addCondition(key, "$regex", regex);
if (!modifiers) { modifiers = ""; }
// Javascript regex options support mig as inline options but store them
// as properties of the object. We support mi & should migrate them to
// modifiers
if (regex.ignoreCase) { modifiers += 'i'; }
if (regex.multiline) { modifiers += 'm'; }
if (modifiers && modifiers.length) {
this._addCondition(key, "$options", modifiers);
}
return this;
},
/**
* Add a constraint that requires that a key's value matches a Parse.Query
* constraint.
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matchesQuery: function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$inQuery", queryJSON);
return this;
},
/**
* Add a constraint that requires that a key's value not matches a
* Parse.Query constraint.
* @param {String} key The key that the contains the object to match the
* query.
* @param {Parse.Query} query The query that should not match.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchQuery: function(key, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$notInQuery", queryJSON);
return this;
},
/**
* Add a constraint that requires that a key's value matches a value in
* an object returned by a different Parse.Query.
* @param {String} key The key that contains the value that is being
* matched.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
matchesKeyInQuery: function(key, queryKey, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$select",
{ key: queryKey, query: queryJSON });
return this;
},
/**
* Add a constraint that requires that a key's value not match a value in
* an object returned by a different Parse.Query.
* @param {String} key The key that contains the value that is being
* excluded.
* @param {String} queryKey The key in the objects returned by the query to
* match against.
* @param {Parse.Query} query The query to run.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
doesNotMatchKeyInQuery: function(key, queryKey, query) {
var queryJSON = query.toJSON();
queryJSON.className = query.className;
this._addCondition(key, "$dontSelect",
{ key: queryKey, query: queryJSON });
return this;
},
/**
* Add constraint that at least one of the passed in queries matches.
* @param {Array} queries
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
_orQuery: function(queries) {
var queryJSON = _.map(queries, function(q) {
return q.toJSON().where;
});
this._where.$or = queryJSON;
return this;
},
/**
* Converts a string into a regex that matches it.
* Surrounding with \Q .. \E does this, we just need to escape \E's in
* the text separately.
*/
_quote: function(s) {
return "\\Q" + s.replace("\\E", "\\E\\\\E\\Q") + "\\E";
},
/**
* Add a constraint for finding string values that contain a provided
* string. This may be slow for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {String} substring The substring that the value must contain.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
contains: function(key, value) {
this._addCondition(key, "$regex", this._quote(value));
return this;
},
/**
* Add a constraint for finding string values that start with a provided
* string. This query will use the backend index, so it will be fast even
* for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {String} prefix The substring that the value must start with.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
startsWith: function(key, value) {
this._addCondition(key, "$regex", "^" + this._quote(value));
return this;
},
/**
* Add a constraint for finding string values that end with a provided
* string. This will be slow for large datasets.
* @param {String} key The key that the string to match is stored in.
* @param {String} suffix The substring that the value must end with.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
endsWith: function(key, value) {
this._addCondition(key, "$regex", this._quote(value) + "$");
return this;
},
/**
* Sorts the results in ascending order by the given key.
*
* @param {String} key The key to order by.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
ascending: function(key) {
this._order = key;
return this;
},
/**
* Sorts the results in descending order by the given key.
*
* @param {String} key The key to order by.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
descending: function(key) {
this._order = "-" + key;
return this;
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given.
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
near: function(key, point) {
if (!(point instanceof Parse.GeoPoint)) {
// Try to cast it to a GeoPoint, so that near("loc", [20,30]) works.
point = new Parse.GeoPoint(point);
}
this._addCondition(key, "$nearSphere", point);
return this;
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param maxDistance Maximum distance (in radians) of results to return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinRadians: function(key, point, distance) {
this.near(key, point);
this._addCondition(key, "$maxDistance", distance);
return this;
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 3958.8 miles.
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in miles) of results to
* return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinMiles: function(key, point, distance) {
return this.withinRadians(key, point, distance / 3958.8);
},
/**
* Add a proximity based constraint for finding objects with key point
* values near the point given and within the maximum distance given.
* Radius of earth used is 6371.0 kilometers.
* @param {String} key The key that the Parse.GeoPoint is stored in.
* @param {Parse.GeoPoint} point The reference Parse.GeoPoint that is used.
* @param {Number} maxDistance Maximum distance (in kilometers) of results
* to return.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinKilometers: function(key, point, distance) {
return this.withinRadians(key, point, distance / 6371.0);
},
/**
* Add a constraint to the query that requires a particular key's
* coordinates be contained within a given rectangular geographic bounding
* box.
* @param {String} key The key to be constrained.
* @param {Parse.GeoPoint} southwest
* The lower-left inclusive corner of the box.
* @param {Parse.GeoPoint} northeast
* The upper-right inclusive corner of the box.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
withinGeoBox: function(key, southwest, northeast) {
if (!(southwest instanceof Parse.GeoPoint)) {
southwest = new Parse.GeoPoint(southwest);
}
if (!(northeast instanceof Parse.GeoPoint)) {
northeast = new Parse.GeoPoint(northeast);
}
this._addCondition(key, '$within', { '$box': [southwest, northeast] });
return this;
},
/**
* Include nested Parse.Objects for the provided key. You can use dot
* notation to specify which fields in the included object are also fetch.
* @param {String} key The name of the key to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
include: function() {
var self = this;
Parse._arrayEach(arguments, function(key) {
if (_.isArray(key)) {
self._include = self._include.concat(key);
} else {
self._include.push(key);
}
});
return this;
},
/**
* Restrict the fields of the returned Parse.Objects to include only the
* provided keys. If this is called multiple times, then all of the keys
* specified in each of the calls will be included.
* @param {Array} keys The names of the keys to include.
* @return {Parse.Query} Returns the query, so you can chain this call.
*/
select: function() {
var self = this;
this._select = this._select || [];
Parse._arrayEach(arguments, function(key) {
if (_.isArray(key)) {
self._select = self._select.concat(key);
} else {
self._select.push(key);
}
});
return this;
},
/**
* Iterates over each result of a query, calling a callback for each one. If
* the callback returns a promise, the iteration will not continue until
* that promise has been fulfilled. If the callback returns a rejected
* promise, then iteration will stop with that error. The items are
* processed in an unspecified order. The query may not have any sort order,
* and may not use limit or skip.
* @param callback {Function} Callback that will be called with each result
* of the query.
* @param options {Object} An optional Backbone-like options object with
* success and error callbacks that will be invoked once the iteration
* has finished.
* @return {Parse.Promise} A promise that will be fulfilled once the
* iteration has completed.
*/
each: function(callback, options) {
options = options || {};
if (this._order || this._skip || (this._limit >= 0)) {
var error =
"Cannot iterate on a query with sort, skip, or limit.";
return Parse.Promise.error(error)._thenRunCallbacks(options);
}
var promise = new Parse.Promise();
var query = new Parse.Query(this.objectClass);
// We can override the batch size from the options.
// This is undocumented, but useful for testing.
query._limit = options.batchSize || 100;
query._where = _.clone(this._where);
query._include = _.clone(this._include);
query.ascending('objectId');
var finished = false;
return Parse.Promise._continueWhile(function() {
return !finished;
}, function() {
return query.find().then(function(results) {
var callbacksDone = Parse.Promise.as();
Parse._.each(results, function(result) {
callbacksDone = callbacksDone.then(function() {
return callback(result);
});
});
return callbacksDone.then(function() {
if (results.length >= query._limit) {
query.greaterThan("objectId", results[results.length - 1].id);
} else {
finished = true;
}
});
});
})._thenRunCallbacks(options);
}
};
}(this));
/*global FB: false , console: false*/
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
var PUBLIC_KEY = "*";
var initialized = false;
var requestedPermissions;
var initOptions;
var provider = {
authenticate: function(options) {
var self = this;
FB.login(function(response) {
if (response.authResponse) {
if (options.success) {
options.success(self, {
id: response.authResponse.userID,
access_token: response.authResponse.accessToken,
expiration_date: new Date(response.authResponse.expiresIn * 1000 +
(new Date()).getTime()).toJSON()
});
}
} else {
if (options.error) {
options.error(self, response);
}
}
}, {
scope: requestedPermissions
});
},
restoreAuthentication: function(authData) {
if (authData) {
var authResponse = {
userID: authData.id,
accessToken: authData.access_token,
expiresIn: (Parse._parseDate(authData.expiration_date).getTime() -
(new Date()).getTime()) / 1000
};
var newOptions = _.clone(initOptions);
newOptions.authResponse = authResponse;
// Suppress checks for login status from the browser.
newOptions.status = false;
FB.init(newOptions);
}
return true;
},
getAuthType: function() {
return "facebook";
},
deauthenticate: function() {
this.restoreAuthentication(null);
FB.logout();
}
};
/**
* Provides a set of utilities for using Parse with Facebook.
* @namespace
* Provides a set of utilities for using Parse with Facebook.
*/
Parse.FacebookUtils = {
/**
* Initializes Parse Facebook integration. Call this function after you
* have loaded the Facebook Javascript SDK with the same parameters
* as you would pass to<code>
* <a href=
* "https://developers.facebook.com/docs/reference/javascript/FB.init/">
* FB.init()</a></code>. Parse.FacebookUtils will invoke FB.init() for you
* with these arguments.
*
* @param {Object} options Facebook options argument as described here:
* <a href=
* "https://developers.facebook.com/docs/reference/javascript/FB.init/">
* FB.init()</a>. The status flag will be coerced to 'false' because it
* interferes with Parse Facebook integration. Call FB.getLoginStatus()
* explicitly if this behavior is required by your application.
*/
init: function(options) {
if (typeof(FB) === 'undefined') {
throw "The Facebook JavaScript SDK must be loaded before calling init.";
}
initOptions = _.clone(options) || {};
if (initOptions.status && typeof(console) !== "undefined") {
var warn = console.warn || console.log || function() {};
warn.call(console, "The 'status' flag passed into" +
" FB.init, when set to true, can interfere with Parse Facebook" +
" integration, so it has been suppressed. Please call" +
" FB.getLoginStatus() explicitly if you require this behavior.");
}
initOptions.status = false;
FB.init(initOptions);
Parse.User._registerAuthenticationProvider(provider);
initialized = true;
},
/**
* Gets whether the user has their account linked to Facebook.
*
* @param {Parse.User} user User to check for a facebook link.
* The user must be logged in on this device.
* @return {Boolean} <code>true</code> if the user has their account
* linked to Facebook.
*/
isLinked: function(user) {
return user._isLinked("facebook");
},
/**
* Logs in a user using Facebook. This method delegates to the Facebook
* SDK to authenticate the user, and then automatically logs in (or
* creates, in the case where it is a new user) a Parse.User.
*
* @param {String, Object} permissions The permissions required for Facebook
* log in. This is a comma-separated string of permissions.
* Alternatively, supply a Facebook authData object as described in our
* REST API docs if you want to handle getting facebook auth tokens
* yourself.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
logIn: function(permissions, options) {
if (!permissions || _.isString(permissions)) {
if (!initialized) {
throw "You must initialize FacebookUtils before calling logIn.";
}
requestedPermissions = permissions;
return Parse.User._logInWith("facebook", options);
} else {
var newOptions = _.clone(options) || {};
newOptions.authData = permissions;
return Parse.User._logInWith("facebook", newOptions);
}
},
/**
* Links Facebook to an existing PFUser. This method delegates to the
* Facebook SDK to authenticate the user, and then automatically links
* the account to the Parse.User.
*
* @param {Parse.User} user User to link to Facebook. This must be the
* current user.
* @param {String, Object} permissions The permissions required for Facebook
* log in. This is a comma-separated string of permissions.
* Alternatively, supply a Facebook authData object as described in our
* REST API docs if you want to handle getting facebook auth tokens
* yourself.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
link: function(user, permissions, options) {
if (!permissions || _.isString(permissions)) {
if (!initialized) {
throw "You must initialize FacebookUtils before calling link.";
}
requestedPermissions = permissions;
return user._linkWith("facebook", options);
} else {
var newOptions = _.clone(options) || {};
newOptions.authData = permissions;
return user._linkWith("facebook", newOptions);
}
},
/**
* Unlinks the Parse.User from a Facebook account.
*
* @param {Parse.User} user User to unlink from Facebook. This must be the
* current user.
* @param {Object} options Standard options object with success and error
* callbacks.
*/
unlink: function(user, options) {
if (!initialized) {
throw "You must initialize FacebookUtils before calling unlink.";
}
return user._unlinkFrom("facebook", options);
}
};
}(this));
/*global _: false, document: false, window: false, navigator: false */
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* History serves as a global router (per frame) to handle hashchange
* events or pushState, match the appropriate route, and trigger
* callbacks. You shouldn't ever have to create one of these yourself
* — you should use the reference to <code>Parse.history</code>
* that will be created for you automatically if you make use of
* Routers with routes.
* @class
*
* <p>A fork of Backbone.History, provided for your convenience. If you
* use this class, you must also include jQuery, or another library
* that provides a jQuery-compatible $ function. For more information,
* see the <a href="http://documentcloud.github.com/backbone/#History">
* Backbone documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
Parse.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
};
// Cached regex for cleaning leading hashes and slashes .
var routeStripper = /^[#\/]/;
// Cached regex for detecting MSIE.
var isExplorer = /msie [\w.]+/;
// Has the history handling already been started?
Parse.History.started = false;
// Set up all inheritable **Parse.History** properties and methods.
_.extend(Parse.History.prototype, Parse.Events,
/** @lends Parse.History.prototype */ {
// The default interval to poll for hash changes, if necessary, is
// twenty times a second.
interval: 50,
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(windowOverride) {
var loc = windowOverride ? windowOverride.location : window.location;
var match = loc.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (Parse._isNullOrUndefined(fragment)) {
if (this._hasPushState || forcePushState) {
fragment = window.location.pathname;
var search = window.location.search;
if (search) {
fragment += search;
}
} else {
fragment = this.getHash();
}
}
if (!fragment.indexOf(this.options.root)) {
fragment = fragment.substr(this.options.root.length);
}
return fragment.replace(routeStripper, '');
},
/**
* Start the hash change handling, returning `true` if the current
* URL matches an existing route, and `false` otherwise.
*/
start: function(options) {
if (Parse.History.started) {
throw new Error("Parse.history has already been started");
}
Parse.History.started = true;
// Figure out the initial configuration. Do we need an iframe?
// Is pushState desired ... is it available?
this.options = _.extend({}, {root: '/'}, this.options, options);
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
this._hasPushState = !!(this.options.pushState &&
window.history &&
window.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) &&
(!docMode || docMode <= 7));
if (oldIE) {
this.iframe = Parse.$('<iframe src="javascript:0" tabindex="-1" />')
.hide().appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
// Depending on whether we're using pushState or hashes, and whether
// 'onhashchange' is supported, determine how we check the URL state.
if (this._hasPushState) {
Parse.$(window).bind('popstate', this.checkUrl);
} else if (this._wantsHashChange &&
('onhashchange' in window) &&
!oldIE) {
Parse.$(window).bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = window.setInterval(this.checkUrl,
this.interval);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = window.location;
var atRoot = loc.pathname === this.options.root;
// If we've started off with a route from a `pushState`-enabled browser,
// but we're currently in a browser that doesn't support it...
if (this._wantsHashChange &&
this._wantsPushState &&
!this._hasPushState &&
!atRoot) {
this.fragment = this.getFragment(null, true);
window.location.replace(this.options.root + '#' + this.fragment);
// Return immediately as browser will do redirect to new url
return true;
// Or if we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
} else if (this._wantsPushState &&
this._hasPushState &&
atRoot &&
loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
window.history.replaceState({}, document.title,
loc.protocol + '//' + loc.host + this.options.root + this.fragment);
}
if (!this.options.silent) {
return this.loadUrl();
}
},
// Disable Parse.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
Parse.$(window).unbind('popstate', this.checkUrl)
.unbind('hashchange', this.checkUrl);
window.clearInterval(this._checkUrlInterval);
Parse.History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`, normalizing across the hidden iframe.
checkUrl: function(e) {
var current = this.getFragment();
if (current === this.fragment && this.iframe) {
current = this.getFragment(this.getHash(this.iframe));
}
if (current === this.fragment) {
return false;
}
if (this.iframe) {
this.navigate(current);
}
if (!this.loadUrl()) {
this.loadUrl(this.getHash());
}
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the
// history.
navigate: function(fragment, options) {
if (!Parse.History.started) {
return false;
}
if (!options || options === true) {
options = {trigger: options};
}
var frag = (fragment || '').replace(routeStripper, '');
if (this.fragment === frag) {
return;
}
// If pushState is available, we use it to set the fragment as a real URL.
if (this._hasPushState) {
if (frag.indexOf(this.options.root) !== 0) {
frag = this.options.root + frag;
}
this.fragment = frag;
var replaceOrPush = options.replace ? 'replaceState' : 'pushState';
window.history[replaceOrPush]({}, document.title, frag);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this.fragment = frag;
this._updateHash(window.location, frag, options.replace);
if (this.iframe &&
(frag !== this.getFragment(this.getHash(this.iframe)))) {
// Opening and closing the iframe tricks IE7 and earlier
// to push a history entry on hash-tag change.
// When replace is true, we don't want this.
if (!options.replace) {
this.iframe.document.open().close();
}
this._updateHash(this.iframe.location, frag, options.replace);
}
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
window.location.assign(this.options.root + fragment);
}
if (options.trigger) {
this.loadUrl(fragment);
}
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var s = location.toString().replace(/(javascript:|#).*$/, '');
location.replace(s + '#' + fragment);
} else {
location.hash = fragment;
}
}
});
}(this));
/*global _: false*/
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* Routers map faux-URLs to actions, and fire events when routes are
* matched. Creating a new one sets its `routes` hash, if not set statically.
* @class
*
* <p>A fork of Backbone.Router, provided for your convenience.
* For more information, see the
* <a href="http://documentcloud.github.com/backbone/#Router">Backbone
* documentation</a>.</p>
* <p><strong><em>Available in the client SDK only.</em></strong></p>
*/
Parse.Router = function(options) {
options = options || {};
if (options.routes) {
this.routes = options.routes;
}
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var namedParam = /:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-\[\]{}()+?.,\\\^\$\|#\s]/g;
// Set up all inheritable **Parse.Router** properties and methods.
_.extend(Parse.Router.prototype, Parse.Events,
/** @lends Parse.Router.prototype */ {
/**
* Initialize is an empty function by default. Override it with your own
* initialization logic.
*/
initialize: function(){},
/**
* Manually bind a single named route to a callback. For example:
*
* <pre>this.route('search/:query/p:num', 'search', function(query, num) {
* ...
* });</pre>
*/
route: function(route, name, callback) {
Parse.history = Parse.history || new Parse.History();
if (!_.isRegExp(route)) {
route = this._routeToRegExp(route);
}
if (!callback) {
callback = this[name];
}
Parse.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
if (callback) {
callback.apply(this, args);
}
this.trigger.apply(this, ['route:' + name].concat(args));
Parse.history.trigger('route', this, name, args);
}, this));
return this;
},
/**
* Whenever you reach a point in your application that you'd
* like to save as a URL, call navigate in order to update the
* URL. If you wish to also call the route function, set the
* trigger option to true. To update the URL without creating
* an entry in the browser's history, set the replace option
* to true.
*/
navigate: function(fragment, options) {
Parse.history.navigate(fragment, options);
},
// Bind all defined routes to `Parse.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) {
return;
}
var routes = [];
for (var route in this.routes) {
if (this.routes.hasOwnProperty(route)) {
routes.unshift([route, this.routes[route]]);
}
}
for (var i = 0, l = routes.length; i < l; i++) {
this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(namedParam, '([^\/]+)')
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted parameters.
_extractParameters: function(route, fragment) {
return route.exec(fragment).slice(1);
}
});
/**
* @function
* @param {Object} instanceProps Instance properties for the router.
* @param {Object} classProps Class properies for the router.
* @return {Class} A new subclass of <code>Parse.Router</code>.
*/
Parse.Router.extend = Parse._extend;
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
var _ = Parse._;
/**
* @namespace Contains functions for calling and declaring
* <a href="/docs/cloud_code_guide#functions">cloud functions</a>.
* <p><strong><em>
* Some functions are only available from Cloud Code.
* </em></strong></p>
*/
Parse.Cloud = Parse.Cloud || {};
_.extend(Parse.Cloud, /** @lends Parse.Cloud */ {
/**
* Makes a call to a cloud function.
* @param {String} name The function name.
* @param {Object} data The parameters to send to the cloud function.
* @param {Object} options A Backbone-style options object
* options.success, if set, should be a function to handle a successful
* call to a cloud function. options.error should be a function that
* handles an error running the cloud function. Both functions are
* optional. Both functions take a single argument.
* @return {Parse.Promise} A promise that will be resolved with the result
* of the function.
*/
run: function(name, data, options) {
var request = Parse._request("functions", name, null, 'POST',
Parse._encode(data, null, true));
return request.then(function(resp) {
return Parse._decode(null, resp).result;
})._thenRunCallbacks(options);
}
});
}(this));
(function(root) {
root.Parse = root.Parse || {};
var Parse = root.Parse;
Parse.Installation = Parse.Object.extend("_Installation");
/**
* Contains functions to deal with Push in Parse
* @name Parse.Push
* @namespace
*/
Parse.Push = Parse.Push || {};
/**
* Sends a push notification.
* @param {Object} data - The data of the push notification. Valid fields
* are:
* <ol>
* <li>channels - An Array of channels to push to.</li>
* <li>push_time - A Date object for when to send the push.</li>
* <li>expiration_time - A Date object for when to expire
* the push.</li>
* <li>expiration_interval - The seconds from now to expire the push.</li>
* <li>where - A Parse.Query over Parse.Installation that is used to match
* a set of installations to push to.</li>
* <li>data - The data to send as part of the push</li>
* <ol>
* @param {Object} options An object that has an optional success function,
* that takes no arguments and will be called on a successful push, and
* an error function that takes a Parse.Error and will be called if the push
* failed.
*/
Parse.Push.send = function(data, options) {
if (data.where) {
data.where = data.where.toJSON().where;
}
if (data.push_time) {
data.push_time = data.push_time.toJSON();
}
if (data.expiration_time) {
data.expiration_time = data.expiration_time.toJSON();
}
if (data.expiration_time && data.expiration_time_interval) {
throw "Both expiration_time and expiration_time_interval can't be set";
}
var request = Parse._request('push', null, null, 'POST', data);
return request._thenRunCallbacks(options);
};
}(this));
| mit |
ranr01/Presentations | MathJax/unpacked/jax/input/MathML/entities/l.js | 4723 | /*************************************************************
*
* MathJax/jax/output/HTML-CSS/entities/l.js
*
* Copyright (c) 2010-2017 The MathJax Consortium
*
* 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.
*
*/
(function (MATHML) {
MathJax.Hub.Insert(MATHML.Parse.Entity,{
'LJcy': '\u0409',
'LT': '\u003C',
'Lacute': '\u0139',
'Lang': '\u27EA',
'Laplacetrf': '\u2112',
'Lcaron': '\u013D',
'Lcedil': '\u013B',
'Lcy': '\u041B',
'LeftArrowBar': '\u21E4',
'LeftDoubleBracket': '\u27E6',
'LeftDownTeeVector': '\u2961',
'LeftDownVectorBar': '\u2959',
'LeftRightVector': '\u294E',
'LeftTeeArrow': '\u21A4',
'LeftTeeVector': '\u295A',
'LeftTriangleBar': '\u29CF',
'LeftUpDownVector': '\u2951',
'LeftUpTeeVector': '\u2960',
'LeftUpVectorBar': '\u2958',
'LeftVectorBar': '\u2952',
'LessLess': '\u2AA1',
'Lmidot': '\u013F',
'LowerLeftArrow': '\u2199',
'LowerRightArrow': '\u2198',
'Lstrok': '\u0141',
'Lt': '\u226A',
'lAarr': '\u21DA',
'lArr': '\u21D0',
'lAtail': '\u291B',
'lBarr': '\u290E',
'lE': '\u2266',
'lHar': '\u2962',
'lacute': '\u013A',
'laemptyv': '\u29B4',
'lagran': '\u2112',
'lang': '\u27E8',
'langd': '\u2991',
'langle': '\u27E8',
'laquo': '\u00AB',
'larr': '\u2190',
'larrb': '\u21E4',
'larrbfs': '\u291F',
'larrfs': '\u291D',
'larrhk': '\u21A9',
'larrpl': '\u2939',
'larrsim': '\u2973',
'lat': '\u2AAB',
'latail': '\u2919',
'late': '\u2AAD',
'lates': '\u2AAD\uFE00',
'lbarr': '\u290C',
'lbbrk': '\u2772',
'lbrke': '\u298B',
'lbrksld': '\u298F',
'lbrkslu': '\u298D',
'lcaron': '\u013E',
'lcedil': '\u013C',
'lceil': '\u2308',
'lcub': '\u007B',
'lcy': '\u043B',
'ldca': '\u2936',
'ldquo': '\u201C',
'ldquor': '\u201E',
'ldrdhar': '\u2967',
'ldrushar': '\u294B',
'ldsh': '\u21B2',
'leftarrow': '\u2190',
'leftarrowtail': '\u21A2',
'leftharpoondown': '\u21BD',
'leftharpoonup': '\u21BC',
'leftrightarrow': '\u2194',
'leftrightarrows': '\u21C6',
'leftrightharpoons': '\u21CB',
'leftrightsquigarrow': '\u21AD',
'leg': '\u22DA',
'leq': '\u2264',
'leqq': '\u2266',
'leqslant': '\u2A7D',
'les': '\u2A7D',
'lescc': '\u2AA8',
'lesdot': '\u2A7F',
'lesdoto': '\u2A81',
'lesdotor': '\u2A83',
'lesg': '\u22DA\uFE00',
'lesges': '\u2A93',
'lessapprox': '\u2A85',
'lesseqgtr': '\u22DA',
'lesseqqgtr': '\u2A8B',
'lessgtr': '\u2276',
'lesssim': '\u2272',
'lfisht': '\u297C',
'lfloor': '\u230A',
'lg': '\u2276',
'lgE': '\u2A91',
'lhard': '\u21BD',
'lharu': '\u21BC',
'lharul': '\u296A',
'lhblk': '\u2584',
'ljcy': '\u0459',
'll': '\u226A',
'llarr': '\u21C7',
'llcorner': '\u231E',
'llhard': '\u296B',
'lltri': '\u25FA',
'lmidot': '\u0140',
'lmoustache': '\u23B0',
'lnapprox': '\u2A89',
'lneq': '\u2A87',
'lneqq': '\u2268',
'loang': '\u27EC',
'loarr': '\u21FD',
'lobrk': '\u27E6',
'longleftarrow': '\u27F5',
'longleftrightarrow': '\u27F7',
'longrightarrow': '\u27F6',
'looparrowleft': '\u21AB',
'lopar': '\u2985',
'loplus': '\u2A2D',
'lotimes': '\u2A34',
'lowbar': '\u005F',
'lozenge': '\u25CA',
'lozf': '\u29EB',
'lpar': '\u0028',
'lparlt': '\u2993',
'lrarr': '\u21C6',
'lrcorner': '\u231F',
'lrhar': '\u21CB',
'lrhard': '\u296D',
'lrm': '\u200E',
'lrtri': '\u22BF',
'lsaquo': '\u2039',
'lsh': '\u21B0',
'lsim': '\u2272',
'lsime': '\u2A8D',
'lsimg': '\u2A8F',
'lsqb': '\u005B',
'lsquo': '\u2018',
'lsquor': '\u201A',
'lstrok': '\u0142',
'ltcc': '\u2AA6',
'ltcir': '\u2A79',
'ltdot': '\u22D6',
'lthree': '\u22CB',
'ltlarr': '\u2976',
'ltquest': '\u2A7B',
'ltrPar': '\u2996',
'ltrie': '\u22B4',
'ltrif': '\u25C2',
'lurdshar': '\u294A',
'luruhar': '\u2966',
'lvertneqq': '\u2268\uFE00',
'lvnE': '\u2268\uFE00'
});
MathJax.Ajax.loadComplete(MATHML.entityDir+"/l.js");
})(MathJax.InputJax.MathML);
| mit |
dnozay/testlink-code | third_party/tinymce/jscripts/tiny_mce/plugins/xhtmlxtras/jscripts/abbr.js | 653 | /**
* $Id: abbr.js,v 1.1 2007/12/03 08:53:30 franciscom Exp $
*
* @author Moxiecode - based on work by Andrew Tetlaw
* @copyright Copyright © 2004-2007, Moxiecode Systems AB, All rights reserved.
*/
function preinit() {
// Initialize
tinyMCE.setWindowArg('mce_windowresize', false);
}
function init() {
tinyMCEPopup.resizeToInnerSize();
SXE.initElementDialog('abbr');
if (SXE.currentAction == "update") {
SXE.showRemoveButton();
}
}
function insertAbbr() {
SXE.insertElement(tinyMCE.isIE && !tinyMCE.isOpera ? 'html:ABBR' : 'abbr');
tinyMCEPopup.close();
}
function removeAbbr() {
SXE.removeElement('abbr');
tinyMCEPopup.close();
} | gpl-2.0 |
RikoOphorst/blowbox-2017 | deps/assimp-4.0.0/code/FBXDocumentUtil.cpp | 4586 | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file FBXDocumentUtil.cpp
* @brief Implementation of the FBX DOM utility functions declared in FBXDocumentUtil.h
*/
#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
#include "FBXParser.h"
#include "FBXDocument.h"
#include "FBXUtil.h"
#include "FBXDocumentUtil.h"
#include "FBXProperties.h"
namespace Assimp {
namespace FBX {
namespace Util {
// ------------------------------------------------------------------------------------------------
// signal DOM construction error, this is always unrecoverable. Throws DeadlyImportError.
void DOMError(const std::string& message, const Token& token)
{
throw DeadlyImportError(Util::AddTokenText("FBX-DOM",message,&token));
}
// ------------------------------------------------------------------------------------------------
void DOMError(const std::string& message, const Element* element /*= NULL*/)
{
if(element) {
DOMError(message,element->KeyToken());
}
throw DeadlyImportError("FBX-DOM " + message);
}
// ------------------------------------------------------------------------------------------------
// print warning, do return
void DOMWarning(const std::string& message, const Token& token)
{
if(DefaultLogger::get()) {
DefaultLogger::get()->warn(Util::AddTokenText("FBX-DOM",message,&token));
}
}
// ------------------------------------------------------------------------------------------------
void DOMWarning(const std::string& message, const Element* element /*= NULL*/)
{
if(element) {
DOMWarning(message,element->KeyToken());
return;
}
if(DefaultLogger::get()) {
DefaultLogger::get()->warn("FBX-DOM: " + message);
}
}
// ------------------------------------------------------------------------------------------------
// fetch a property table and the corresponding property template
std::shared_ptr<const PropertyTable> GetPropertyTable(const Document& doc,
const std::string& templateName,
const Element &element,
const Scope& sc,
bool no_warn /*= false*/)
{
const Element* const Properties70 = sc["Properties70"];
std::shared_ptr<const PropertyTable> templateProps = std::shared_ptr<const PropertyTable>(
static_cast<const PropertyTable*>(NULL));
if(templateName.length()) {
PropertyTemplateMap::const_iterator it = doc.Templates().find(templateName);
if(it != doc.Templates().end()) {
templateProps = (*it).second;
}
}
if(!Properties70) {
if(!no_warn) {
DOMWarning("property table (Properties70) not found",&element);
}
if(templateProps) {
return templateProps;
}
else {
return std::make_shared<const PropertyTable>();
}
}
return std::make_shared<const PropertyTable>(*Properties70,templateProps);
}
} // !Util
} // !FBX
} // !Assimp
#endif
| gpl-3.0 |
jlspyaozhongkai/Uter | third_party_backup/binutils-2.25/gold/testsuite/pie_copyrelocs_test.cc | 1090 | // pie_coprelocs_test.cc -- a test case for gold
// Copyright (C) 2014 Free Software Foundation, Inc.
// Written by Sriraman Tallam <[email protected]>.
// This file is part of gold.
// 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.
// Check if copy relocs are used to access globals below when -fpie is
// is not used to compile but -pie is used to link.
extern int glob_a;
int main ()
{
return glob_a - 128;
}
| gpl-3.0 |
blois/AndroidSDKCloneMin | ndk/tests/device/test-stlport/unit/cmath_test.cpp | 7079 | #define _STLP_DO_IMPORT_CSTD_FUNCTIONS
#include <limits>
#include <cmath>
//We also test math functions imported from stdlib.h or
//defined in cstdlib
#include <cstdlib>
#include "math_aux.h"
#include "cppunit/cppunit_proxy.h"
//This test purpose is to check the right import of math.h C symbols
//into the std namespace so we do not use the using namespace std
//specification
//
// TestCase class
//
class CMathTest : public CPPUNIT_NS::TestCase
{
CPPUNIT_TEST_SUITE(CMathTest);
#if defined (STLPORT) && !defined (_STLP_USE_NAMESPACES)
CPPUNIT_IGNORE;
#endif
CPPUNIT_TEST(import_checks);
CPPUNIT_TEST_SUITE_END();
protected:
void import_checks();
};
CPPUNIT_TEST_SUITE_REGISTRATION(CMathTest);
//
// tests implementation
//
void CMathTest::import_checks()
{
#if !defined (STLPORT) || defined (_STLP_USE_NAMESPACES)
int int_val = -1;
long long_val = -1l;
float float_val = -1.0f;
double double_val = -1.0;
# if !defined (_STLP_NO_LONG_DOUBLE)
long double long_double_val = -1.0l;
# endif
CPPUNIT_CHECK( are_equals(std::abs(int_val), -int_val) );
CPPUNIT_CHECK( are_equals(std::abs(long_val), -long_val) );
CPPUNIT_CHECK( are_equals(std::labs(long_val), -long_val) );
CPPUNIT_CHECK( are_equals(std::abs(float_val), -float_val) );
CPPUNIT_CHECK( are_equals(std::abs(double_val), -double_val) );
# if !defined (_STLP_NO_LONG_DOUBLE)
CPPUNIT_CHECK( are_equals(std::abs(long_double_val), -long_double_val) );
# endif
CPPUNIT_CHECK( are_equals(std::fabs(float_val), -float_val) );
CPPUNIT_CHECK( are_equals(std::fabs(double_val), -double_val) );
# if !defined (_STLP_NO_LONG_DOUBLE)
CPPUNIT_CHECK( are_equals(std::fabs(long_double_val), -long_double_val) );
# endif
std::div_t div_res = std::div(3, 2);
CPPUNIT_CHECK( div_res.quot == 1 );
CPPUNIT_CHECK( div_res.rem == 1 );
std::ldiv_t ldiv_res = std::ldiv(3l, 2l);
CPPUNIT_CHECK( ldiv_res.quot == 1l );
CPPUNIT_CHECK( ldiv_res.rem == 1l );
ldiv_res = std::div(3l, 2l);
CPPUNIT_CHECK( ldiv_res.quot == 1l );
CPPUNIT_CHECK( ldiv_res.rem == 1l );
std::srand(2);
int rand_val = std::rand();
CPPUNIT_CHECK( rand_val >= 0 && rand_val <= RAND_MAX );
CPPUNIT_CHECK( are_equals(std::floor(1.5), 1.0) );
CPPUNIT_CHECK( are_equals(std::ceil(1.5), 2.0) );
CPPUNIT_CHECK( are_equals(std::fmod(1.5, 1.0), 0.5) );
CPPUNIT_CHECK( are_equals(std::sqrt(4.0), 2.0) );
CPPUNIT_CHECK( are_equals(std::pow(2.0, 2), 4.0) );
/*
* Uncomment the following to check that it generates an ambiguous call
* as there is no Standard pow(int, int) function only pow(double, int),
* pow(float, int) and some others...
* If it do not generate a compile time error it should at least give
* the good result.
*/
//CPPUNIT_CHECK( are_equals(std::pow(10, -2), 0.01) );
CPPUNIT_CHECK( are_equals(std::pow(10.0, -2), 0.01) );
CPPUNIT_CHECK( are_equals(std::exp(0.0), 1.0) );
CPPUNIT_CHECK( are_equals(std::log(std::exp(1.0)), 1.0) );
CPPUNIT_CHECK( are_equals(std::log10(100.0), 2.0) );
# if !defined (STLPORT) || !defined (_STLP_USING_PLATFORM_SDK_COMPILER) || !defined (_WIN64)
CPPUNIT_CHECK( are_equals(std::modf(100.5, &double_val), 0.5) );
CPPUNIT_CHECK( are_equals(double_val, 100.0) );
# endif
double_val = std::frexp(8.0, &int_val);
CPPUNIT_CHECK( are_equals(double_val * std::pow(2.0, int_val), 8.0) );
CPPUNIT_CHECK( are_equals(std::ldexp(1.0, 2), 4.0) );
CPPUNIT_CHECK( are_equals(std::cos(std::acos(1.0)), 1.0) );
CPPUNIT_CHECK( are_equals(std::sin(std::asin(1.0)), 1.0) );
CPPUNIT_CHECK( are_equals(std::tan(std::atan(1.0)), 1.0) );
CPPUNIT_CHECK( are_equals(std::tan(std::atan2(1.0, 1.0)), 1.0) );
CPPUNIT_CHECK( are_equals(std::cosh(0.0), 1.0) );
CPPUNIT_CHECK( are_equals(std::sinh(0.0), 0.0) );
# if !defined (STLPORT) || !defined (_STLP_USING_PLATFORM_SDK_COMPILER) || !defined (_M_AMD64)
CPPUNIT_CHECK( are_equals(std::tanh(0.0), 0.0) );
# endif
CPPUNIT_CHECK( are_equals(std::floor(1.5f), 1.0f) );
CPPUNIT_CHECK( are_equals(std::ceil(1.5f), 2.0f) );
CPPUNIT_CHECK( are_equals(std::fmod(1.5f, 1.0f), 0.5f) );
CPPUNIT_CHECK( are_equals(std::sqrt(4.0f), 2.0f) );
CPPUNIT_CHECK( are_equals(std::pow(2.0f, 2), 4.0f) );
CPPUNIT_CHECK( are_equals(std::exp(0.0f), 1.0f) );
CPPUNIT_CHECK( are_equals(std::log(std::exp(1.0f)), 1.0f) );
CPPUNIT_CHECK( are_equals(std::log10(100.0f), 2.0f) );
# if !defined (STLPORT) || !defined (_STLP_USING_PLATFORM_SDK_COMPILER) || !defined (_WIN64)
CPPUNIT_CHECK( are_equals(std::modf(100.5f, &float_val), 0.5f) );
CPPUNIT_CHECK( are_equals(float_val, 100.0f) );
# endif
float_val = std::frexp(8.0f, &int_val);
CPPUNIT_CHECK( are_equals(float_val * std::pow(2.0f, int_val), 8.0f) );
CPPUNIT_CHECK( are_equals(std::ldexp(1.0f, 2), 4.0f) );
CPPUNIT_CHECK( are_equals(std::cos(std::acos(1.0f)), 1.0f) );
CPPUNIT_CHECK( are_equals(std::sin(std::asin(1.0f)), 1.0f) );
CPPUNIT_CHECK( are_equals(std::tan(std::atan(1.0f)), 1.0f) );
CPPUNIT_CHECK( are_equals(std::tan(std::atan2(1.0f, 1.0f)), 1.0f) );
CPPUNIT_CHECK( are_equals(std::cosh(0.0f), 1.0f) );
CPPUNIT_CHECK( are_equals(std::sinh(0.0f), 0.0f) );
# if !defined (STLPORT) || !defined (_STLP_USING_PLATFORM_SDK_COMPILER) || !defined (_M_AMD64)
CPPUNIT_CHECK( are_equals(std::tanh(0.0f), 0.0f) );
# endif
# if !defined (_STLP_NO_LONG_DOUBLE)
CPPUNIT_CHECK( are_equals(std::floor(1.5l), 1.0l) );
CPPUNIT_CHECK( are_equals(std::ceil(1.5l), 2.0l) );
CPPUNIT_CHECK( are_equals(std::fmod(1.5l, 1.0l), 0.5l) );
CPPUNIT_CHECK( are_equals(std::sqrt(4.0l), 2.0l) );
CPPUNIT_CHECK( are_equals(std::pow(2.0l, 2), 4.0l) );
CPPUNIT_CHECK( are_equals(std::exp(0.0l), 1.0l) );
CPPUNIT_CHECK( are_equals(std::log(std::exp(1.0l)), 1.0l) );
CPPUNIT_CHECK( are_equals(std::log10(100.0l), 2.0l) );
# if !defined (STLPORT) || !defined (_STLP_USING_PLATFORM_SDK_COMPILER) || !defined (_WIN64)
CPPUNIT_CHECK( are_equals(std::modf(100.5l, &long_double_val), 0.5l) );
CPPUNIT_CHECK( are_equals(long_double_val, 100.0l) );
# endif
long_double_val = std::frexp(8.0l, &int_val);
CPPUNIT_CHECK( are_equals(long_double_val * std::pow(2.0l, int_val), 8.0l) );
CPPUNIT_CHECK( are_equals(std::ldexp(1.0l, 2), 4.0l) );
CPPUNIT_CHECK( are_equals(std::cos(std::acos(1.0l)), 1.0l) );
CPPUNIT_CHECK( are_equals(std::sin(std::asin(1.0l)), 1.0l) );
CPPUNIT_CHECK( are_equals(std::tan(0.0l), 0.0l) );
CPPUNIT_CHECK( are_equals(std::atan(0.0l), 0.0l) );
CPPUNIT_CHECK( are_equals(std::atan2(0.0l, 1.0l), 0.0l) );
CPPUNIT_CHECK( are_equals(std::cosh(0.0l), 1.0l) );
CPPUNIT_CHECK( are_equals(std::sinh(0.0l), 0.0l) );
# if !defined (STLPORT) || !defined (_STLP_USING_PLATFORM_SDK_COMPILER) || !defined (_M_AMD64)
CPPUNIT_CHECK( are_equals(std::tanh(0.0l), 0.0l) );
# endif
# endif
CPPUNIT_CHECK( are_equals(std::sqrt(std::sqrt(std::sqrt(256.0))), 2.0) );
CPPUNIT_CHECK( are_equals(std::sqrt(std::sqrt(std::sqrt(256.0f))), 2.0f) );
# if !defined (_STLP_NO_LONG_DOUBLE)
CPPUNIT_CHECK( are_equals(std::sqrt(std::sqrt(std::sqrt(256.0l))), 2.0l) );
# endif
#endif
}
| apache-2.0 |
scheib/chromium | third_party/blink/web_tests/external/wpt/workers/interfaces/WorkerGlobalScope/onerror/propagate-to-window-onerror.js | 28 | function x() {
y();
}
x(); | bsd-3-clause |
growbots/mysqld_exporter | vendor/github.com/prometheus/client_golang/prometheus/untyped.go | 4957 | // Copyright 2014 The Prometheus Authors
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package prometheus
// Untyped is a Metric that represents a single numerical value that can
// arbitrarily go up and down.
//
// An Untyped metric works the same as a Gauge. The only difference is that to
// no type information is implied.
//
// To create Untyped instances, use NewUntyped.
type Untyped interface {
Metric
Collector
// Set sets the Untyped metric to an arbitrary value.
Set(float64)
// Inc increments the Untyped metric by 1.
Inc()
// Dec decrements the Untyped metric by 1.
Dec()
// Add adds the given value to the Untyped metric. (The value can be
// negative, resulting in a decrease.)
Add(float64)
// Sub subtracts the given value from the Untyped metric. (The value can
// be negative, resulting in an increase.)
Sub(float64)
}
// UntypedOpts is an alias for Opts. See there for doc comments.
type UntypedOpts Opts
// NewUntyped creates a new Untyped metric from the provided UntypedOpts.
func NewUntyped(opts UntypedOpts) Untyped {
return newValue(NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
nil,
opts.ConstLabels,
), UntypedValue, 0)
}
// UntypedVec is a Collector that bundles a set of Untyped metrics that all
// share the same Desc, but have different values for their variable
// labels. This is used if you want to count the same thing partitioned by
// various dimensions. Create instances with NewUntypedVec.
type UntypedVec struct {
MetricVec
}
// NewUntypedVec creates a new UntypedVec based on the provided UntypedOpts and
// partitioned by the given label names. At least one label name must be
// provided.
func NewUntypedVec(opts UntypedOpts, labelNames []string) *UntypedVec {
desc := NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
labelNames,
opts.ConstLabels,
)
return &UntypedVec{
MetricVec: MetricVec{
children: map[uint64]Metric{},
desc: desc,
newMetric: func(lvs ...string) Metric {
return newValue(desc, UntypedValue, 0, lvs...)
},
},
}
}
// GetMetricWithLabelValues replaces the method of the same name in
// MetricVec. The difference is that this method returns an Untyped and not a
// Metric so that no type conversion is required.
func (m *UntypedVec) GetMetricWithLabelValues(lvs ...string) (Untyped, error) {
metric, err := m.MetricVec.GetMetricWithLabelValues(lvs...)
if metric != nil {
return metric.(Untyped), err
}
return nil, err
}
// GetMetricWith replaces the method of the same name in MetricVec. The
// difference is that this method returns an Untyped and not a Metric so that no
// type conversion is required.
func (m *UntypedVec) GetMetricWith(labels Labels) (Untyped, error) {
metric, err := m.MetricVec.GetMetricWith(labels)
if metric != nil {
return metric.(Untyped), err
}
return nil, err
}
// WithLabelValues works as GetMetricWithLabelValues, but panics where
// GetMetricWithLabelValues would have returned an error. By not returning an
// error, WithLabelValues allows shortcuts like
// myVec.WithLabelValues("404", "GET").Add(42)
func (m *UntypedVec) WithLabelValues(lvs ...string) Untyped {
return m.MetricVec.WithLabelValues(lvs...).(Untyped)
}
// With works as GetMetricWith, but panics where GetMetricWithLabels would have
// returned an error. By not returning an error, With allows shortcuts like
// myVec.With(Labels{"code": "404", "method": "GET"}).Add(42)
func (m *UntypedVec) With(labels Labels) Untyped {
return m.MetricVec.With(labels).(Untyped)
}
// UntypedFunc is an Untyped whose value is determined at collect time by
// calling a provided function.
//
// To create UntypedFunc instances, use NewUntypedFunc.
type UntypedFunc interface {
Metric
Collector
}
// NewUntypedFunc creates a new UntypedFunc based on the provided
// UntypedOpts. The value reported is determined by calling the given function
// from within the Write method. Take into account that metric collection may
// happen concurrently. If that results in concurrent calls to Write, like in
// the case where an UntypedFunc is directly registered with Prometheus, the
// provided function must be concurrency-safe.
func NewUntypedFunc(opts UntypedOpts, function func() float64) UntypedFunc {
return newValueFunc(NewDesc(
BuildFQName(opts.Namespace, opts.Subsystem, opts.Name),
opts.Help,
nil,
opts.ConstLabels,
), UntypedValue, function)
}
| apache-2.0 |
dbartolini/crown | 3rdparty/bgfx/3rdparty/spirv-tools/source/reduce/merge_blocks_reduction_opportunity_finder.cpp | 1734 | // Copyright (c) 2019 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.
#include "source/reduce/merge_blocks_reduction_opportunity_finder.h"
#include "source/opt/block_merge_util.h"
#include "source/reduce/merge_blocks_reduction_opportunity.h"
namespace spvtools {
namespace reduce {
std::string MergeBlocksReductionOpportunityFinder::GetName() const {
return "MergeBlocksReductionOpportunityFinder";
}
std::vector<std::unique_ptr<ReductionOpportunity>>
MergeBlocksReductionOpportunityFinder::GetAvailableOpportunities(
opt::IRContext* context, uint32_t target_function) const {
std::vector<std::unique_ptr<ReductionOpportunity>> result;
// Consider every block in every function.
for (auto* function : GetTargetFunctions(context, target_function)) {
for (auto& block : *function) {
// See whether it is possible to merge this block with its successor.
if (opt::blockmergeutil::CanMergeWithSuccessor(context, &block)) {
// It is, so record an opportunity to do this.
result.push_back(spvtools::MakeUnique<MergeBlocksReductionOpportunity>(
context, function, &block));
}
}
}
return result;
}
} // namespace reduce
} // namespace spvtools
| mit |
ViktorHofer/corefx | src/System.Runtime.Serialization.Formatters/tests/FormatterServicesTests.cs | 15173 | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using Xunit;
namespace System.Runtime.Serialization.Formatters.Tests
{
public partial class FormatterServicesTests
{
[Fact]
public void CheckTypeSecurity_Nop()
{
FormatterServices.CheckTypeSecurity(typeof(int), TypeFilterLevel.Full);
FormatterServices.CheckTypeSecurity(typeof(int), TypeFilterLevel.Low);
}
[Fact]
public void GetSerializableMembers_InvalidArguments_ThrowsException()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => FormatterServices.GetSerializableMembers(null));
}
[Fact]
public void GetSerializableMembers_Interface()
{
Assert.Equal<MemberInfo>(new MemberInfo[0], FormatterServices.GetSerializableMembers(typeof(IDisposable)));
}
[Fact]
public void GetUninitializedObject_NullType_ThrowsArgumentNullException()
{
AssertExtensions.Throws<ArgumentNullException>("type", () => FormatterServices.GetUninitializedObject(null));
AssertExtensions.Throws<ArgumentNullException>("type", () => FormatterServices.GetSafeUninitializedObject(null));
}
[Fact]
public void GetUninitializedObject_NonRuntimeType_ThrowsSerializationException()
{
Assert.Throws<SerializationException>(() => FormatterServices.GetUninitializedObject(new NonRuntimeType()));
Assert.Throws<SerializationException>(() => FormatterServices.GetSafeUninitializedObject(new NonRuntimeType()));
}
public static IEnumerable<object[]> GetUninitializedObject_NotSupportedType_TestData()
{
yield return new object[] { typeof(int[]) };
yield return new object[] { typeof(int[,]) };
yield return new object[] { typeof(int).MakePointerType() };
yield return new object[] { typeof(int).MakeByRefType() };
yield return new object[] { typeof(GenericClass<>).GetTypeInfo().GenericTypeParameters[0] };
}
[Theory]
[MemberData(nameof(GetUninitializedObject_NotSupportedType_TestData))]
public void GetUninitializedObject_NotSupportedType_ThrowsArgumentException(Type type)
{
AssertExtensions.Throws<ArgumentException>(null, () => FormatterServices.GetUninitializedObject(type));
AssertExtensions.Throws<ArgumentException>(null, () => FormatterServices.GetSafeUninitializedObject(type));
}
[Theory]
[InlineData(typeof(AbstractClass))]
[InlineData(typeof(StaticClass))]
[InlineData(typeof(Interface))]
[InlineData(typeof(Array))]
public void GetUninitializedObject_AbstractClass_ThrowsMemberAccessException(Type type)
{
Assert.Throws<MemberAccessException>(() => FormatterServices.GetUninitializedObject(type));
Assert.Throws<MemberAccessException>(() => FormatterServices.GetSafeUninitializedObject(type));
}
public abstract class AbstractClass { }
public static class StaticClass { }
public interface Interface { }
public static IEnumerable<object[]> GetUninitializedObject_OpenGenericClass_TestData()
{
yield return new object[] { typeof(GenericClass<>) };
yield return new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) };
}
[Theory]
[MemberData(nameof(GetUninitializedObject_OpenGenericClass_TestData))]
public void GetUninitializedObject_OpenGenericClass_ThrowsMemberAccessException(Type type)
{
Assert.Throws<MemberAccessException>(() => FormatterServices.GetUninitializedObject(type));
Assert.Throws<MemberAccessException>(() => FormatterServices.GetSafeUninitializedObject(type));
}
public interface IGenericClass
{
int Value { get; set; }
}
public class GenericClass<T> : IGenericClass
{
public int Value { get; set; }
}
public static IEnumerable<object[]> GetUninitializedObject_ByRefLikeType_TestData()
{
yield return new object[] { typeof(TypedReference) };
yield return new object[] { typeof(RuntimeArgumentHandle) };
// .NET Standard 2.0 doesn't have ArgIterator, but .NET Core 2.0 does
Type argIterator = typeof(object).Assembly.GetType("System.ArgIterator");
if (argIterator != null)
{
yield return new object[] { argIterator };
}
}
public static IEnumerable<object[]> GetUninitializedObject_ByRefLikeType_NetCore_TestData()
{
yield return new object[] { typeof(Span<int>) };
yield return new object[] { typeof(ReadOnlySpan<int>) };
yield return new object[] { typeof(StructWithSpanField) };
}
#pragma warning disable 0169 // The private field 'class member' is never used
private ref struct StructWithSpanField
{
Span<byte> _bytes;
int _position;
}
#pragma warning restore 0169
[Theory]
[MemberData(nameof(GetUninitializedObject_ByRefLikeType_NetCore_TestData))]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, "Some runtimes don't support or recognise Span<T>, ReadOnlySpan<T> or ByReference<T> as ref types.")]
public void GetUninitializedObject_ByRefLikeType_NetCore_ThrowsNotSupportedException(Type type)
{
Assert.Throws<NotSupportedException>(() => FormatterServices.GetUninitializedObject(type));
Assert.Throws<NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(type));
}
[Theory]
[MemberData(nameof(GetUninitializedObject_ByRefLikeType_TestData))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "full .NET Framework has bug that allows allocating instances of byref-like types.")]
public void GetUninitializedObject_ByRefLikeType_NonNetfx_ThrowsNotSupportedException(Type type)
{
Assert.Throws<NotSupportedException>(() => FormatterServices.GetUninitializedObject(type));
Assert.Throws<NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(type));
}
[Fact]
[SkipOnTargetFramework(~TargetFrameworkMonikers.Netcoreapp, "The coreclr doesn't support GetUninitializedObject for shared generic instances")]
public void GetUninitializedObject_SharedGenericInstance_NetCore_ThrowsNotSupportedException()
{
Type canonType = Type.GetType("System.__Canon");
Assert.NotNull(canonType);
Type sharedGenericInstance = typeof(GenericClass<>).MakeGenericType(canonType);
Assert.Throws<NotSupportedException>(() => FormatterServices.GetUninitializedObject(sharedGenericInstance));
Assert.Throws<NotSupportedException>(() => FormatterServices.GetSafeUninitializedObject(sharedGenericInstance));
}
[Fact]
public void GetUninitializedObject_NullableType_InitializesValue()
{
int? nullableUnsafe = (int?)FormatterServices.GetUninitializedObject(typeof(int?));
Assert.True(nullableUnsafe.HasValue);
Assert.Equal(0, nullableUnsafe.Value);
int? nullableSafe = (int?)FormatterServices.GetSafeUninitializedObject(typeof(int?));
Assert.True(nullableSafe.HasValue);
Assert.Equal(0, nullableSafe.Value);
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "The full .NET Framework doesn't support GetUninitializedObject for subclasses of ContextBoundObject")]
public void GetUninitializedObject_ContextBoundObjectSubclass_NetCore_InitializesValue()
{
Assert.Equal(0, ((ContextBoundSubclass)FormatterServices.GetUninitializedObject(typeof(ContextBoundSubclass))).Value);
Assert.Equal(0, ((ContextBoundSubclass)FormatterServices.GetSafeUninitializedObject(typeof(ContextBoundSubclass))).Value);
}
public class ContextBoundSubclass : ContextBoundObject
{
public int Value { get; set; }
}
[Fact]
public void GetUninitializedObject_TypeHasDefaultConstructor_DoesNotRunConstructor()
{
Assert.Equal(42, new ObjectWithDefaultConstructor().Value);
Assert.Equal(0, ((ObjectWithDefaultConstructor)FormatterServices.GetUninitializedObject(typeof(ObjectWithDefaultConstructor))).Value);
Assert.Equal(0, ((ObjectWithDefaultConstructor)FormatterServices.GetSafeUninitializedObject(typeof(ObjectWithDefaultConstructor))).Value);
}
private class ObjectWithDefaultConstructor
{
public ObjectWithDefaultConstructor()
{
Value = 42;
}
public int Value;
}
[Fact]
public void GetUninitializedObject_StaticConstructor_CallsStaticConstructor()
{
Assert.Equal(2, ((ObjectWithStaticConstructor)FormatterServices.GetUninitializedObject(typeof(ObjectWithStaticConstructor))).GetValue());
}
private class ObjectWithStaticConstructor
{
private static int s_value = 1;
static ObjectWithStaticConstructor()
{
s_value = 2;
}
public int GetValue() => s_value;
}
[Fact]
public void GetUninitializedObject_StaticField_InitializesStaticFields()
{
Assert.Equal(1, ((ObjectWithStaticField)FormatterServices.GetUninitializedObject(typeof(ObjectWithStaticField))).GetValue());
}
private class ObjectWithStaticField
{
private static int s_value = 1;
public int GetValue() => s_value;
}
[Fact]
public void GetUninitializedObject_StaticConstructorThrows_ThrowsTypeInitializationException()
{
TypeInitializationException ex = Assert.Throws<TypeInitializationException>(() => FormatterServices.GetUninitializedObject(typeof(StaticConstructorThrows)));
Assert.IsType<DivideByZeroException>(ex.InnerException);
}
private class StaticConstructorThrows
{
static StaticConstructorThrows()
{
throw new DivideByZeroException();
}
}
[Fact]
public void GetUninitializedObject_ClassFieldWithDefaultValue_DefaultValueIgnored()
{
Assert.Equal(42, new ObjectWithStructDefaultField().Value);
Assert.Null(((ObjectWithClassDefaultField)FormatterServices.GetUninitializedObject(typeof(ObjectWithClassDefaultField))).Value);
Assert.Null(((ObjectWithClassDefaultField)FormatterServices.GetSafeUninitializedObject(typeof(ObjectWithClassDefaultField))).Value);
}
private class ObjectWithClassDefaultField
{
public string Value = "abc";
}
[Fact]
public void GetUninitializedObject_StructFieldWithDefaultValue_DefaultValueIgnored()
{
Assert.Equal(42, new ObjectWithStructDefaultField().Value);
Assert.Equal(0, ((ObjectWithStructDefaultField)FormatterServices.GetUninitializedObject(typeof(ObjectWithStructDefaultField))).Value);
Assert.Equal(0, ((ObjectWithStructDefaultField)FormatterServices.GetSafeUninitializedObject(typeof(ObjectWithStructDefaultField))).Value);
}
private class ObjectWithStructDefaultField
{
public int Value = 42;
}
[Fact]
public void PopulateObjectMembers_InvalidArguments_ThrowsException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => FormatterServices.PopulateObjectMembers(null, new MemberInfo[0], new object[0]));
AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.PopulateObjectMembers(new object(), null, new object[0]));
AssertExtensions.Throws<ArgumentNullException>("data", () => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[0], null));
AssertExtensions.Throws<ArgumentException>(null, () => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[1], new object[2]));
AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[1], new object[1]));
Assert.Throws<SerializationException>(() => FormatterServices.PopulateObjectMembers(new object(), new MemberInfo[] { typeof(object).GetMethod("GetHashCode") }, new object[] { new object() }));
}
[Fact]
public void GetObjectData_InvalidArguments_ThrowsException()
{
AssertExtensions.Throws<ArgumentNullException>("obj", () => FormatterServices.GetObjectData(null, new MemberInfo[0]));
AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.GetObjectData(new object(), null));
AssertExtensions.Throws<ArgumentNullException>("members", () => FormatterServices.GetObjectData(new object(), new MemberInfo[1]));
Assert.Throws<SerializationException>(() => FormatterServices.GetObjectData(new object(), new MethodInfo[] { typeof(object).GetMethod("GetHashCode") }));
}
[Fact]
public void GetSurrogateForCyclicalReference_InvalidArguments_ThrowsException()
{
AssertExtensions.Throws<ArgumentNullException>("innerSurrogate", () => FormatterServices.GetSurrogateForCyclicalReference(null));
}
[Fact]
public void GetSurrogateForCyclicalReference_ValidSurrogate_GetsObject()
{
var surrogate = new NonSerializablePairSurrogate();
ISerializationSurrogate newSurrogate = FormatterServices.GetSurrogateForCyclicalReference(surrogate);
Assert.NotNull(newSurrogate);
Assert.NotSame(surrogate, newSurrogate);
}
[Fact]
public void GetTypeFromAssembly_InvalidArguments_ThrowsException()
{
AssertExtensions.Throws<ArgumentNullException>("assem", () => FormatterServices.GetTypeFromAssembly(null, "name"));
Assert.Null(FormatterServices.GetTypeFromAssembly(GetType().Assembly, Guid.NewGuid().ToString("N"))); // non-existing type doesn't throw
}
}
}
namespace System.Runtime.CompilerServices
{
// Local definition of IsByRefLikeAttribute while the real one becomes available in corefx
[AttributeUsage(AttributeTargets.Struct)]
public sealed class IsByRefLikeAttribute : Attribute
{
public IsByRefLikeAttribute()
{
}
}
}
| mit |
fengshao0907/actor-platform | actor-apps/runtime/src/main/java/im/actor/runtime/json/JSONException.java | 1139 | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
package im.actor.runtime.json;
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONException extends RuntimeException {
private static final long serialVersionUID = 0;
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
*
* @param message
* Detail about the reason for the exception.
*/
public JSONException(String message) {
super(message);
}
/**
* Constructs a new JSONException with the specified cause.
* @param cause The cause.
*/
public JSONException(Throwable cause) {
super(cause.getMessage());
this.cause = cause;
}
/**
* Returns the cause of this exception or null if the cause is nonexistent
* or unknown.
*
* @return the cause of this exception or null if the cause is nonexistent
* or unknown.
*/
@Override
public Throwable getCause() {
return this.cause;
}
}
| mit |
WY08271/node-mysql | test/unit/pool/test-end-ping.js | 983 | var common = require('../../common');
var assert = require('assert');
var pool = common.createPool({
connectionLimit : 1,
port : common.fakeServerPort,
queueLimit : 5,
waitForConnections : true
});
var conn1Err = null;
var conn2Err = null;
var poolEnded = false;
var server = common.createFakeServer();
server.listen(common.fakeServerPort, function (err) {
assert.ifError(err);
pool.getConnection(function (err, conn) {
assert.ifError(err);
conn.release();
pool.getConnection(function (err, conn) {
assert.ok(err);
assert.equal(err.message, 'Pool is closed.');
});
pool.end(function (err) {
assert.ifError(err);
server.destroy();
});
});
});
server.on('connection', function (conn) {
conn.handshake();
conn.on('ping', function () {
setTimeout(function () {
conn._sendPacket(new common.Packets.OkPacket());
conn._parser.resetPacketNumber();
}, 100);
});
});
| mit |
cdnjs/cdnjs | ajax/libs/simple-icons/5.15.0/thymeleaf.min.js | 956 | module.exports={title:"Thymeleaf",slug:"thymeleaf",svg:'<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Thymeleaf</title><path d="M1.727 0C.782 0 .02.761.02 1.707v20.586C.02 23.24.782 24 1.727 24h20.546c.945 0 1.707-.761 1.707-1.707V1.707C23.98.76 23.218 0 22.273 0H1.727zm18.714 3.273c-1.861 3.694-3.3 7.627-5.674 11.046-1.064 1.574-2.329 3.163-4.16 3.86-1.31.552-2.936.337-3.98-.647-.628-.523-.54-1.43-.173-2.075.96-1.224 2.34-2.02 3.59-2.915 3.842-2.625 7.446-5.654 10.397-9.27zm-1.693 1.25c-2.503 2.751-5.381 5.16-8.452 7.269l-.003.002-.003.003c-1.327.979-2.835 1.824-3.993 3.114-.349.333-.583 1.042-.537 1.481-.622-1.043-.8-2.614-.257-3.74.526-1.19 1.742-1.807 2.876-2.292 3.757-1.353 6.695-2.926 10.369-5.836z"/></svg>',get path(){return this.svg.match(/<path\s+d="([^"]*)/)[1]},source:"https://github.com/thymeleaf/thymeleaf-dist/tree/master/src/artwork/thymeleaf%202016",hex:"005F0F",guidelines:void 0,license:void 0}; | mit |
alvarpoon/silverheritage.com | vendor/aws/aws-sdk-php/tests/Aws/Tests/Common/Waiter/CompositeWaiterFactoryTest.php | 1156 | <?php
namespace Aws\Tests\Common\Waiter;
use Aws\Common\Waiter\CompositeWaiterFactory;
use Aws\Common\Waiter\WaiterConfigFactory;
/**
* @covers Aws\Common\Waiter\CompositeWaiterFactory
*/
class CompositeWaiterFactoryTest extends \Guzzle\Tests\GuzzleTestCase
{
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Waiter was not found matching foo
*/
public function testEnsuresWaiterExists()
{
$factory = new CompositeWaiterFactory(array(
new WaiterConfigFactory(array())
));
$this->assertFalse($factory->canBuild('foo'));
$factory->build('foo');
}
public function testBuildsWaiters()
{
$f1 = new WaiterConfigFactory(array('Boo' => array('test')));
$f2 = new WaiterConfigFactory(array('foo' => array('max_attempts' => 10)));
$factory = new CompositeWaiterFactory(array($f1));
$factory->addFactory($f2);
$this->assertInstanceOf('Aws\Common\Waiter\ConfigResourceWaiter', $factory->build('foo'));
$this->assertInstanceOf('Aws\Common\Waiter\ConfigResourceWaiter', $factory->build('Boo'));
}
}
| gpl-2.0 |
phpwomen/wp-phpwomen | wp-content/plugins/wordpress-social-login/includes/services/wsl.mail.notification.php | 2143 | <?php
/*!
* WordPress Social Login
*
* http://miled.github.io/wordpress-social-login/ | https://github.com/miled/wordpress-social-login
* (c) 2011-2014 Mohamed Mrassi and contributors | http://wordpress.org/plugins/wordpress-social-login/
*/
/**
* Email notifications to send. so far only the admin one is implemented
*/
// Exit if accessed directly
if ( !defined( 'ABSPATH' ) ) exit;
// --------------------------------------------------------------------
/**
* Send a notification to blog administrator when a new user register using WSL
*
* also borrowed from http://wordpress.org/extend/plugins/oa-social-login/
*
* Note:
* You may redefine this function
*/
if( ! function_exists( 'wsl_admin_notification' ) )
{
function wsl_admin_notification( $user_id, $provider )
{
//Get the user details
$user = new WP_User($user_id);
$user_login = stripslashes( $user->user_login );
// The blogname option is escaped with esc_html on the way into the database
// in sanitize_option we want to reverse this for the plain text arena of emails.
$blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);
$message = sprintf(__('New user registration on your site: %s', 'wordpress-social-login'), $blogname ) . "\r\n\r\n";
$message .= sprintf(__('Username: %s' , 'wordpress-social-login'), $user_login ) . "\r\n";
$message .= sprintf(__('Provider: %s' , 'wordpress-social-login'), $provider ) . "\r\n";
$message .= sprintf(__('Profile: %s' , 'wordpress-social-login'), $user->user_url ) . "\r\n";
$message .= sprintf(__('Email: %s' , 'wordpress-social-login'), $user->user_email) . "\r\n";
$message .= "\r\n--\r\n";
$message .= "WordPress Social Login\r\n";
$message .= "http://wordpress.org/extend/plugins/wordpress-social-login/\r\n";
@ wp_mail(get_option('admin_email'), '[WordPress Social Login] '.sprintf(__('[%s] New User Registration', 'wordpress-social-login'), $blogname), $message);
}
}
// --------------------------------------------------------------------
| gpl-2.0 |
koutheir/incinerator-hotspot | jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/handler/SOAPMessageContextImpl.java | 4642 | /*
* Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.xml.internal.ws.handler;
import com.sun.xml.internal.ws.api.message.Header;
import com.sun.xml.internal.ws.api.message.Message;
import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.message.saaj.SAAJFactory;
import com.sun.xml.internal.ws.api.WSBinding;
import com.sun.xml.internal.ws.api.SOAPVersion;
import javax.xml.bind.JAXBContext;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Implementation of {@link SOAPMessageContext}. This class is used at runtime
* to pass to the handlers for processing soap messages.
*
* @see MessageContextImpl
*
* @author WS Development Team
*/
public class SOAPMessageContextImpl extends MessageUpdatableContext implements SOAPMessageContext {
private Set<String> roles;
private SOAPMessage soapMsg = null;
private WSBinding binding;
public SOAPMessageContextImpl(WSBinding binding, Packet packet,Set<String> roles) {
super(packet);
this.binding = binding;
this.roles = roles;
}
public SOAPMessage getMessage() {
if(soapMsg == null) {
try {
Message m = packet.getMessage();
soapMsg = m != null ? m.readAsSOAPMessage() : null;
} catch (SOAPException e) {
throw new WebServiceException(e);
}
}
return soapMsg;
}
public void setMessage(SOAPMessage soapMsg) {
try {
this.soapMsg = soapMsg;
} catch(Exception e) {
throw new WebServiceException(e);
}
}
void setPacketMessage(Message newMessage){
if(newMessage != null) {
packet.setMessage(newMessage);
soapMsg = null;
}
}
protected void updateMessage() {
//Check if SOAPMessage has changed, if so construct new one,
// Packet are handled through MessageContext
if(soapMsg != null) {
packet.setMessage(SAAJFactory.create(soapMsg));
soapMsg = null;
}
}
public Object[] getHeaders(QName header, JAXBContext jaxbContext, boolean allRoles) {
SOAPVersion soapVersion = binding.getSOAPVersion();
List<Object> beanList = new ArrayList<Object>();
try {
Iterator<Header> itr = packet.getMessage().getHeaders().getHeaders(header,false);
if(allRoles) {
while(itr.hasNext()) {
beanList.add(itr.next().readAsJAXB(jaxbContext.createUnmarshaller()));
}
} else {
while(itr.hasNext()) {
Header soapHeader = itr.next();
//Check if the role is one of the roles on this Binding
String role = soapHeader.getRole(soapVersion);
if(getRoles().contains(role)) {
beanList.add(soapHeader.readAsJAXB(jaxbContext.createUnmarshaller()));
}
}
}
return beanList.toArray();
} catch(Exception e) {
throw new WebServiceException(e);
}
}
public Set<String> getRoles() {
return roles;
}
}
| gpl-2.0 |
kerr-huang/uwsgi | uwsgidsl.rb | 2839 | # based on uwsgidecorators.py
if UWSGI.masterpid == 0
raise "you have to enable the uWSGI master process to use this module"
end
def get_free_signal()
for signum in 0..255
if not UWSGI.signal_registered(signum)
return signum
end
end
end
$postfork_chain = []
$mulefunc_list = []
$spoolfunc_list = []
module UWSGI
module_function
def post_fork_hook()
$postfork_chain.each {|func| func.call }
end
module_function
def spooler(args)
$spoolfunc_list[args['ud_spool_func'].to_i].call(args)
end
module_function
def mule_msg_hook(message)
service = Marshal.load(message)
if service['service'] == 'uwsgi_mulefunc'
mulefunc_manager(service)
end
end
end
def timer(secs, target='', &block)
freesig = get_free_signal
UWSGI.register_signal(freesig, target, block)
UWSGI.add_timer(freesig, secs)
end
def rbtimer(secs, target='', &block)
freesig = get_free_signal
UWSGI.register_signal(freesig, target, block)
UWSGI.add_rb_timer(freesig, secs)
end
def filemon(file, target='', &block)
freesig = get_free_signal
UWSGI.register_signal(freesig, target, block)
UWSGI.add_file_monitor(freesig, file)
end
def cron(minute, hour, day, month, dayweek, target='', &block)
freesig = get_free_signal
UWSGI.register_signal(freesig, target, block)
UWSGI.add_cron(freesig, minute, hour, day, month, dayweek)
end
def signal(signum, target='', &block)
UWSGI.register_signal(signum, target, block)
end
def postfork(&block)
$postfork_chain << block
end
class SpoolProc < Proc
def initialize(&block)
@block = block
@id = (($spoolfunc_list << block).length-1).to_s
end
def call(args)
args['ud_spool_func'] = @id
UWSGI::send_to_spooler(args)
end
end
def rpc(name, &block)
if block.arity <= 0
UWSGI.register_rpc(name, block, 0)
else
UWSGI.register_rpc(name, block, block.arity)
end
end
def mulefunc_manager(service)
$mulefunc_list[service['func']].real_call(service['args'])
end
class MuleFunc < Proc
def initialize(id=0, &block)
@id = id
@block = block
@func_pos = (($mulefunc_list << self).length)-1
end
def real_call(*args)
@block.call(*args)
end
def call(*args)
UWSGI.mule_msg( Marshal.dump( {
'service' => 'uwsgi_mulefunc',
'func' => @func_pos,
'args'=> args
}), @id)
end
end
class MuleProc < Proc
def initialize(id, block)
@id = id
@block = block
end
def call()
if UWSGI.mule_id == @id
@block.call
end
end
end
class MuleLoopProc < MuleProc
def call()
if UWSGI.mule_id == @id
loop do
@block.call
end
end
end
end
def mule(id, &block)
$postfork_chain << MuleProc.new(id, block)
end
def muleloop(id, &block)
$postfork_chain << MuleLoopProc.new(id, block)
end
| gpl-2.0 |
fedyfausto/RaspberryWebPanel | editor/components/active/controller.php | 2796 | <?php
/*
* Copyright (c) Codiad & Kent Safranski (codiad.com), distributed
* as-is and without warranty under the MIT License. See
* [root]/license.txt for more. This information must remain intact.
*/
require_once('../../common.php');
require_once('class.active.php');
$Active = new Active();
//////////////////////////////////////////////////////////////////
// Verify Session or Key
//////////////////////////////////////////////////////////////////
checkSession();
//////////////////////////////////////////////////////////////////
// Get user's active files
//////////////////////////////////////////////////////////////////
if($_GET['action']=='list'){
$Active->username = $_SESSION['user'];
$Active->ListActive();
}
//////////////////////////////////////////////////////////////////
// Add active record
//////////////////////////////////////////////////////////////////
if($_GET['action']=='add'){
$Active->username = $_SESSION['user'];
$Active->path = $_GET['path'];
$Active->Add();
}
//////////////////////////////////////////////////////////////////
// Rename
//////////////////////////////////////////////////////////////////
if($_GET['action']=='rename'){
$Active->username = $_SESSION['user'];
$Active->path = $_GET['old_path'];
$Active->new_path = $_GET['new_path'];
$Active->Rename();
}
//////////////////////////////////////////////////////////////////
// Check if file is active
//////////////////////////////////////////////////////////////////
if($_GET['action']=='check'){
$Active->username = $_SESSION['user'];
$Active->path = $_GET['path'];
$Active->Check();
}
//////////////////////////////////////////////////////////////////
// Remove active record
//////////////////////////////////////////////////////////////////
if($_GET['action']=='remove'){
$Active->username = $_SESSION['user'];
$Active->path = $_GET['path'];
$Active->Remove();
}
//////////////////////////////////////////////////////////////////
// Remove all active record
//////////////////////////////////////////////////////////////////
if($_GET['action']=='removeall'){
$Active->username = $_SESSION['user'];
$Active->RemoveAll();
}
//////////////////////////////////////////////////////////////////
// Mark file as focused
//////////////////////////////////////////////////////////////////
if($_GET['action']=='focused'){
$Active->username = $_SESSION['user'];
$Active->path = $_GET['path'];
$Active->MarkFileAsFocused();
}
?> | bsd-2-clause |
sean-abbott/chamberlain | chamberlain/user/forms.py | 1490 | # -*- coding: utf-8 -*-
"""User forms."""
from flask_wtf import Form
from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired, Email, EqualTo, Length
from .models import User
class RegisterForm(Form):
"""Register form."""
username = StringField('Username',
validators=[DataRequired(), Length(min=3, max=25)])
email = StringField('Email',
validators=[DataRequired(), Email(), Length(min=6, max=40)])
password = PasswordField('Password',
validators=[DataRequired(), Length(min=6, max=40)])
confirm = PasswordField('Verify password',
[DataRequired(), EqualTo('password', message='Passwords must match')])
def __init__(self, *args, **kwargs):
"""Create instance."""
super(RegisterForm, self).__init__(*args, **kwargs)
self.user = None
def validate(self):
"""Validate the form."""
initial_validation = super(RegisterForm, self).validate()
if not initial_validation:
return False
user = User.query.filter_by(username=self.username.data).first()
if user:
self.username.errors.append('Username already registered')
return False
user = User.query.filter_by(email=self.email.data).first()
if user:
self.email.errors.append('Email already registered')
return False
return True
| bsd-3-clause |
heladio/my-blog | pelica-env/lib/python2.7/site-packages/pip/vcs/subversion.py | 10496 | from __future__ import absolute_import
import logging
import os
import re
from pip._vendor.six.moves.urllib import parse as urllib_parse
from pip.index import Link
from pip.utils import rmtree, display_path
from pip.utils.logging import indent_log
from pip.vcs import vcs, VersionControl
_svn_xml_url_re = re.compile('url="([^"]+)"')
_svn_rev_re = re.compile('committed-rev="(\d+)"')
_svn_url_re = re.compile(r'URL: (.+)')
_svn_revision_re = re.compile(r'Revision: (.+)')
_svn_info_xml_rev_re = re.compile(r'\s*revision="(\d+)"')
_svn_info_xml_url_re = re.compile(r'<url>(.*)</url>')
logger = logging.getLogger(__name__)
class Subversion(VersionControl):
name = 'svn'
dirname = '.svn'
repo_name = 'checkout'
schemes = ('svn', 'svn+ssh', 'svn+http', 'svn+https', 'svn+svn')
def get_info(self, location):
"""Returns (url, revision), where both are strings"""
assert not location.rstrip('/').endswith(self.dirname), \
'Bad directory: %s' % location
output = self.run_command(
['info', location],
show_stdout=False,
extra_environ={'LANG': 'C'},
)
match = _svn_url_re.search(output)
if not match:
logger.warning(
'Cannot determine URL of svn checkout %s',
display_path(location),
)
logger.debug('Output that cannot be parsed: \n%s', output)
return None, None
url = match.group(1).strip()
match = _svn_revision_re.search(output)
if not match:
logger.warning(
'Cannot determine revision of svn checkout %s',
display_path(location),
)
logger.debug('Output that cannot be parsed: \n%s', output)
return url, None
return url, match.group(1)
def export(self, location):
"""Export the svn repository at the url to the destination location"""
url, rev = self.get_url_rev()
rev_options = get_rev_options(url, rev)
logger.info('Exporting svn repository %s to %s', url, location)
with indent_log():
if os.path.exists(location):
# Subversion doesn't like to check out over an existing
# directory --force fixes this, but was only added in svn 1.5
rmtree(location)
self.run_command(
['export'] + rev_options + [url, location],
filter_stdout=self._filter, show_stdout=False)
def switch(self, dest, url, rev_options):
self.run_command(['switch'] + rev_options + [url, dest])
def update(self, dest, rev_options):
self.run_command(['update'] + rev_options + [dest])
def obtain(self, dest):
url, rev = self.get_url_rev()
rev_options = get_rev_options(url, rev)
if rev:
rev_display = ' (to revision %s)' % rev
else:
rev_display = ''
if self.check_destination(dest, url, rev_options, rev_display):
logger.info(
'Checking out %s%s to %s',
url,
rev_display,
display_path(dest),
)
self.run_command(['checkout', '-q'] + rev_options + [url, dest])
def get_location(self, dist, dependency_links):
for url in dependency_links:
egg_fragment = Link(url).egg_fragment
if not egg_fragment:
continue
if '-' in egg_fragment:
# FIXME: will this work when a package has - in the name?
key = '-'.join(egg_fragment.split('-')[:-1]).lower()
else:
key = egg_fragment
if key == dist.key:
return url.split('#', 1)[0]
return None
def get_revision(self, location):
"""
Return the maximum revision for all files under a given location
"""
# Note: taken from setuptools.command.egg_info
revision = 0
for base, dirs, files in os.walk(location):
if self.dirname not in dirs:
dirs[:] = []
continue # no sense walking uncontrolled subdirs
dirs.remove(self.dirname)
entries_fn = os.path.join(base, self.dirname, 'entries')
if not os.path.exists(entries_fn):
# FIXME: should we warn?
continue
dirurl, localrev = self._get_svn_url_rev(base)
if base == location:
base_url = dirurl + '/' # save the root url
elif not dirurl or not dirurl.startswith(base_url):
dirs[:] = []
continue # not part of the same svn tree, skip it
revision = max(revision, localrev)
return revision
def get_url_rev(self):
# hotfix the URL scheme after removing svn+ from svn+ssh:// readd it
url, rev = super(Subversion, self).get_url_rev()
if url.startswith('ssh://'):
url = 'svn+' + url
return url, rev
def get_url(self, location):
# In cases where the source is in a subdirectory, not alongside
# setup.py we have to look up in the location until we find a real
# setup.py
orig_location = location
while not os.path.exists(os.path.join(location, 'setup.py')):
last_location = location
location = os.path.dirname(location)
if location == last_location:
# We've traversed up to the root of the filesystem without
# finding setup.py
logger.warning(
"Could not find setup.py for directory %s (tried all "
"parent directories)",
orig_location,
)
return None
return self._get_svn_url_rev(location)[0]
def _get_svn_url_rev(self, location):
from pip.exceptions import InstallationError
with open(os.path.join(location, self.dirname, 'entries')) as f:
data = f.read()
if (data.startswith('8') or
data.startswith('9') or
data.startswith('10')):
data = list(map(str.splitlines, data.split('\n\x0c\n')))
del data[0][0] # get rid of the '8'
url = data[0][3]
revs = [int(d[9]) for d in data if len(d) > 9 and d[9]] + [0]
elif data.startswith('<?xml'):
match = _svn_xml_url_re.search(data)
if not match:
raise ValueError('Badly formatted data: %r' % data)
url = match.group(1) # get repository URL
revs = [int(m.group(1)) for m in _svn_rev_re.finditer(data)] + [0]
else:
try:
# subversion >= 1.7
xml = self.run_command(
['info', '--xml', location],
show_stdout=False,
)
url = _svn_info_xml_url_re.search(xml).group(1)
revs = [
int(m.group(1)) for m in _svn_info_xml_rev_re.finditer(xml)
]
except InstallationError:
url, revs = None, []
if revs:
rev = max(revs)
else:
rev = 0
return url, rev
def get_tag_revs(self, svn_tag_url):
stdout = self.run_command(['ls', '-v', svn_tag_url], show_stdout=False)
results = []
for line in stdout.splitlines():
parts = line.split()
rev = int(parts[0])
tag = parts[-1].strip('/')
results.append((tag, rev))
return results
def find_tag_match(self, rev, tag_revs):
best_match_rev = None
best_tag = None
for tag, tag_rev in tag_revs:
if (tag_rev > rev and
(best_match_rev is None or best_match_rev > tag_rev)):
# FIXME: Is best_match > tag_rev really possible?
# or is it a sign something is wacky?
best_match_rev = tag_rev
best_tag = tag
return best_tag
def get_src_requirement(self, dist, location, find_tags=False):
repo = self.get_url(location)
if repo is None:
return None
parts = repo.split('/')
# FIXME: why not project name?
egg_project_name = dist.egg_name().split('-', 1)[0]
rev = self.get_revision(location)
if parts[-2] in ('tags', 'tag'):
# It's a tag, perfect!
full_egg_name = '%s-%s' % (egg_project_name, parts[-1])
elif parts[-2] in ('branches', 'branch'):
# It's a branch :(
full_egg_name = '%s-%s-r%s' % (dist.egg_name(), parts[-1], rev)
elif parts[-1] == 'trunk':
# Trunk :-/
full_egg_name = '%s-dev_r%s' % (dist.egg_name(), rev)
if find_tags:
tag_url = '/'.join(parts[:-1]) + '/tags'
tag_revs = self.get_tag_revs(tag_url)
match = self.find_tag_match(rev, tag_revs)
if match:
logger.info(
'trunk checkout %s seems to be equivalent to tag %s',
match,
)
repo = '%s/%s' % (tag_url, match)
full_egg_name = '%s-%s' % (egg_project_name, match)
else:
# Don't know what it is
logger.warning(
'svn URL does not fit normal structure (tags/branches/trunk): '
'%s',
repo,
)
full_egg_name = '%s-dev_r%s' % (egg_project_name, rev)
return 'svn+%s@%s#egg=%s' % (repo, rev, full_egg_name)
def get_rev_options(url, rev):
if rev:
rev_options = ['-r', rev]
else:
rev_options = []
r = urllib_parse.urlsplit(url)
if hasattr(r, 'username'):
# >= Python-2.5
username, password = r.username, r.password
else:
netloc = r[1]
if '@' in netloc:
auth = netloc.split('@')[0]
if ':' in auth:
username, password = auth.split(':', 1)
else:
username, password = auth, None
else:
username, password = None, None
if username:
rev_options += ['--username', username]
if password:
rev_options += ['--password', password]
return rev_options
vcs.register(Subversion)
| mit |
LeChuck42/or1k-gcc | libstdc++-v3/testsuite/ext/pb_ds/regression/tree_set_rand_debug.cc | 4096 | // { dg-require-debug-mode "" }
// { dg-require-time "" }
// This can take long on simulators, timing out the test.
// { dg-options "-DITERATIONS=5" { target simulator } }
// { dg-timeout-factor 2.0 }
// -*- C++ -*-
// Copyright (C) 2011-2014 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, 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
// General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
/**
* @file tree_data_map_rand_debug.cc
* Contains a random-operation test for maps and sets, separated out.
*/
#define PB_DS_REGRESSION
//#define PB_DS_REGRESSION_TRACE
#include <regression/rand/assoc/rand_regression_test.hpp>
#include <regression/common_type.hpp>
#include <ext/throw_allocator.h>
#include <ext/pb_ds/tag_and_trait.hpp>
#ifndef ITERATIONS
# define ITERATIONS 100
#endif
#ifndef KEYS
# define KEYS 200
#endif
// Debug version of the rand regression tests, based on tree_data_map.
// 1
// Simplify things by unrolling the typelist of the different
// container types into individual statements.
//
// Unroll the typelist represented by tree_types, from
// regression/common_type.hpp. This is just a compile-time list of 6
// tree types, with different policies for the type of tree
// (ov_tree_tag, rb_tree_tag, splay_tree_tag) and for the node
// update (null_node_update, tree_order_statistics_node_update)
using namespace __gnu_pbds::test::detail;
using namespace __gnu_pbds;
typedef __gnu_pbds::test::basic_type basic_type;
typedef __gnu_cxx::throw_allocator_random<basic_type> allocator_type;
// ov_tree_tag
typedef tree<basic_type, null_type, std::less<basic_type>,
ov_tree_tag, null_node_update,
allocator_type> ov_tree_type1;
typedef tree<basic_type, null_type, std::less<basic_type>,
ov_tree_tag, tree_order_statistics_node_update,
allocator_type> ov_tree_type2;
// rb_tree_tag
typedef tree<basic_type, null_type, std::less<basic_type>,
rb_tree_tag, null_node_update,
allocator_type> rb_tree_type1;
typedef tree<basic_type, null_type, std::less<basic_type>,
rb_tree_tag, tree_order_statistics_node_update,
allocator_type> rb_tree_type2;
// splay_tree_tag
typedef tree<basic_type, null_type, std::less<basic_type>,
splay_tree_tag, null_node_update,
allocator_type> splay_tree_type1;
typedef tree<basic_type, null_type, std::less<basic_type>,
splay_tree_tag, tree_order_statistics_node_update,
allocator_type> splay_tree_type2;
// 2
// Specialize container_rand_regression_test for specific container
// type and test function.
#ifdef SPECIALIZE
// For testing one specific container type.
typedef ov_tree_type2 test_type;
void debug_break_here() { }
namespace __gnu_pbds {
namespace test {
namespace detail {
template<>
void
container_rand_regression_test<test_type>::operator()()
{
}
}
}
}
#endif
int
main()
{
// Set up the test object.
size_t sd = 1303948889;
rand_reg_test test(sd, ITERATIONS, KEYS, 0.2, .6, .2, .001, .25, true);
// 1
// Determine the problem container, function that fails.
test(ov_tree_type1());
test(ov_tree_type2());
test(rb_tree_type1());
test(rb_tree_type2());
test(splay_tree_type1());
test(splay_tree_type2());
#ifdef SPECIALIZE
// 2
// With specified problem container set test_type typedef
// appropriately above. Then, specialize operator()(), also
// above. Finally, run this below.
using namespace std;
test_type obj;
test(obj);
#endif
return 0;
}
| gpl-2.0 |
GrandHsu/rt-thread | bsp/lpc178x/rtconfig.py | 2122 | import os
# toolchains options
ARCH='arm'
CPU='cortex-m3'
CROSS_TOOL='keil'
if os.getenv('RTT_CC'):
CROSS_TOOL = os.getenv('RTT_CC')
if CROSS_TOOL == 'gcc':
PLATFORM = 'gcc'
EXEC_PATH = 'C:/Program Files/CodeSourcery/Sourcery_CodeBench_Lite_for_ARM_EABI/bin'
elif CROSS_TOOL == 'keil':
PLATFORM = 'armcc'
EXEC_PATH = 'C:/Keil'
elif CROSS_TOOL == 'iar':
print '================ERROR============================'
print 'Not support iar yet!'
print '================================================='
exit(0)
if os.getenv('RTT_EXEC_PATH'):
EXEC_PATH = os.getenv('RTT_EXEC_PATH')
BUILD = 'debug'
if PLATFORM == 'gcc':
# toolchains
PREFIX = 'arm-none-eabi-'
CC = PREFIX + 'gcc'
AS = PREFIX + 'gcc'
AR = PREFIX + 'ar'
LINK = PREFIX + 'gcc'
TARGET_EXT = 'axf'
SIZE = PREFIX + 'size'
OBJDUMP = PREFIX + 'objdump'
OBJCPY = PREFIX + 'objcopy'
DEVICE = ' -mcpu=cortex-m3 -mthumb'
CFLAGS = DEVICE + ' -DRT_USING_MINILIBC'
AFLAGS = ' -c' + DEVICE + ' -x assembler-with-cpp'
LFLAGS = DEVICE + ' -Wl,--gc-sections,-Map=rtthread-lpc178x.map,-cref,-u,Reset_Handler -T rtthread-lpc178x.ld'
CPATH = ''
LPATH = ''
if BUILD == 'debug':
CFLAGS += ' -O0 -gdwarf-2'
AFLAGS += ' -gdwarf-2'
else:
CFLAGS += ' -O2'
POST_ACTION = OBJCPY + ' -O binary $TARGET rtthread.bin\n' + SIZE + ' $TARGET \n'
elif PLATFORM == 'armcc':
# toolchains
CC = 'armcc'
AS = 'armasm'
AR = 'armar'
LINK = 'armlink'
TARGET_EXT = 'axf'
DEVICE = ' --device DARMP1'
CFLAGS = DEVICE + ' --apcs=interwork'
AFLAGS = DEVICE
LFLAGS = DEVICE + ' --info sizes --info totals --info unused --info veneers --list rtthread-lpc178x.map --scatter rtthread-lpc178x.sct'
CFLAGS += ' -I' + EXEC_PATH + '/ARM/RV31/INC'
LFLAGS += ' --libpath ' + EXEC_PATH + '/ARM/RV31/LIB'
EXEC_PATH += '/arm/bin40/'
if BUILD == 'debug':
CFLAGS += ' -g -O0'
AFLAGS += ' -g'
else:
CFLAGS += ' -O2'
POST_ACTION = 'fromelf --bin $TARGET --output rtthread.bin \nfromelf -z $TARGET'
| gpl-2.0 |
GuoyuHao/azure-xplat-cli | test/recordings/cli.mobile.job-tests/cli_DotNet_job_create.nock.js | 1357 | // This file has been autogenerated.
var profile = require('../../../lib/util/profile');
exports.getMockedProfile = function () {
var newProfile = new profile.Profile();
newProfile.addSubscription(new profile.Subscription({
id: '5e7d1bb6-4953-44fe-8a54-43fbdb53b989',
managementCertificate: {
key: 'mockedKey',
cert: 'mockedCert'
},
name: 'Mobilytics Test1',
registeredProviders: ['website', 'mobileservice'],
registeredResourceNamespaces: [],
isDefault: true
}, newProfile.environments['AzureCloud']));
return newProfile;
};
exports.setEnvironment = function() {
};
exports.scopes = [[function (nock) {
var result =
nock('https://management.core.windows.net:443')
.filteringRequestBody(function (path) { return '*';})
.post('/5e7d1bb6-4953-44fe-8a54-43fbdb53b989/services/mobileservices/mobileservices/clitestDotNet4056/scheduler/jobs', '*')
.reply(201, "", { 'cache-control': 'no-cache',
pragma: 'no-cache',
'transfer-encoding': 'chunked',
expires: '-1',
server: '1.0.6198.213 (rd_rdfe_stable.150402-1703) Microsoft-HTTPAPI/2.0',
'x-ms-servedbyregion': 'ussouth2',
'strict-transport-security': 'max-age=31536000; includeSubDomains',
'x-powered-by': 'ASP.NET',
'x-ms-request-id': '9df1ea6afe2e894ca7461e96cf32818b',
date: 'Wed, 08 Apr 2015 01:15:25 GMT' });
return result; }]]; | apache-2.0 |
alexlau811/azure-xplat-cli | lib/commands/asm/mobile/pipelineChannel.js | 3279 | //
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// 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.
//
var xml2js = require('xml2js');
module.exports = PipelineChannel;
function PipelineChannel(client, webResource, log) {
this.azureService = client;
this.client = client.pipeline;
this.resource = webResource;
this.log = log;
}
PipelineChannel.prototype.path = function (path) {
this.resource.url += '/' + path;
return this;
};
PipelineChannel.prototype.header = function (name, value) {
this.resource = this.resource.withHeader(name, value);
return this;
};
PipelineChannel.prototype.query = function (name, value) {
if (!this.resource.qs) {
this.resource.qs = {};
}
this.resource.qs[name] = value;
return this;
};
PipelineChannel.prototype.get = function (callback) {
this.resource.method = 'GET';
this._execute(callback);
};
PipelineChannel.prototype.poll = function (callback) {
this.resource.method = 'GET';
var self = this;
function pollAndRetry() {
self._execute(function (error, body) {
var retry = callback(error, body);
if(retry) {
setTimeout(function() { pollAndRetry(); }, self.azureService.longRunningOperationRetryTimeout);
}
});
}
pollAndRetry();
};
PipelineChannel.prototype.post = function (settings, callback) {
this.resource = this.resource.withBody(settings);
this.resource.method = 'POST';
this._execute(callback);
};
PipelineChannel.prototype.put = function (settings, callback) {
this.resource = this.resource.withBody(settings);
this.resource.method = 'PUT';
this._execute(callback);
};
PipelineChannel.prototype.patch = function (settings, callback) {
this.resource = this.resource.withBody(settings);
this.resource.method = 'PATCH';
this._execute(callback);
};
PipelineChannel.prototype.delete = function (callback) {
this.resource.method = 'DELETE';
this._execute(callback);
};
PipelineChannel.prototype._execute = function (callback) {
var log = this.log;
this.client(this.resource, function (error, response, body) {
if (error) {
log.silly('error');
log.json('silly', error);
callback(error, body, response);
} else if (response.statusCode < 200 || response.statusCode >= 300) {
callback(body, body, response);
} else if (response.headers['content-type'] && response.headers['content-type'].indexOf('application/xml') > -1) {
var parser = new xml2js.Parser();
parser.parseString(body, function (parserError, output) {
if (parserError) {
log.silly('parserError');
log.json('silly', parserError);
}
callback(parserError, output, response);
});
} else {
callback(error, body, response);
}
});
}; | apache-2.0 |
dcrisan/origin | Godeps/_workspace/src/github.com/coreos/etcd/etcdserver/etcdhttp/client_test.go | 48554 | // Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package etcdhttp
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"path"
"reflect"
"strings"
"testing"
"time"
etcdErr "github.com/coreos/etcd/error"
"github.com/coreos/etcd/etcdserver"
"github.com/coreos/etcd/etcdserver/etcdhttp/httptypes"
"github.com/coreos/etcd/etcdserver/etcdserverpb"
"github.com/coreos/etcd/pkg/testutil"
"github.com/coreos/etcd/pkg/types"
"github.com/coreos/etcd/raft/raftpb"
"github.com/coreos/etcd/store"
"github.com/coreos/etcd/version"
"github.com/jonboulle/clockwork"
"golang.org/x/net/context"
)
func mustMarshalEvent(t *testing.T, ev *store.Event) string {
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(ev); err != nil {
t.Fatalf("error marshalling event %#v: %v", ev, err)
}
return b.String()
}
// mustNewForm takes a set of Values and constructs a PUT *http.Request,
// with a URL constructed from appending the given path to the standard keysPrefix
func mustNewForm(t *testing.T, p string, vals url.Values) *http.Request {
u := testutil.MustNewURL(t, path.Join(keysPrefix, p))
req, err := http.NewRequest("PUT", u.String(), strings.NewReader(vals.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
t.Fatalf("error creating new request: %v", err)
}
return req
}
// mustNewPostForm takes a set of Values and constructs a POST *http.Request,
// with a URL constructed from appending the given path to the standard keysPrefix
func mustNewPostForm(t *testing.T, p string, vals url.Values) *http.Request {
u := testutil.MustNewURL(t, path.Join(keysPrefix, p))
req, err := http.NewRequest("POST", u.String(), strings.NewReader(vals.Encode()))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if err != nil {
t.Fatalf("error creating new request: %v", err)
}
return req
}
// mustNewRequest takes a path, appends it to the standard keysPrefix, and constructs
// a GET *http.Request referencing the resulting URL
func mustNewRequest(t *testing.T, p string) *http.Request {
return mustNewMethodRequest(t, "GET", p)
}
func mustNewMethodRequest(t *testing.T, m, p string) *http.Request {
return &http.Request{
Method: m,
URL: testutil.MustNewURL(t, path.Join(keysPrefix, p)),
}
}
type serverRecorder struct {
actions []action
}
func (s *serverRecorder) Start() {}
func (s *serverRecorder) Stop() {}
func (s *serverRecorder) Leader() types.ID { return types.ID(1) }
func (s *serverRecorder) ID() types.ID { return types.ID(1) }
func (s *serverRecorder) Do(_ context.Context, r etcdserverpb.Request) (etcdserver.Response, error) {
s.actions = append(s.actions, action{name: "Do", params: []interface{}{r}})
return etcdserver.Response{}, nil
}
func (s *serverRecorder) Process(_ context.Context, m raftpb.Message) error {
s.actions = append(s.actions, action{name: "Process", params: []interface{}{m}})
return nil
}
func (s *serverRecorder) AddMember(_ context.Context, m etcdserver.Member) error {
s.actions = append(s.actions, action{name: "AddMember", params: []interface{}{m}})
return nil
}
func (s *serverRecorder) RemoveMember(_ context.Context, id uint64) error {
s.actions = append(s.actions, action{name: "RemoveMember", params: []interface{}{id}})
return nil
}
func (s *serverRecorder) UpdateMember(_ context.Context, m etcdserver.Member) error {
s.actions = append(s.actions, action{name: "UpdateMember", params: []interface{}{m}})
return nil
}
type action struct {
name string
params []interface{}
}
// flushingRecorder provides a channel to allow users to block until the Recorder is Flushed()
type flushingRecorder struct {
*httptest.ResponseRecorder
ch chan struct{}
}
func (fr *flushingRecorder) Flush() {
fr.ResponseRecorder.Flush()
fr.ch <- struct{}{}
}
// resServer implements the etcd.Server interface for testing.
// It returns the given responsefrom any Do calls, and nil error
type resServer struct {
res etcdserver.Response
}
func (rs *resServer) Start() {}
func (rs *resServer) Stop() {}
func (rs *resServer) ID() types.ID { return types.ID(1) }
func (rs *resServer) Leader() types.ID { return types.ID(1) }
func (rs *resServer) Do(_ context.Context, _ etcdserverpb.Request) (etcdserver.Response, error) {
return rs.res, nil
}
func (rs *resServer) Process(_ context.Context, _ raftpb.Message) error { return nil }
func (rs *resServer) AddMember(_ context.Context, _ etcdserver.Member) error { return nil }
func (rs *resServer) RemoveMember(_ context.Context, _ uint64) error { return nil }
func (rs *resServer) UpdateMember(_ context.Context, _ etcdserver.Member) error { return nil }
func boolp(b bool) *bool { return &b }
type dummyRaftTimer struct{}
func (drt dummyRaftTimer) Index() uint64 { return uint64(100) }
func (drt dummyRaftTimer) Term() uint64 { return uint64(5) }
type dummyWatcher struct {
echan chan *store.Event
sidx uint64
}
func (w *dummyWatcher) EventChan() chan *store.Event {
return w.echan
}
func (w *dummyWatcher) StartIndex() uint64 { return w.sidx }
func (w *dummyWatcher) Remove() {}
func TestBadParseRequest(t *testing.T) {
tests := []struct {
in *http.Request
wcode int
}{
{
// parseForm failure
&http.Request{
Body: nil,
Method: "PUT",
},
etcdErr.EcodeInvalidForm,
},
{
// bad key prefix
&http.Request{
URL: testutil.MustNewURL(t, "/badprefix/"),
},
etcdErr.EcodeInvalidForm,
},
// bad values for prevIndex, waitIndex, ttl
{
mustNewForm(t, "foo", url.Values{"prevIndex": []string{"garbage"}}),
etcdErr.EcodeIndexNaN,
},
{
mustNewForm(t, "foo", url.Values{"prevIndex": []string{"1.5"}}),
etcdErr.EcodeIndexNaN,
},
{
mustNewForm(t, "foo", url.Values{"prevIndex": []string{"-1"}}),
etcdErr.EcodeIndexNaN,
},
{
mustNewForm(t, "foo", url.Values{"waitIndex": []string{"garbage"}}),
etcdErr.EcodeIndexNaN,
},
{
mustNewForm(t, "foo", url.Values{"waitIndex": []string{"??"}}),
etcdErr.EcodeIndexNaN,
},
{
mustNewForm(t, "foo", url.Values{"ttl": []string{"-1"}}),
etcdErr.EcodeTTLNaN,
},
// bad values for recursive, sorted, wait, prevExist, dir, stream
{
mustNewForm(t, "foo", url.Values{"recursive": []string{"hahaha"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"recursive": []string{"1234"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"recursive": []string{"?"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"sorted": []string{"?"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"sorted": []string{"x"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"wait": []string{"?!"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"wait": []string{"yes"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"prevExist": []string{"yes"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"prevExist": []string{"#2"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"dir": []string{"no"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"dir": []string{"file"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"quorum": []string{"no"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"quorum": []string{"file"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"stream": []string{"zzz"}}),
etcdErr.EcodeInvalidField,
},
{
mustNewForm(t, "foo", url.Values{"stream": []string{"something"}}),
etcdErr.EcodeInvalidField,
},
// prevValue cannot be empty
{
mustNewForm(t, "foo", url.Values{"prevValue": []string{""}}),
etcdErr.EcodePrevValueRequired,
},
// wait is only valid with GET requests
{
mustNewMethodRequest(t, "HEAD", "foo?wait=true"),
etcdErr.EcodeInvalidField,
},
// query values are considered
{
mustNewRequest(t, "foo?prevExist=wrong"),
etcdErr.EcodeInvalidField,
},
{
mustNewRequest(t, "foo?ttl=wrong"),
etcdErr.EcodeTTLNaN,
},
// but body takes precedence if both are specified
{
mustNewForm(
t,
"foo?ttl=12",
url.Values{"ttl": []string{"garbage"}},
),
etcdErr.EcodeTTLNaN,
},
{
mustNewForm(
t,
"foo?prevExist=false",
url.Values{"prevExist": []string{"yes"}},
),
etcdErr.EcodeInvalidField,
},
}
for i, tt := range tests {
got, err := parseKeyRequest(tt.in, clockwork.NewFakeClock())
if err == nil {
t.Errorf("#%d: unexpected nil error!", i)
continue
}
ee, ok := err.(*etcdErr.Error)
if !ok {
t.Errorf("#%d: err is not etcd.Error!", i)
continue
}
if ee.ErrorCode != tt.wcode {
t.Errorf("#%d: code=%d, want %v", i, ee.ErrorCode, tt.wcode)
t.Logf("cause: %#v", ee.Cause)
}
if !reflect.DeepEqual(got, etcdserverpb.Request{}) {
t.Errorf("#%d: unexpected non-empty Request: %#v", i, got)
}
}
}
func TestGoodParseRequest(t *testing.T) {
fc := clockwork.NewFakeClock()
fc.Advance(1111)
tests := []struct {
in *http.Request
w etcdserverpb.Request
}{
{
// good prefix, all other values default
mustNewRequest(t, "foo"),
etcdserverpb.Request{
Method: "GET",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// value specified
mustNewForm(
t,
"foo",
url.Values{"value": []string{"some_value"}},
),
etcdserverpb.Request{
Method: "PUT",
Val: "some_value",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// prevIndex specified
mustNewForm(
t,
"foo",
url.Values{"prevIndex": []string{"98765"}},
),
etcdserverpb.Request{
Method: "PUT",
PrevIndex: 98765,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// recursive specified
mustNewForm(
t,
"foo",
url.Values{"recursive": []string{"true"}},
),
etcdserverpb.Request{
Method: "PUT",
Recursive: true,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// sorted specified
mustNewForm(
t,
"foo",
url.Values{"sorted": []string{"true"}},
),
etcdserverpb.Request{
Method: "PUT",
Sorted: true,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// quorum specified
mustNewForm(
t,
"foo",
url.Values{"quorum": []string{"true"}},
),
etcdserverpb.Request{
Method: "PUT",
Quorum: true,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// wait specified
mustNewRequest(t, "foo?wait=true"),
etcdserverpb.Request{
Method: "GET",
Wait: true,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// empty TTL specified
mustNewRequest(t, "foo?ttl="),
etcdserverpb.Request{
Method: "GET",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
Expiration: 0,
},
},
{
// non-empty TTL specified
mustNewRequest(t, "foo?ttl=5678"),
etcdserverpb.Request{
Method: "GET",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
Expiration: fc.Now().Add(5678 * time.Second).UnixNano(),
},
},
{
// zero TTL specified
mustNewRequest(t, "foo?ttl=0"),
etcdserverpb.Request{
Method: "GET",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
Expiration: fc.Now().UnixNano(),
},
},
{
// dir specified
mustNewRequest(t, "foo?dir=true"),
etcdserverpb.Request{
Method: "GET",
Dir: true,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// dir specified negatively
mustNewRequest(t, "foo?dir=false"),
etcdserverpb.Request{
Method: "GET",
Dir: false,
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// prevExist should be non-null if specified
mustNewForm(
t,
"foo",
url.Values{"prevExist": []string{"true"}},
),
etcdserverpb.Request{
Method: "PUT",
PrevExist: boolp(true),
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
{
// prevExist should be non-null if specified
mustNewForm(
t,
"foo",
url.Values{"prevExist": []string{"false"}},
),
etcdserverpb.Request{
Method: "PUT",
PrevExist: boolp(false),
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
// mix various fields
{
mustNewForm(
t,
"foo",
url.Values{
"value": []string{"some value"},
"prevExist": []string{"true"},
"prevValue": []string{"previous value"},
},
),
etcdserverpb.Request{
Method: "PUT",
PrevExist: boolp(true),
PrevValue: "previous value",
Val: "some value",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
// query parameters should be used if given
{
mustNewForm(
t,
"foo?prevValue=woof",
url.Values{},
),
etcdserverpb.Request{
Method: "PUT",
PrevValue: "woof",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
// but form values should take precedence over query parameters
{
mustNewForm(
t,
"foo?prevValue=woof",
url.Values{
"prevValue": []string{"miaow"},
},
),
etcdserverpb.Request{
Method: "PUT",
PrevValue: "miaow",
Path: path.Join(etcdserver.StoreKeysPrefix, "/foo"),
},
},
}
for i, tt := range tests {
got, err := parseKeyRequest(tt.in, fc)
if err != nil {
t.Errorf("#%d: err = %v, want %v", i, err, nil)
}
if !reflect.DeepEqual(got, tt.w) {
t.Errorf("#%d: request=%#v, want %#v", i, got, tt.w)
}
}
}
func TestServeMembers(t *testing.T) {
memb1 := etcdserver.Member{ID: 12, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8080"}}}
memb2 := etcdserver.Member{ID: 13, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8081"}}}
cluster := &fakeCluster{
id: 1,
members: map[uint64]*etcdserver.Member{1: &memb1, 2: &memb2},
}
h := &membersHandler{
server: &serverRecorder{},
clock: clockwork.NewFakeClock(),
clusterInfo: cluster,
}
wmc := string(`{"members":[{"id":"c","name":"","peerURLs":[],"clientURLs":["http://localhost:8080"]},{"id":"d","name":"","peerURLs":[],"clientURLs":["http://localhost:8081"]}]}`)
tests := []struct {
path string
wcode int
wct string
wbody string
}{
{membersPrefix, http.StatusOK, "application/json", wmc + "\n"},
{membersPrefix + "/", http.StatusOK, "application/json", wmc + "\n"},
{path.Join(membersPrefix, "100"), http.StatusNotFound, "application/json", `{"message":"Not found"}`},
{path.Join(membersPrefix, "foobar"), http.StatusNotFound, "application/json", `{"message":"Not found"}`},
}
for i, tt := range tests {
req, err := http.NewRequest("GET", testutil.MustNewURL(t, tt.path).String(), nil)
if err != nil {
t.Fatal(err)
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
if rw.Code != tt.wcode {
t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
}
if gct := rw.Header().Get("Content-Type"); gct != tt.wct {
t.Errorf("#%d: content-type = %s, want %s", i, gct, tt.wct)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := cluster.ID().String()
if gcid != wcid {
t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
}
if rw.Body.String() != tt.wbody {
t.Errorf("#%d: body = %q, want %q", i, rw.Body.String(), tt.wbody)
}
}
}
// TODO: consolidate **ALL** fake server implementations and add no leader test case.
func TestServeLeader(t *testing.T) {
memb1 := etcdserver.Member{ID: 1, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8080"}}}
memb2 := etcdserver.Member{ID: 2, Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8081"}}}
cluster := &fakeCluster{
id: 1,
members: map[uint64]*etcdserver.Member{1: &memb1, 2: &memb2},
}
h := &membersHandler{
server: &serverRecorder{},
clock: clockwork.NewFakeClock(),
clusterInfo: cluster,
}
wmc := string(`{"id":"1","name":"","peerURLs":[],"clientURLs":["http://localhost:8080"]}`)
tests := []struct {
path string
wcode int
wct string
wbody string
}{
{membersPrefix + "leader", http.StatusOK, "application/json", wmc + "\n"},
// TODO: add no leader case
}
for i, tt := range tests {
req, err := http.NewRequest("GET", testutil.MustNewURL(t, tt.path).String(), nil)
if err != nil {
t.Fatal(err)
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
if rw.Code != tt.wcode {
t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
}
if gct := rw.Header().Get("Content-Type"); gct != tt.wct {
t.Errorf("#%d: content-type = %s, want %s", i, gct, tt.wct)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := cluster.ID().String()
if gcid != wcid {
t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
}
if rw.Body.String() != tt.wbody {
t.Errorf("#%d: body = %q, want %q", i, rw.Body.String(), tt.wbody)
}
}
}
func TestServeMembersCreate(t *testing.T) {
u := testutil.MustNewURL(t, membersPrefix)
b := []byte(`{"peerURLs":["http://127.0.0.1:1"]}`)
req, err := http.NewRequest("POST", u.String(), bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
s := &serverRecorder{}
h := &membersHandler{
server: s,
clock: clockwork.NewFakeClock(),
clusterInfo: &fakeCluster{id: 1},
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
wcode := http.StatusCreated
if rw.Code != wcode {
t.Errorf("code=%d, want %d", rw.Code, wcode)
}
wct := "application/json"
if gct := rw.Header().Get("Content-Type"); gct != wct {
t.Errorf("content-type = %s, want %s", gct, wct)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("cid = %s, want %s", gcid, wcid)
}
wb := `{"id":"2a86a83729b330d5","name":"","peerURLs":["http://127.0.0.1:1"],"clientURLs":[]}` + "\n"
g := rw.Body.String()
if g != wb {
t.Errorf("got body=%q, want %q", g, wb)
}
wm := etcdserver.Member{
ID: 3064321551348478165,
RaftAttributes: etcdserver.RaftAttributes{
PeerURLs: []string{"http://127.0.0.1:1"},
},
}
wactions := []action{{name: "AddMember", params: []interface{}{wm}}}
if !reflect.DeepEqual(s.actions, wactions) {
t.Errorf("actions = %+v, want %+v", s.actions, wactions)
}
}
func TestServeMembersDelete(t *testing.T) {
req := &http.Request{
Method: "DELETE",
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "BEEF")),
}
s := &serverRecorder{}
h := &membersHandler{
server: s,
clusterInfo: &fakeCluster{id: 1},
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
wcode := http.StatusNoContent
if rw.Code != wcode {
t.Errorf("code=%d, want %d", rw.Code, wcode)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("cid = %s, want %s", gcid, wcid)
}
g := rw.Body.String()
if g != "" {
t.Errorf("got body=%q, want %q", g, "")
}
wactions := []action{{name: "RemoveMember", params: []interface{}{uint64(0xBEEF)}}}
if !reflect.DeepEqual(s.actions, wactions) {
t.Errorf("actions = %+v, want %+v", s.actions, wactions)
}
}
func TestServeMembersUpdate(t *testing.T) {
u := testutil.MustNewURL(t, path.Join(membersPrefix, "1"))
b := []byte(`{"peerURLs":["http://127.0.0.1:1"]}`)
req, err := http.NewRequest("PUT", u.String(), bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
s := &serverRecorder{}
h := &membersHandler{
server: s,
clock: clockwork.NewFakeClock(),
clusterInfo: &fakeCluster{id: 1},
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
wcode := http.StatusNoContent
if rw.Code != wcode {
t.Errorf("code=%d, want %d", rw.Code, wcode)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("cid = %s, want %s", gcid, wcid)
}
wm := etcdserver.Member{
ID: 1,
RaftAttributes: etcdserver.RaftAttributes{
PeerURLs: []string{"http://127.0.0.1:1"},
},
}
wactions := []action{{name: "UpdateMember", params: []interface{}{wm}}}
if !reflect.DeepEqual(s.actions, wactions) {
t.Errorf("actions = %+v, want %+v", s.actions, wactions)
}
}
func TestServeMembersFail(t *testing.T) {
tests := []struct {
req *http.Request
server etcdserver.Server
wcode int
}{
{
// bad method
&http.Request{
Method: "CONNECT",
},
&resServer{},
http.StatusMethodNotAllowed,
},
{
// bad method
&http.Request{
Method: "TRACE",
},
&resServer{},
http.StatusMethodNotAllowed,
},
{
// parse body error
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader("bad json")),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&resServer{},
http.StatusBadRequest,
},
{
// bad content type
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/bad"}},
},
&errServer{},
http.StatusUnsupportedMediaType,
},
{
// bad url
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://a"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{},
http.StatusBadRequest,
},
{
// etcdserver.AddMember error
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{
errors.New("Error while adding a member"),
},
http.StatusInternalServerError,
},
{
// etcdserver.AddMember error
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{
etcdserver.ErrIDExists,
},
http.StatusConflict,
},
{
// etcdserver.AddMember error
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "POST",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{
etcdserver.ErrPeerURLexists,
},
http.StatusConflict,
},
{
// etcdserver.RemoveMember error with arbitrary server error
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "1")),
Method: "DELETE",
},
&errServer{
errors.New("Error while removing member"),
},
http.StatusInternalServerError,
},
{
// etcdserver.RemoveMember error with previously removed ID
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "DELETE",
},
&errServer{
etcdserver.ErrIDRemoved,
},
http.StatusGone,
},
{
// etcdserver.RemoveMember error with nonexistent ID
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "DELETE",
},
&errServer{
etcdserver.ErrIDNotFound,
},
http.StatusNotFound,
},
{
// etcdserver.RemoveMember error with badly formed ID
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "bad_id")),
Method: "DELETE",
},
nil,
http.StatusNotFound,
},
{
// etcdserver.RemoveMember with no ID
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "DELETE",
},
nil,
http.StatusMethodNotAllowed,
},
{
// parse body error
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "PUT",
Body: ioutil.NopCloser(strings.NewReader("bad json")),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&resServer{},
http.StatusBadRequest,
},
{
// bad content type
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "PUT",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/bad"}},
},
&errServer{},
http.StatusUnsupportedMediaType,
},
{
// bad url
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "PUT",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://a"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{},
http.StatusBadRequest,
},
{
// etcdserver.UpdateMember error
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "PUT",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{
errors.New("blah"),
},
http.StatusInternalServerError,
},
{
// etcdserver.UpdateMember error
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "PUT",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{
etcdserver.ErrPeerURLexists,
},
http.StatusConflict,
},
{
// etcdserver.UpdateMember error
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "0")),
Method: "PUT",
Body: ioutil.NopCloser(strings.NewReader(`{"PeerURLs": ["http://127.0.0.1:1"]}`)),
Header: map[string][]string{"Content-Type": []string{"application/json"}},
},
&errServer{
etcdserver.ErrIDNotFound,
},
http.StatusNotFound,
},
{
// etcdserver.UpdateMember error with badly formed ID
&http.Request{
URL: testutil.MustNewURL(t, path.Join(membersPrefix, "bad_id")),
Method: "PUT",
},
nil,
http.StatusNotFound,
},
{
// etcdserver.UpdateMember with no ID
&http.Request{
URL: testutil.MustNewURL(t, membersPrefix),
Method: "PUT",
},
nil,
http.StatusMethodNotAllowed,
},
}
for i, tt := range tests {
h := &membersHandler{
server: tt.server,
clusterInfo: &fakeCluster{id: 1},
clock: clockwork.NewFakeClock(),
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, tt.req)
if rw.Code != tt.wcode {
t.Errorf("#%d: code=%d, want %d", i, rw.Code, tt.wcode)
}
if rw.Code != http.StatusMethodNotAllowed {
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
}
}
}
}
func TestWriteEvent(t *testing.T) {
// nil event should not panic
rec := httptest.NewRecorder()
writeKeyEvent(rec, nil, dummyRaftTimer{})
h := rec.Header()
if len(h) > 0 {
t.Fatalf("unexpected non-empty headers: %#v", h)
}
b := rec.Body.String()
if len(b) > 0 {
t.Fatalf("unexpected non-empty body: %q", b)
}
tests := []struct {
ev *store.Event
idx string
// TODO(jonboulle): check body as well as just status code
code int
err error
}{
// standard case, standard 200 response
{
&store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
PrevNode: &store.NodeExtern{},
},
"0",
http.StatusOK,
nil,
},
// check new nodes return StatusCreated
{
&store.Event{
Action: store.Create,
Node: &store.NodeExtern{},
PrevNode: &store.NodeExtern{},
},
"0",
http.StatusCreated,
nil,
},
}
for i, tt := range tests {
rw := httptest.NewRecorder()
writeKeyEvent(rw, tt.ev, dummyRaftTimer{})
if gct := rw.Header().Get("Content-Type"); gct != "application/json" {
t.Errorf("case %d: bad Content-Type: got %q, want application/json", i, gct)
}
if gri := rw.Header().Get("X-Raft-Index"); gri != "100" {
t.Errorf("case %d: bad X-Raft-Index header: got %s, want %s", i, gri, "100")
}
if grt := rw.Header().Get("X-Raft-Term"); grt != "5" {
t.Errorf("case %d: bad X-Raft-Term header: got %s, want %s", i, grt, "5")
}
if gei := rw.Header().Get("X-Etcd-Index"); gei != tt.idx {
t.Errorf("case %d: bad X-Etcd-Index header: got %s, want %s", i, gei, tt.idx)
}
if rw.Code != tt.code {
t.Errorf("case %d: bad response code: got %d, want %v", i, rw.Code, tt.code)
}
}
}
func TestV2DeprecatedMachinesEndpoint(t *testing.T) {
tests := []struct {
method string
wcode int
}{
{"GET", http.StatusOK},
{"HEAD", http.StatusOK},
{"POST", http.StatusMethodNotAllowed},
}
m := NewClientHandler(&etcdserver.EtcdServer{Cluster: &etcdserver.Cluster{}})
s := httptest.NewServer(m)
defer s.Close()
for _, tt := range tests {
req, err := http.NewRequest(tt.method, s.URL+deprecatedMachinesPrefix, nil)
if err != nil {
t.Fatal(err)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
if resp.StatusCode != tt.wcode {
t.Errorf("StatusCode = %d, expected %d", resp.StatusCode, tt.wcode)
}
}
}
func TestServeMachines(t *testing.T) {
cluster := &fakeCluster{
clientURLs: []string{"http://localhost:8080", "http://localhost:8081", "http://localhost:8082"},
}
writer := httptest.NewRecorder()
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatal(err)
}
h := &deprecatedMachinesHandler{clusterInfo: cluster}
h.ServeHTTP(writer, req)
w := "http://localhost:8080, http://localhost:8081, http://localhost:8082"
if g := writer.Body.String(); g != w {
t.Errorf("body = %s, want %s", g, w)
}
if writer.Code != http.StatusOK {
t.Errorf("code = %d, want %d", writer.Code, http.StatusOK)
}
}
func TestGetID(t *testing.T) {
tests := []struct {
path string
wok bool
wid types.ID
wcode int
}{
{
"123",
true, 0x123, http.StatusOK,
},
{
"bad_id",
false, 0, http.StatusNotFound,
},
{
"",
false, 0, http.StatusMethodNotAllowed,
},
}
for i, tt := range tests {
w := httptest.NewRecorder()
id, ok := getID(tt.path, w)
if id != tt.wid {
t.Errorf("#%d: id = %d, want %d", i, id, tt.wid)
}
if ok != tt.wok {
t.Errorf("#%d: ok = %t, want %t", i, ok, tt.wok)
}
if w.Code != tt.wcode {
t.Errorf("#%d code = %d, want %d", i, w.Code, tt.wcode)
}
}
}
type dummyStats struct {
data []byte
}
func (ds *dummyStats) SelfStats() []byte { return ds.data }
func (ds *dummyStats) LeaderStats() []byte { return ds.data }
func (ds *dummyStats) StoreStats() []byte { return ds.data }
func (ds *dummyStats) UpdateRecvApp(_ types.ID, _ int64) {}
func TestServeSelfStats(t *testing.T) {
wb := []byte("some statistics")
w := string(wb)
sh := &statsHandler{
stats: &dummyStats{data: wb},
}
rw := httptest.NewRecorder()
sh.serveSelf(rw, &http.Request{Method: "GET"})
if rw.Code != http.StatusOK {
t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
}
wct := "application/json"
if gct := rw.Header().Get("Content-Type"); gct != wct {
t.Errorf("Content-Type = %q, want %q", gct, wct)
}
if g := rw.Body.String(); g != w {
t.Errorf("body = %s, want %s", g, w)
}
}
func TestSelfServeStatsBad(t *testing.T) {
for _, m := range []string{"PUT", "POST", "DELETE"} {
sh := &statsHandler{}
rw := httptest.NewRecorder()
sh.serveSelf(
rw,
&http.Request{
Method: m,
},
)
if rw.Code != http.StatusMethodNotAllowed {
t.Errorf("method %s: code=%d, want %d", m, rw.Code, http.StatusMethodNotAllowed)
}
}
}
func TestLeaderServeStatsBad(t *testing.T) {
for _, m := range []string{"PUT", "POST", "DELETE"} {
sh := &statsHandler{}
rw := httptest.NewRecorder()
sh.serveLeader(
rw,
&http.Request{
Method: m,
},
)
if rw.Code != http.StatusMethodNotAllowed {
t.Errorf("method %s: code=%d, want %d", m, rw.Code, http.StatusMethodNotAllowed)
}
}
}
func TestServeLeaderStats(t *testing.T) {
wb := []byte("some statistics")
w := string(wb)
sh := &statsHandler{
stats: &dummyStats{data: wb},
}
rw := httptest.NewRecorder()
sh.serveLeader(rw, &http.Request{Method: "GET"})
if rw.Code != http.StatusOK {
t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
}
wct := "application/json"
if gct := rw.Header().Get("Content-Type"); gct != wct {
t.Errorf("Content-Type = %q, want %q", gct, wct)
}
if g := rw.Body.String(); g != w {
t.Errorf("body = %s, want %s", g, w)
}
}
func TestServeStoreStats(t *testing.T) {
wb := []byte("some statistics")
w := string(wb)
sh := &statsHandler{
stats: &dummyStats{data: wb},
}
rw := httptest.NewRecorder()
sh.serveStore(rw, &http.Request{Method: "GET"})
if rw.Code != http.StatusOK {
t.Errorf("code = %d, want %d", rw.Code, http.StatusOK)
}
wct := "application/json"
if gct := rw.Header().Get("Content-Type"); gct != wct {
t.Errorf("Content-Type = %q, want %q", gct, wct)
}
if g := rw.Body.String(); g != w {
t.Errorf("body = %s, want %s", g, w)
}
}
func TestServeVersion(t *testing.T) {
req, err := http.NewRequest("GET", "", nil)
if err != nil {
t.Fatalf("error creating request: %v", err)
}
rw := httptest.NewRecorder()
serveVersion(rw, req)
if rw.Code != http.StatusOK {
t.Errorf("code=%d, want %d", rw.Code, http.StatusOK)
}
w := fmt.Sprintf("etcd %s", version.Version)
if g := rw.Body.String(); g != w {
t.Fatalf("body = %q, want %q", g, w)
}
}
func TestServeVersionFails(t *testing.T) {
for _, m := range []string{
"CONNECT", "TRACE", "PUT", "POST", "HEAD",
} {
req, err := http.NewRequest(m, "", nil)
if err != nil {
t.Fatalf("error creating request: %v", err)
}
rw := httptest.NewRecorder()
serveVersion(rw, req)
if rw.Code != http.StatusMethodNotAllowed {
t.Errorf("method %s: code=%d, want %d", m, rw.Code, http.StatusMethodNotAllowed)
}
}
}
func TestBadServeKeys(t *testing.T) {
testBadCases := []struct {
req *http.Request
server etcdserver.Server
wcode int
wbody string
}{
{
// bad method
&http.Request{
Method: "CONNECT",
},
&resServer{},
http.StatusMethodNotAllowed,
"Method Not Allowed",
},
{
// bad method
&http.Request{
Method: "TRACE",
},
&resServer{},
http.StatusMethodNotAllowed,
"Method Not Allowed",
},
{
// parseRequest error
&http.Request{
Body: nil,
Method: "PUT",
},
&resServer{},
http.StatusBadRequest,
`{"errorCode":210,"message":"Invalid POST form","cause":"missing form body","index":0}`,
},
{
// etcdserver.Server error
mustNewRequest(t, "foo"),
&errServer{
errors.New("Internal Server Error"),
},
http.StatusInternalServerError,
`{"message":"Internal Server Error"}`,
},
{
// etcdserver.Server etcd error
mustNewRequest(t, "foo"),
&errServer{
etcdErr.NewError(etcdErr.EcodeKeyNotFound, "/1/pant", 0),
},
http.StatusNotFound,
`{"errorCode":100,"message":"Key not found","cause":"/pant","index":0}`,
},
{
// non-event/watcher response from etcdserver.Server
mustNewRequest(t, "foo"),
&resServer{
etcdserver.Response{},
},
http.StatusInternalServerError,
`{"message":"Internal Server Error"}`,
},
}
for i, tt := range testBadCases {
h := &keysHandler{
timeout: 0, // context times out immediately
server: tt.server,
clusterInfo: &fakeCluster{id: 1},
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, tt.req)
if rw.Code != tt.wcode {
t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
}
if rw.Code != http.StatusMethodNotAllowed {
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("#%d: cid = %s, want %s", i, gcid, wcid)
}
}
if g := strings.TrimSuffix(rw.Body.String(), "\n"); g != tt.wbody {
t.Errorf("#%d: body = %s, want %s", i, g, tt.wbody)
}
}
}
func TestServeKeysGood(t *testing.T) {
tests := []struct {
req *http.Request
wcode int
}{
{
mustNewMethodRequest(t, "HEAD", "foo"),
http.StatusOK,
},
{
mustNewMethodRequest(t, "GET", "foo"),
http.StatusOK,
},
{
mustNewForm(t, "foo", url.Values{"value": []string{"bar"}}),
http.StatusOK,
},
{
mustNewMethodRequest(t, "DELETE", "foo"),
http.StatusOK,
},
{
mustNewPostForm(t, "foo", url.Values{"value": []string{"bar"}}),
http.StatusOK,
},
}
server := &resServer{
etcdserver.Response{
Event: &store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
},
},
}
for i, tt := range tests {
h := &keysHandler{
timeout: time.Hour,
server: server,
timer: &dummyRaftTimer{},
clusterInfo: &fakeCluster{id: 1},
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, tt.req)
if rw.Code != tt.wcode {
t.Errorf("#%d: got code=%d, want %d", i, rw.Code, tt.wcode)
}
}
}
func TestServeKeysEvent(t *testing.T) {
req := mustNewRequest(t, "foo")
server := &resServer{
etcdserver.Response{
Event: &store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
},
},
}
h := &keysHandler{
timeout: time.Hour,
server: server,
clusterInfo: &fakeCluster{id: 1},
timer: &dummyRaftTimer{},
}
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
wcode := http.StatusOK
wbody := mustMarshalEvent(
t,
&store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
},
)
if rw.Code != wcode {
t.Errorf("got code=%d, want %d", rw.Code, wcode)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("cid = %s, want %s", gcid, wcid)
}
g := rw.Body.String()
if g != wbody {
t.Errorf("got body=%#v, want %#v", g, wbody)
}
}
func TestServeKeysWatch(t *testing.T) {
req := mustNewRequest(t, "/foo/bar")
ec := make(chan *store.Event)
dw := &dummyWatcher{
echan: ec,
}
server := &resServer{
etcdserver.Response{
Watcher: dw,
},
}
h := &keysHandler{
timeout: time.Hour,
server: server,
clusterInfo: &fakeCluster{id: 1},
timer: &dummyRaftTimer{},
}
go func() {
ec <- &store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
}
}()
rw := httptest.NewRecorder()
h.ServeHTTP(rw, req)
wcode := http.StatusOK
wbody := mustMarshalEvent(
t,
&store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
},
)
if rw.Code != wcode {
t.Errorf("got code=%d, want %d", rw.Code, wcode)
}
gcid := rw.Header().Get("X-Etcd-Cluster-ID")
wcid := h.clusterInfo.ID().String()
if gcid != wcid {
t.Errorf("cid = %s, want %s", gcid, wcid)
}
g := rw.Body.String()
if g != wbody {
t.Errorf("got body=%#v, want %#v", g, wbody)
}
}
type recordingCloseNotifier struct {
*httptest.ResponseRecorder
cn chan bool
}
func (rcn *recordingCloseNotifier) CloseNotify() <-chan bool {
return rcn.cn
}
func TestHandleWatch(t *testing.T) {
defaultRwRr := func() (http.ResponseWriter, *httptest.ResponseRecorder) {
r := httptest.NewRecorder()
return r, r
}
noopEv := func(chan *store.Event) {}
tests := []struct {
getCtx func() context.Context
getRwRr func() (http.ResponseWriter, *httptest.ResponseRecorder)
doToChan func(chan *store.Event)
wbody string
}{
{
// Normal case: one event
context.Background,
defaultRwRr,
func(ch chan *store.Event) {
ch <- &store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
}
},
mustMarshalEvent(
t,
&store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
},
),
},
{
// Channel is closed, no event
context.Background,
defaultRwRr,
func(ch chan *store.Event) {
close(ch)
},
"",
},
{
// Simulate a timed-out context
func() context.Context {
ctx, cancel := context.WithCancel(context.Background())
cancel()
return ctx
},
defaultRwRr,
noopEv,
"",
},
{
// Close-notifying request
context.Background,
func() (http.ResponseWriter, *httptest.ResponseRecorder) {
rw := &recordingCloseNotifier{
ResponseRecorder: httptest.NewRecorder(),
cn: make(chan bool, 1),
}
rw.cn <- true
return rw, rw.ResponseRecorder
},
noopEv,
"",
},
}
for i, tt := range tests {
rw, rr := tt.getRwRr()
wa := &dummyWatcher{
echan: make(chan *store.Event, 1),
sidx: 10,
}
tt.doToChan(wa.echan)
handleKeyWatch(tt.getCtx(), rw, wa, false, dummyRaftTimer{})
wcode := http.StatusOK
wct := "application/json"
wei := "10"
wri := "100"
wrt := "5"
if rr.Code != wcode {
t.Errorf("#%d: got code=%d, want %d", i, rr.Code, wcode)
}
h := rr.Header()
if ct := h.Get("Content-Type"); ct != wct {
t.Errorf("#%d: Content-Type=%q, want %q", i, ct, wct)
}
if ei := h.Get("X-Etcd-Index"); ei != wei {
t.Errorf("#%d: X-Etcd-Index=%q, want %q", i, ei, wei)
}
if ri := h.Get("X-Raft-Index"); ri != wri {
t.Errorf("#%d: X-Raft-Index=%q, want %q", i, ri, wri)
}
if rt := h.Get("X-Raft-Term"); rt != wrt {
t.Errorf("#%d: X-Raft-Term=%q, want %q", i, rt, wrt)
}
g := rr.Body.String()
if g != tt.wbody {
t.Errorf("#%d: got body=%#v, want %#v", i, g, tt.wbody)
}
}
}
func TestHandleWatchStreaming(t *testing.T) {
rw := &flushingRecorder{
httptest.NewRecorder(),
make(chan struct{}, 1),
}
wa := &dummyWatcher{
echan: make(chan *store.Event),
}
// Launch the streaming handler in the background with a cancellable context
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
handleKeyWatch(ctx, rw, wa, true, dummyRaftTimer{})
close(done)
}()
// Expect one Flush for the headers etc.
select {
case <-rw.ch:
case <-time.After(time.Second):
t.Fatalf("timed out waiting for flush")
}
// Expect headers but no body
wcode := http.StatusOK
wct := "application/json"
wbody := ""
if rw.Code != wcode {
t.Errorf("got code=%d, want %d", rw.Code, wcode)
}
h := rw.Header()
if ct := h.Get("Content-Type"); ct != wct {
t.Errorf("Content-Type=%q, want %q", ct, wct)
}
g := rw.Body.String()
if g != wbody {
t.Errorf("got body=%#v, want %#v", g, wbody)
}
// Now send the first event
select {
case wa.echan <- &store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
}:
case <-time.After(time.Second):
t.Fatal("timed out waiting for send")
}
// Wait for it to be flushed...
select {
case <-rw.ch:
case <-time.After(time.Second):
t.Fatalf("timed out waiting for flush")
}
// And check the body is as expected
wbody = mustMarshalEvent(
t,
&store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
},
)
g = rw.Body.String()
if g != wbody {
t.Errorf("got body=%#v, want %#v", g, wbody)
}
// Rinse and repeat
select {
case wa.echan <- &store.Event{
Action: store.Get,
Node: &store.NodeExtern{},
}:
case <-time.After(time.Second):
t.Fatal("timed out waiting for send")
}
select {
case <-rw.ch:
case <-time.After(time.Second):
t.Fatalf("timed out waiting for flush")
}
// This time, we expect to see both events
wbody = wbody + wbody
g = rw.Body.String()
if g != wbody {
t.Errorf("got body=%#v, want %#v", g, wbody)
}
// Finally, time out the connection and ensure the serving goroutine returns
cancel()
select {
case <-done:
case <-time.After(time.Second):
t.Fatalf("timed out waiting for done")
}
}
func TestTrimEventPrefix(t *testing.T) {
pre := "/abc"
tests := []struct {
ev *store.Event
wev *store.Event
}{
{
nil,
nil,
},
{
&store.Event{},
&store.Event{},
},
{
&store.Event{Node: &store.NodeExtern{Key: "/abc/def"}},
&store.Event{Node: &store.NodeExtern{Key: "/def"}},
},
{
&store.Event{PrevNode: &store.NodeExtern{Key: "/abc/ghi"}},
&store.Event{PrevNode: &store.NodeExtern{Key: "/ghi"}},
},
{
&store.Event{
Node: &store.NodeExtern{Key: "/abc/def"},
PrevNode: &store.NodeExtern{Key: "/abc/ghi"},
},
&store.Event{
Node: &store.NodeExtern{Key: "/def"},
PrevNode: &store.NodeExtern{Key: "/ghi"},
},
},
}
for i, tt := range tests {
ev := trimEventPrefix(tt.ev, pre)
if !reflect.DeepEqual(ev, tt.wev) {
t.Errorf("#%d: event = %+v, want %+v", i, ev, tt.wev)
}
}
}
func TestTrimNodeExternPrefix(t *testing.T) {
pre := "/abc"
tests := []struct {
n *store.NodeExtern
wn *store.NodeExtern
}{
{
nil,
nil,
},
{
&store.NodeExtern{Key: "/abc/def"},
&store.NodeExtern{Key: "/def"},
},
{
&store.NodeExtern{
Key: "/abc/def",
Nodes: []*store.NodeExtern{
{Key: "/abc/def/1"},
{Key: "/abc/def/2"},
},
},
&store.NodeExtern{
Key: "/def",
Nodes: []*store.NodeExtern{
{Key: "/def/1"},
{Key: "/def/2"},
},
},
},
}
for i, tt := range tests {
n := trimNodeExternPrefix(tt.n, pre)
if !reflect.DeepEqual(n, tt.wn) {
t.Errorf("#%d: node = %+v, want %+v", i, n, tt.wn)
}
}
}
func TestTrimPrefix(t *testing.T) {
tests := []struct {
in string
prefix string
w string
}{
{"/v2/members", "/v2/members", ""},
{"/v2/members/", "/v2/members", ""},
{"/v2/members/foo", "/v2/members", "foo"},
}
for i, tt := range tests {
if g := trimPrefix(tt.in, tt.prefix); g != tt.w {
t.Errorf("#%d: trimPrefix = %q, want %q", i, g, tt.w)
}
}
}
func TestNewMemberCollection(t *testing.T) {
fixture := []*etcdserver.Member{
&etcdserver.Member{
ID: 12,
Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"}},
RaftAttributes: etcdserver.RaftAttributes{PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"}},
},
&etcdserver.Member{
ID: 13,
Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:9090", "http://localhost:9091"}},
RaftAttributes: etcdserver.RaftAttributes{PeerURLs: []string{"http://localhost:9092", "http://localhost:9093"}},
},
}
got := newMemberCollection(fixture)
want := httptypes.MemberCollection([]httptypes.Member{
httptypes.Member{
ID: "c",
ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"},
PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"},
},
httptypes.Member{
ID: "d",
ClientURLs: []string{"http://localhost:9090", "http://localhost:9091"},
PeerURLs: []string{"http://localhost:9092", "http://localhost:9093"},
},
})
if !reflect.DeepEqual(&want, got) {
t.Fatalf("newMemberCollection failure: want=%#v, got=%#v", &want, got)
}
}
func TestNewMember(t *testing.T) {
fixture := &etcdserver.Member{
ID: 12,
Attributes: etcdserver.Attributes{ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"}},
RaftAttributes: etcdserver.RaftAttributes{PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"}},
}
got := newMember(fixture)
want := httptypes.Member{
ID: "c",
ClientURLs: []string{"http://localhost:8080", "http://localhost:8081"},
PeerURLs: []string{"http://localhost:8082", "http://localhost:8083"},
}
if !reflect.DeepEqual(want, got) {
t.Fatalf("newMember failure: want=%#v, got=%#v", want, got)
}
}
| apache-2.0 |
OpenCollabZA/sakai | search/search-tool/tool/src/java/org/sakaiproject/search/tool/SearchBeanFactoryImpl.java | 5737 | /**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 The Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.search.tool;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.sakaiproject.authz.api.SecurityService;
import org.sakaiproject.component.api.ComponentManager;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.exception.IdUnusedException;
import org.sakaiproject.exception.PermissionException;
import org.sakaiproject.search.api.SearchService;
import org.sakaiproject.search.tool.api.OpenSearchBean;
import org.sakaiproject.search.tool.api.SearchAdminBean;
import org.sakaiproject.search.tool.api.SearchBean;
import org.sakaiproject.search.tool.api.SearchBeanFactory;
import org.sakaiproject.search.tool.api.SherlockSearchBean;
import org.sakaiproject.site.api.SiteService;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;
/**
* @author ieb
*/
@Slf4j
public class SearchBeanFactoryImpl implements SearchBeanFactory
{
private SearchService searchService;
private SiteService siteService;
private ToolManager toolManager;
private SessionManager sessionManager;
private UserDirectoryService userDirectoryService;
private ServletContext context;
private SecurityService securityService;
private ServerConfigurationService serverConfigurationService;
public void init()
{
ComponentManager cm = org.sakaiproject.component.cover.ComponentManager
.getInstance();
sessionManager = (SessionManager) load(cm, SessionManager.class
.getName());
searchService = (SearchService) load(cm, SearchService.class.getName());
siteService = (SiteService) load(cm, SiteService.class.getName());
toolManager = (ToolManager) load(cm, ToolManager.class.getName());
userDirectoryService = (UserDirectoryService) load(cm, UserDirectoryService.class.getName());
securityService = (SecurityService)load(cm, SecurityService.class.getName());
serverConfigurationService = (ServerConfigurationService) load(cm, ServerConfigurationService.class.getName());
}
private Object load(ComponentManager cm, String name)
{
Object o = cm.get(name);
if (o == null)
{
log.error("Cant find Spring component named " + name);
}
return o;
}
/**
* {@inheritDoc}
*
* @throws PermissionException
*/
public SearchBean newSearchBean(HttpServletRequest request)
{
try
{
SearchBean searchBean = new SearchBeanImpl(request,
searchService, siteService, toolManager, userDirectoryService, securityService, serverConfigurationService);
return searchBean;
}
catch (IdUnusedException e)
{
throw new RuntimeException(
Messages.getString("searchbeanfact_siteerror"));
}
}
/**
* {@inheritDoc}
*
* @throws PermissionException
*/
public SearchAdminBean newSearchAdminBean(HttpServletRequest request)
throws PermissionException
{
try
{
SearchAdminBeanImpl searchAdminBean = new SearchAdminBeanImpl(
request, searchService, siteService, toolManager,
sessionManager, securityService, serverConfigurationService);
return searchAdminBean;
}
catch (IdUnusedException e)
{
throw new RuntimeException(
Messages.getString("searchbeanfact_siteerror"));
}
}
public SearchBean newSearchBean(HttpServletRequest request, String sortName, String filterName) throws PermissionException
{
try
{
SearchBean searchBean = new SearchBeanImpl(request, sortName, filterName,
searchService, siteService, toolManager, userDirectoryService, securityService, serverConfigurationService);
return searchBean;
}
catch (IdUnusedException e)
{
throw new RuntimeException(
Messages.getString("searchbeanfact_siteerror"));
}
}
public OpenSearchBean newOpenSearchBean(HttpServletRequest request) throws PermissionException
{
try
{
OpenSearchBean openSearchBean = new OpenSearchBeanImpl(request,
searchService, siteService, toolManager);
return openSearchBean;
}
catch (IdUnusedException e)
{
throw new RuntimeException(
Messages.getString("searchbeanfact_siteerror"));
}
}
public SherlockSearchBean newSherlockSearchBean(HttpServletRequest request) throws PermissionException
{
try
{
SherlockSearchBean sherlockSearchBean =
new SherlockSearchBeanImpl(request,
context,
searchService, siteService, toolManager);
return sherlockSearchBean;
}
catch (IdUnusedException e)
{
throw new RuntimeException(
Messages.getString("searchbeanfact_siteerror"));
}
}
/**
* @return the context
*/
public ServletContext getContext()
{
return context;
}
/**
* @param context the context to set
*/
public void setContext(ServletContext context)
{
this.context = context;
}
}
| apache-2.0 |
felixmulder/scala | test/files/pos/t2331.scala | 168 | trait C {
def m[T]: T
}
object Test {
val o /*: C --> no crash*/ = new C {
def m[T]: Nothing /*: T --> no crash*/ = sys.error("omitted")
}
o.m[Nothing]
}
| bsd-3-clause |
ROMFactory/android_external_chromium_org | content/test/run_all_unittests.cc | 398 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/test/content_test_suite.h"
#include "content/public/test/unittest_test_suite.h"
int main(int argc, char** argv) {
return content::UnitTestTestSuite(
new content::ContentTestSuite(argc, argv)).Run();
}
| bsd-3-clause |
TeamExodus/external_chromium_org | chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.cc | 5292 | // Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/signed_in_devices/signed_in_devices_api.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/values.h"
#include "chrome/browser/extensions/api/signed_in_devices/id_mapping_helper.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/sync/profile_sync_service_factory.h"
#include "chrome/common/extensions/api/signed_in_devices.h"
#include "components/sync_driver/device_info_tracker.h"
#include "components/sync_driver/local_device_info_provider.h"
#include "extensions/browser/extension_prefs.h"
using base::DictionaryValue;
using sync_driver::DeviceInfo;
using sync_driver::DeviceInfoTracker;
using sync_driver::LocalDeviceInfoProvider;
namespace extensions {
static const char kPrefStringForIdMapping[] = "id_mapping_dictioanry";
// Gets the dictionary that stores the id mapping. The dictionary is stored
// in the |ExtensionPrefs|.
const base::DictionaryValue* GetIdMappingDictionary(
ExtensionPrefs* extension_prefs,
const std::string& extension_id) {
const base::DictionaryValue* out_value = NULL;
if (!extension_prefs->ReadPrefAsDictionary(
extension_id,
kPrefStringForIdMapping,
&out_value) || out_value == NULL) {
// Looks like this is the first call to get the dictionary. Let us create
// a dictionary and set it in to |extension_prefs|.
scoped_ptr<base::DictionaryValue> dictionary(new base::DictionaryValue());
out_value = dictionary.get();
extension_prefs->UpdateExtensionPref(
extension_id,
kPrefStringForIdMapping,
dictionary.release());
}
return out_value;
}
// Helper routine to get all signed in devices. The helper takes in
// the pointers for |DeviceInfoTracker| and |Extensionprefs|. This
// makes it easier to test by passing mock values for these pointers.
ScopedVector<DeviceInfo> GetAllSignedInDevices(
const std::string& extension_id,
DeviceInfoTracker* device_tracker,
ExtensionPrefs* extension_prefs) {
DCHECK(device_tracker);
ScopedVector<DeviceInfo> devices = device_tracker->GetAllDeviceInfo();
const base::DictionaryValue* mapping_dictionary = GetIdMappingDictionary(
extension_prefs,
extension_id);
CHECK(mapping_dictionary);
// |mapping_dictionary| is const. So make an editable copy.
scoped_ptr<base::DictionaryValue> editable_mapping_dictionary(
mapping_dictionary->DeepCopy());
CreateMappingForUnmappedDevices(&(devices.get()),
editable_mapping_dictionary.get());
// Write into |ExtensionPrefs| which will get persisted in disk.
extension_prefs->UpdateExtensionPref(extension_id,
kPrefStringForIdMapping,
editable_mapping_dictionary.release());
return devices.Pass();
}
ScopedVector<DeviceInfo> GetAllSignedInDevices(
const std::string& extension_id,
Profile* profile) {
// Get the device tracker and extension prefs pointers
// and call the helper.
DeviceInfoTracker* device_tracker =
ProfileSyncServiceFactory::GetForProfile(profile)->GetDeviceInfoTracker();
if (device_tracker == NULL) {
// Devices are not sync'ing.
return ScopedVector<DeviceInfo>().Pass();
}
ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(profile);
return GetAllSignedInDevices(extension_id, device_tracker, extension_prefs);
}
scoped_ptr<DeviceInfo> GetLocalDeviceInfo(const std::string& extension_id,
Profile* profile) {
ProfileSyncService* pss = ProfileSyncServiceFactory::GetForProfile(profile);
if (!pss) {
return scoped_ptr<DeviceInfo>();
}
LocalDeviceInfoProvider* local_device = pss->GetLocalDeviceInfoProvider();
DCHECK(local_device);
std::string guid = local_device->GetLocalSyncCacheGUID();
scoped_ptr<DeviceInfo> device = GetDeviceInfoForClientId(guid,
extension_id,
profile);
return device.Pass();
}
bool SignedInDevicesGetFunction::RunSync() {
scoped_ptr<api::signed_in_devices::Get::Params> params(
api::signed_in_devices::Get::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
bool is_local = params->is_local.get() ? *params->is_local : false;
if (is_local) {
scoped_ptr<DeviceInfo> device =
GetLocalDeviceInfo(extension_id(), GetProfile());
base::ListValue* result = new base::ListValue();
if (device.get()) {
result->Append(device->ToValue());
}
SetResult(result);
return true;
}
ScopedVector<DeviceInfo> devices =
GetAllSignedInDevices(extension_id(), GetProfile());
scoped_ptr<base::ListValue> result(new base::ListValue());
for (ScopedVector<DeviceInfo>::const_iterator it = devices.begin();
it != devices.end();
++it) {
result->Append((*it)->ToValue());
}
SetResult(result.release());
return true;
}
} // namespace extensions
| bsd-3-clause |
B130296/CoreNLP | src/edu/stanford/nlp/parser/shiftreduce/ShiftReduceParserQuery.java | 9191 | package edu.stanford.nlp.parser.shiftreduce;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
import edu.stanford.nlp.ling.HasWord;
import edu.stanford.nlp.ling.Label;
import edu.stanford.nlp.ling.Sentence;
import edu.stanford.nlp.parser.KBestViterbiParser;
import edu.stanford.nlp.parser.common.ParserConstraint;
import edu.stanford.nlp.parser.common.ParserQuery;
import edu.stanford.nlp.parser.lexparser.Debinarizer;
import edu.stanford.nlp.trees.Tree;
import edu.stanford.nlp.trees.tregex.TregexPattern;
import edu.stanford.nlp.trees.tregex.tsurgeon.Tsurgeon;
import edu.stanford.nlp.trees.tregex.tsurgeon.TsurgeonPattern;
import edu.stanford.nlp.util.Generics;
import edu.stanford.nlp.util.ScoredComparator;
import edu.stanford.nlp.util.ScoredObject;
public class ShiftReduceParserQuery implements ParserQuery {
Debinarizer debinarizer = new Debinarizer(false);
List<? extends HasWord> originalSentence;
private State initialState, finalState;
Tree debinarized;
boolean success;
boolean unparsable;
private List<State> bestParses;
final ShiftReduceParser parser;
List<ParserConstraint> constraints = null;
public ShiftReduceParserQuery(ShiftReduceParser parser) {
this.parser = parser;
}
@Override
public boolean parse(List<? extends HasWord> sentence) {
this.originalSentence = sentence;
initialState = ShiftReduceParser.initialStateFromTaggedSentence(sentence);
return parseInternal();
}
public boolean parse(Tree tree) {
this.originalSentence = tree.yieldHasWord();
initialState = ShiftReduceParser.initialStateFromGoldTagTree(tree);
return parseInternal();
}
// TODO: we are assuming that sentence final punctuation always has
// either . or PU as the tag.
private static TregexPattern rearrangeFinalPunctuationTregex =
TregexPattern.compile("__ !> __ <- (__=top <- (__ <<- (/[.]|PU/=punc < /[.!?。!?]/ ?> (__=single <: =punc))))");
private static TsurgeonPattern rearrangeFinalPunctuationTsurgeon =
Tsurgeon.parseOperation("[move punc >-1 top] [if exists single prune single]");
private boolean parseInternal() {
final int maxBeamSize = Math.max(parser.op.testOptions().beamSize, 1);
success = true;
unparsable = false;
PriorityQueue<State> beam = new PriorityQueue<State>(maxBeamSize + 1, ScoredComparator.ASCENDING_COMPARATOR);
beam.add(initialState);
// TODO: don't construct as many PriorityQueues
while (beam.size() > 0) {
// System.err.println("================================================");
// System.err.println("Current beam:");
// System.err.println(beam);
PriorityQueue<State> oldBeam = beam;
beam = new PriorityQueue<State>(maxBeamSize + 1, ScoredComparator.ASCENDING_COMPARATOR);
State bestState = null;
for (State state : oldBeam) {
Collection<ScoredObject<Integer>> predictedTransitions = parser.model.findHighestScoringTransitions(state, true, maxBeamSize, constraints);
// System.err.println("Examining state: " + state);
for (ScoredObject<Integer> predictedTransition : predictedTransitions) {
Transition transition = parser.model.transitionIndex.get(predictedTransition.object());
State newState = transition.apply(state, predictedTransition.score());
// System.err.println(" Transition: " + transition + " (" + predictedTransition.score() + ")");
if (bestState == null || bestState.score() < newState.score()) {
bestState = newState;
}
beam.add(newState);
if (beam.size() > maxBeamSize) {
beam.poll();
}
}
}
if (beam.size() == 0) {
// Oops, time for some fallback plan
// This can happen with the set of constraints given by the original paper
// For example, one particular French model had a situation where it would reach
// @Ssub @Ssub .
// without a left(Ssub) transition, so finishing the parse was impossible.
// This will probably result in a bad parse, but at least it
// will result in some sort of parse.
for (State state : oldBeam) {
Transition transition = parser.model.findEmergencyTransition(state, constraints);
if (transition != null) {
State newState = transition.apply(state);
if (bestState == null || bestState.score() < newState.score()) {
bestState = newState;
}
beam.add(newState);
}
}
}
// bestState == null only happens when we have failed to make progress, so quit
// If the bestState is finished, we are done
if (bestState == null || bestState.isFinished()) {
break;
}
}
if (beam.size() == 0) {
success = false;
unparsable = true;
debinarized = null;
finalState = null;
bestParses = Collections.emptyList();
} else {
// TODO: filter out beam elements that aren't finished
bestParses = Generics.newArrayList(beam);
Collections.sort(bestParses, beam.comparator());
Collections.reverse(bestParses);
finalState = bestParses.get(0);
debinarized = debinarizer.transformTree(finalState.stack.peek());
debinarized = Tsurgeon.processPattern(rearrangeFinalPunctuationTregex, rearrangeFinalPunctuationTsurgeon, debinarized);
}
return success;
}
/**
* TODO: if we add anything interesting to report, we should report it here
*/
@Override
public boolean parseAndReport(List<? extends HasWord> sentence, PrintWriter pwErr) {
boolean success = parse(sentence);
//System.err.println(getBestTransitionSequence());
//System.err.println(getBestBinarizedParse());
return success;
}
public Tree getBestBinarizedParse() {
return finalState.stack.peek();
}
public List<Transition> getBestTransitionSequence() {
return finalState.transitions.asList();
}
@Override
public double getPCFGScore() {
return finalState.score;
}
@Override
public Tree getBestParse() {
return debinarized;
}
/** TODO: can we get away with not calling this PCFG? */
@Override
public Tree getBestPCFGParse() {
return debinarized;
}
@Override
public Tree getBestDependencyParse(boolean debinarize) {
return null;
}
@Override
public Tree getBestFactoredParse() {
return null;
}
/** TODO: if this is a beam, return all equal parses */
@Override
public List<ScoredObject<Tree>> getBestPCFGParses() {
ScoredObject<Tree> parse = new ScoredObject<Tree>(debinarized, finalState.score);
return Collections.singletonList(parse);
}
@Override
public boolean hasFactoredParse() {
return false;
}
/** TODO: return more if this used a beam */
@Override
public List<ScoredObject<Tree>> getKBestPCFGParses(int kbestPCFG) {
ScoredObject<Tree> parse = new ScoredObject<Tree>(debinarized, finalState.score);
return Collections.singletonList(parse);
}
@Override
public List<ScoredObject<Tree>> getKGoodFactoredParses(int kbest) {
throw new UnsupportedOperationException();
}
@Override
public KBestViterbiParser getPCFGParser() {
// TODO: find some way to treat this as a KBestViterbiParser?
return null;
}
@Override
public KBestViterbiParser getDependencyParser() {
return null;
}
@Override
public KBestViterbiParser getFactoredParser() {
return null;
}
@Override
public void setConstraints(List<ParserConstraint> constraints) {
this.constraints = constraints;
}
@Override
public boolean saidMemMessage() {
return false;
}
@Override
public boolean parseSucceeded() {
return success;
}
/** TODO: skip sentences which are too long */
@Override
public boolean parseSkipped() {
return false;
}
@Override
public boolean parseFallback() {
return false;
}
/** TODO: add memory handling? */
@Override
public boolean parseNoMemory() {
return false;
}
@Override
public boolean parseUnparsable() {
return unparsable;
}
@Override
public List<? extends HasWord> originalSentence() {
return originalSentence;
}
/**
* TODO: clearly this should be a default method in ParserQuery once Java 8 comes out
*/
@Override
public void restoreOriginalWords(Tree tree) {
if (originalSentence == null || tree == null) {
return;
}
List<Tree> leaves = tree.getLeaves();
if (leaves.size() != originalSentence.size()) {
throw new IllegalStateException("originalWords and sentence of different sizes: " + originalSentence.size() + " vs. " + leaves.size() +
"\n Orig: " + Sentence.listToString(originalSentence) +
"\n Pars: " + Sentence.listToString(leaves));
}
// TODO: get rid of this cast
Iterator<? extends Label> wordsIterator = (Iterator<? extends Label>) originalSentence.iterator();
for (Tree leaf : leaves) {
leaf.setLabel(wordsIterator.next());
}
}
}
| gpl-2.0 |
greasydeal/darkstar | scripts/zones/Bostaunieux_Oubliette/mobs/Werebat.lua | 326 | -----------------------------------
-- Area: Bostaunieux Oubliette
-- MOB: Werebat
-----------------------------------
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
checkGoVregime(killer,mob,611,2);
end;
| gpl-3.0 |
Freedom-FD/freedom | upload/admin/controller/extension/payment/pp_express.php | 61653 | <?php
class ControllerExtensionPaymentPPExpress extends Controller {
private $error = array();
public function index() {
$this->load->language('extension/payment/pp_express');
$this->document->setTitle($this->language->get('heading_title'));
$this->load->model('setting/setting');
if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validate()) {
$this->model_setting_setting->editSetting('pp_express', $this->request->post);
$this->session->data['success'] = $this->language->get('text_success');
$this->response->redirect($this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=payment', true));
}
$data['heading_title'] = $this->language->get('heading_title');
$data['text_edit'] = $this->language->get('text_edit');
$data['text_signup'] = $this->language->get('text_signup');
$data['text_sandbox'] = $this->language->get('text_sandbox');
$data['text_enabled'] = $this->language->get('text_enabled');
$data['text_disabled'] = $this->language->get('text_disabled');
$data['text_all_zones'] = $this->language->get('text_all_zones');
$data['text_yes'] = $this->language->get('text_yes');
$data['text_no'] = $this->language->get('text_no');
$data['text_authorization'] = $this->language->get('text_authorization');
$data['text_sale'] = $this->language->get('text_sale');
$data['entry_username'] = $this->language->get('entry_username');
$data['entry_password'] = $this->language->get('entry_password');
$data['entry_signature'] = $this->language->get('entry_signature');
$data['entry_sandbox_username'] = $this->language->get('entry_sandbox_username');
$data['entry_sandbox_password'] = $this->language->get('entry_sandbox_password');
$data['entry_sandbox_signature'] = $this->language->get('entry_sandbox_signature');
$data['entry_ipn'] = $this->language->get('entry_ipn');
$data['entry_test'] = $this->language->get('entry_test');
$data['entry_debug'] = $this->language->get('entry_debug');
$data['entry_currency'] = $this->language->get('entry_currency');
$data['entry_recurring_cancel'] = $this->language->get('entry_recurring_cancel');
$data['entry_transaction'] = $this->language->get('entry_transaction');
$data['entry_total'] = $this->language->get('entry_total');
$data['entry_geo_zone'] = $this->language->get('entry_geo_zone');
$data['entry_status'] = $this->language->get('entry_status');
$data['entry_sort_order'] = $this->language->get('entry_sort_order');
$data['entry_canceled_reversal_status'] = $this->language->get('entry_canceled_reversal_status');
$data['entry_completed_status'] = $this->language->get('entry_completed_status');
$data['entry_denied_status'] = $this->language->get('entry_denied_status');
$data['entry_expired_status'] = $this->language->get('entry_expired_status');
$data['entry_failed_status'] = $this->language->get('entry_failed_status');
$data['entry_pending_status'] = $this->language->get('entry_pending_status');
$data['entry_processed_status'] = $this->language->get('entry_processed_status');
$data['entry_refunded_status'] = $this->language->get('entry_refunded_status');
$data['entry_reversed_status'] = $this->language->get('entry_reversed_status');
$data['entry_voided_status'] = $this->language->get('entry_voided_status');
$data['entry_allow_notes'] = $this->language->get('entry_allow_notes');
$data['entry_logo'] = $this->language->get('entry_logo');
$data['entry_colour'] = $this->language->get('entry_colour');
$data['help_total'] = $this->language->get('help_total');
$data['help_ipn'] = $this->language->get('help_ipn');
$data['help_currency'] = $this->language->get('help_currency');
$data['help_logo'] = $this->language->get('help_logo');
$data['help_colour'] = $this->language->get('help_colour');
$data['button_save'] = $this->language->get('button_save');
$data['button_cancel'] = $this->language->get('button_cancel');
$data['button_search'] = $this->language->get('button_search');
$data['tab_api'] = $this->language->get('tab_api');
$data['tab_general'] = $this->language->get('tab_general');
$data['tab_order_status'] = $this->language->get('tab_order_status');
$data['tab_checkout'] = $this->language->get('tab_checkout');
$data['token'] = $this->session->data['token'];
if (isset($this->error['warning'])) {
$data['error_warning'] = $this->error['warning'];
} else {
$data['error_warning'] = '';
}
if (isset($this->error['username'])) {
$data['error_username'] = $this->error['username'];
} else {
$data['error_username'] = '';
}
if (isset($this->error['password'])) {
$data['error_password'] = $this->error['password'];
} else {
$data['error_password'] = '';
}
if (isset($this->error['signature'])) {
$data['error_signature'] = $this->error['signature'];
} else {
$data['error_signature'] = '';
}
if (isset($this->error['sandbox_username'])) {
$data['error_sandbox_username'] = $this->error['sandbox_username'];
} else {
$data['error_sandbox_username'] = '';
}
if (isset($this->error['sandbox_password'])) {
$data['error_sandbox_password'] = $this->error['sandbox_password'];
} else {
$data['error_sandbox_password'] = '';
}
if (isset($this->error['sandbox_signature'])) {
$data['error_sandbox_signature'] = $this->error['sandbox_signature'];
} else {
$data['error_sandbox_signature'] = '';
}
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_extension'),
'href' => $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=payment', true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true),
);
$data['action'] = $this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true);
$data['cancel'] = $this->url->link('extension/extension', 'token=' . $this->session->data['token'] . '&type=payment', true);
$data['search'] = $this->url->link('extension/payment/pp_express/search', 'token=' . $this->session->data['token'], true);
$this->load->model('localisation/country');
$country_info = $this->model_localisation_country->getCountry($this->config->get('config_country_id'));
$data['signup'] = 'https://www.paypal.com/webapps/merchantboarding/webflow/externalpartnerflow?countryCode=' . $country_info['iso_code_2'] . '&integrationType=F&merchantId=David111&displayMode=minibrowser&partnerId=9PDNYE4RZBVFJ&productIntentID=addipmt&receiveCredentials=TRUE&returnToPartnerUrl=' . base64_encode(html_entity_decode($this->url->link('extension/payment/pp_express/live', 'token=' . $this->session->data['token'], true))) . '&subIntegrationType=S';
$data['sandbox'] = 'https://www.sandbox.paypal.com/webapps/merchantboarding/webflow/externalpartnerflow?countryCode=' . $country_info['iso_code_2'] . '&integrationType=F&merchantId=David111&displayMode=minibrowser&partnerId=T4E8WSXT43QPJ&productIntentID=addipmt&receiveCredentials=TRUE&returnToPartnerUrl=' . base64_encode(html_entity_decode($this->url->link('extension/payment/pp_express/sandbox', 'token=' . $this->session->data['token'], true))) . '&subIntegrationType=S';
if (isset($this->request->post['pp_express_username'])) {
$data['pp_express_username'] = $this->request->post['pp_express_username'];
} else {
$data['pp_express_username'] = $this->config->get('pp_express_username');
}
if (isset($this->request->post['pp_express_password'])) {
$data['pp_express_password'] = $this->request->post['pp_express_password'];
} else {
$data['pp_express_password'] = $this->config->get('pp_express_password');
}
if (isset($this->request->post['pp_express_signature'])) {
$data['pp_express_signature'] = $this->request->post['pp_express_signature'];
} else {
$data['pp_express_signature'] = $this->config->get('pp_express_signature');
}
if (isset($this->request->post['pp_express_sandbox_username'])) {
$data['pp_express_sandbox_username'] = $this->request->post['pp_express_sandbox_username'];
} else {
$data['pp_express_sandbox_username'] = $this->config->get('pp_express_sandbox_username');
}
if (isset($this->request->post['pp_express_sandbox_password'])) {
$data['pp_express_sandbox_password'] = $this->request->post['pp_express_sandbox_password'];
} else {
$data['pp_express_sandbox_password'] = $this->config->get('pp_express_sandbox_password');
}
if (isset($this->request->post['pp_express_sandbox_signature'])) {
$data['pp_express_sandbox_signature'] = $this->request->post['pp_express_sandbox_signature'];
} else {
$data['pp_express_sandbox_signature'] = $this->config->get('pp_express_sandbox_signature');
}
$data['ipn_url'] = HTTPS_CATALOG . 'index.php?route=extension/payment/pp_express/ipn';
if (isset($this->request->post['pp_express_test'])) {
$data['pp_express_test'] = $this->request->post['pp_express_test'];
} else {
$data['pp_express_test'] = $this->config->get('pp_express_test');
}
if (isset($this->request->post['pp_express_debug'])) {
$data['pp_express_debug'] = $this->request->post['pp_express_debug'];
} else {
$data['pp_express_debug'] = $this->config->get('pp_express_debug');
}
if (isset($this->request->post['pp_express_currency'])) {
$data['pp_express_currency'] = $this->request->post['pp_express_currency'];
} else {
$data['pp_express_currency'] = $this->config->get('pp_express_currency');
}
$this->load->model('extension/payment/pp_express');
$data['currencies'] = $this->model_extension_payment_pp_express->getCurrencies();
if (isset($this->request->post['pp_express_recurring_cancel'])) {
$data['pp_express_recurring_cancel'] = $this->request->post['pp_express_recurring_cancel'];
} else {
$data['pp_express_recurring_cancel'] = $this->config->get('pp_express_recurring_cancel');
}
if (isset($this->request->post['pp_express_transaction'])) {
$data['pp_express_transaction'] = $this->request->post['pp_express_transaction'];
} else {
$data['pp_express_transaction'] = $this->config->get('pp_express_transaction');
}
if (isset($this->request->post['pp_express_total'])) {
$data['pp_express_total'] = $this->request->post['pp_express_total'];
} else {
$data['pp_express_total'] = $this->config->get('pp_express_total');
}
if (isset($this->request->post['pp_express_geo_zone_id'])) {
$data['pp_express_geo_zone_id'] = $this->request->post['pp_express_geo_zone_id'];
} else {
$data['pp_express_geo_zone_id'] = $this->config->get('pp_express_geo_zone_id');
}
$this->load->model('localisation/geo_zone');
$data['geo_zones'] = $this->model_localisation_geo_zone->getGeoZones();
if (isset($this->request->post['pp_express_status'])) {
$data['pp_express_status'] = $this->request->post['pp_express_status'];
} else {
$data['pp_express_status'] = $this->config->get('pp_express_status');
}
if (isset($this->request->post['pp_express_sort_order'])) {
$data['pp_express_sort_order'] = $this->request->post['pp_express_sort_order'];
} else {
$data['pp_express_sort_order'] = $this->config->get('pp_express_sort_order');
}
if (isset($this->request->post['pp_express_canceled_reversal_status_id'])) {
$data['pp_express_canceled_reversal_status_id'] = $this->request->post['pp_express_canceled_reversal_status_id'];
} else {
$data['pp_express_canceled_reversal_status_id'] = $this->config->get('pp_express_canceled_reversal_status_id');
}
if (isset($this->request->post['pp_express_completed_status_id'])) {
$data['pp_express_completed_status_id'] = $this->request->post['pp_express_completed_status_id'];
} else {
$data['pp_express_completed_status_id'] = $this->config->get('pp_express_completed_status_id');
}
if (isset($this->request->post['pp_express_denied_status_id'])) {
$data['pp_express_denied_status_id'] = $this->request->post['pp_express_denied_status_id'];
} else {
$data['pp_express_denied_status_id'] = $this->config->get('pp_express_denied_status_id');
}
if (isset($this->request->post['pp_express_expired_status_id'])) {
$data['pp_express_expired_status_id'] = $this->request->post['pp_express_expired_status_id'];
} else {
$data['pp_express_expired_status_id'] = $this->config->get('pp_express_expired_status_id');
}
if (isset($this->request->post['pp_express_failed_status_id'])) {
$data['pp_express_failed_status_id'] = $this->request->post['pp_express_failed_status_id'];
} else {
$data['pp_express_failed_status_id'] = $this->config->get('pp_express_failed_status_id');
}
if (isset($this->request->post['pp_express_pending_status_id'])) {
$data['pp_express_pending_status_id'] = $this->request->post['pp_express_pending_status_id'];
} else {
$data['pp_express_pending_status_id'] = $this->config->get('pp_express_pending_status_id');
}
if (isset($this->request->post['pp_express_processed_status_id'])) {
$data['pp_express_processed_status_id'] = $this->request->post['pp_express_processed_status_id'];
} else {
$data['pp_express_processed_status_id'] = $this->config->get('pp_express_processed_status_id');
}
if (isset($this->request->post['pp_express_refunded_status_id'])) {
$data['pp_express_refunded_status_id'] = $this->request->post['pp_express_refunded_status_id'];
} else {
$data['pp_express_refunded_status_id'] = $this->config->get('pp_express_refunded_status_id');
}
if (isset($this->request->post['pp_express_reversed_status_id'])) {
$data['pp_express_reversed_status_id'] = $this->request->post['pp_express_reversed_status_id'];
} else {
$data['pp_express_reversed_status_id'] = $this->config->get('pp_express_reversed_status_id');
}
if (isset($this->request->post['pp_express_voided_status_id'])) {
$data['pp_express_voided_status_id'] = $this->request->post['pp_express_voided_status_id'];
} else {
$data['pp_express_voided_status_id'] = $this->config->get('pp_express_voided_status_id');
}
$this->load->model('localisation/order_status');
$data['order_statuses'] = $this->model_localisation_order_status->getOrderStatuses();
if (isset($this->request->post['pp_express_allow_note'])) {
$data['pp_express_allow_note'] = $this->request->post['pp_express_allow_note'];
} else {
$data['pp_express_allow_note'] = $this->config->get('pp_express_allow_note');
}
if (isset($this->request->post['pp_express_colour'])) {
$data['pp_express_colour'] = str_replace('#', '', $this->request->post['pp_express_colour']);
} else {
$data['pp_express_colour'] = $this->config->get('pp_express_colour');
}
if (isset($this->request->post['pp_express_logo'])) {
$data['pp_express_logo'] = $this->request->post['pp_express_logo'];
} else {
$data['pp_express_logo'] = $this->config->get('pp_express_logo');
}
$this->load->model('tool/image');
if (isset($this->request->post['pp_express_logo']) && is_file(DIR_IMAGE . $this->request->post['pp_express_logo'])) {
$data['thumb'] = $this->model_tool_image->resize($this->request->post['pp_express_logo'], 750, 90);
} elseif (is_file(DIR_IMAGE . $this->config->get('pp_express_logo'))) {
$data['thumb'] = $this->model_tool_image->resize($this->config->get('pp_express_logo'), 750, 90);
} else {
$data['thumb'] = $this->model_tool_image->resize('no_image.png', 750, 90);
}
$data['placeholder'] = $this->model_tool_image->resize('no_image.png', 750, 90);
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('extension/payment/pp_express', $data));
}
protected function validate() {
if (!$this->user->hasPermission('modify', 'extension/payment/pp_express')) {
$this->error['warning'] = $this->language->get('error_permission');
}
if ($this->request->post['pp_express_test']) {
if (!$this->request->post['pp_express_sandbox_username']) {
$this->error['sandbox_username'] = $this->language->get('error_sandbox_username');
}
if (!$this->request->post['pp_express_sandbox_password']) {
$this->error['sandbox_password'] = $this->language->get('error_sandbox_password');
}
if (!$this->request->post['pp_express_sandbox_signature']) {
$this->error['sandbox_signature'] = $this->language->get('error_sandbox_signature');
}
} else {
if (!$this->request->post['pp_express_username']) {
$this->error['username'] = $this->language->get('error_username');
}
if (!$this->request->post['pp_express_password']) {
$this->error['password'] = $this->language->get('error_password');
}
if (!$this->request->post['pp_express_signature']) {
$this->error['signature'] = $this->language->get('error_signature');
}
}
return !$this->error;
}
public function install() {
$this->load->model('extension/payment/pp_express');
$this->model_extension_payment_pp_express->install();
}
public function uninstall() {
$this->load->model('extension/payment/pp_express');
$this->model_extension_payment_pp_express->uninstall();
}
public function order() {
if ($this->config->get('pp_express_status')) {
$this->load->language('extension/payment/pp_express_order');
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('extension/payment/pp_express');
$paypal_info = $this->model_extension_payment_pp_express->getPayPalOrder($order_id);
if ($paypal_info) {
$data['text_payment'] = $this->language->get('text_payment');
$data['text_capture'] = $this->language->get('text_capture');
$data['text_transaction'] = $this->language->get('text_transaction');
$data['text_capture_status'] = $this->language->get('text_capture_status');
$data['text_amount_authorised'] = $this->language->get('text_amount_authorised');
$data['text_amount_captured'] = $this->language->get('text_amount_captured');
$data['text_amount_refunded'] = $this->language->get('text_amount_refunded');
$data['text_confirm_void'] = $this->language->get('text_confirm_void');
$data['text_full_refund'] = $this->language->get('text_full_refund');
$data['text_partial_refund'] = $this->language->get('text_partial_refund');
$data['text_loading'] = $this->language->get('text_loading');
$data['entry_capture_amount'] = $this->language->get('entry_capture_amount');
$data['entry_capture_complete'] = $this->language->get('entry_capture_complete');
$data['entry_full_refund'] = $this->language->get('entry_full_refund');
$data['entry_note'] = $this->language->get('entry_note');
$data['entry_amount'] = $this->language->get('entry_amount');
$data['button_capture'] = $this->language->get('button_capture');
$data['button_refund'] = $this->language->get('button_refund');
$data['button_void'] = $this->language->get('button_void');
$data['tab_capture'] = $this->language->get('tab_capture');
$data['tab_refund'] = $this->language->get('tab_refund');
$data['token'] = $this->session->data['token'];
$data['order_id'] = $this->request->get['order_id'];
$data['capture_status'] = $paypal_info['capture_status'];
$data['total'] = $paypal_info['total'];
$captured = number_format($this->model_extension_payment_pp_express->getCapturedTotal($paypal_info['paypal_order_id']), 2);
$data['captured'] = $captured;
$data['capture_remaining'] = number_format($paypal_info['total'] - $captured, 2);
$refunded = number_format($this->model_extension_payment_pp_express->getRefundedTotal($paypal_info['paypal_order_id']), 2);
$data['refunded'] = $refunded;
return $this->load->view('extension/payment/pp_express_order', $data);
}
}
}
public function transaction() {
$this->load->language('extension/payment/pp_express_order');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['column_transaction'] = $this->language->get('column_transaction');
$data['column_amount'] = $this->language->get('column_amount');
$data['column_type'] = $this->language->get('column_type');
$data['column_status'] = $this->language->get('column_status');
$data['column_pending_reason'] = $this->language->get('column_pending_reason');
$data['column_date_added'] = $this->language->get('column_date_added');
$data['column_action'] = $this->language->get('column_action');
$data['button_view'] = $this->language->get('button_view');
$data['button_refund'] = $this->language->get('button_refund');
$data['button_resend'] = $this->language->get('button_resend');
$data['transactions'] = array();
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('extension/payment/pp_express');
$paypal_info = $this->model_extension_payment_pp_express->getOrder($order_id);
if ($paypal_info) {
$results = $this->model_extension_payment_pp_express->getTransactions($paypal_info['paypal_order_id']);
foreach ($results as $result) {
$data['transactions'][] = array(
'transaction_id' => $result['transaction_id'],
'amount' => $result['amount'],
'payment_type' => $result['payment_type'],
'payment_status' => $result['payment_status'],
'pending_reason' => $result['pending_reason'],
'date_added' => date($this->language->get('datetime_format'), strtotime($result['date_added'])),
'view' => $this->url->link('extension/payment/pp_express/info', 'token=' . $this->session->data['token'] . '&transaction_id=' . $result['transaction_id'], true),
'refund' => $this->url->link('extension/payment/pp_express/refund', 'token=' . $this->session->data['token'] . '&transaction_id=' . $result['transaction_id'], true),
'resend' => $this->url->link('extension/payment/pp_express/resend', 'token=' . $this->session->data['token'] . '&paypal_order_transaction_id=' . $result['paypal_order_transaction_id'], true)
);
}
}
$this->response->setOutput($this->load->view('extension/payment/pp_express_transaction', $data));
}
public function capture() {
$json = array();
$this->load->language('extension/payment/pp_express_order');
if (!isset($this->request->post['amount']) && $this->request->post['amount'] > 0) {
$json['error'] = $this->language->get('error_capture');
}
if (!$json) {
$this->load->model('extension/payment/pp_express');
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$paypal_info = $this->model_extension_payment_pp_express->getOrder($order_id);
if ($paypal_info) {
// If this is the final amount to capture or not
if ($this->request->post['complete'] == 1) {
$complete = 'Complete';
} else {
$complete = 'NotComplete';
}
$request = array(
'METHOD' => 'DoCapture',
'AUTHORIZATIONID' => $paypal_info['authorization_id'],
'AMT' => number_format($this->request->post['amount'], 2),
'CURRENCYCODE' => $paypal_info['currency_code'],
'COMPLETETYPE' => $complete,
'MSGSUBID' => uniqid(mt_rand(), true)
);
$response = $this->model_extension_payment_pp_express->call($request);
if (isset($response['ACK']) && ($response['ACK'] != 'Failure') && ($response['ACK'] != 'FailureWithWarning')) {
$transaction_data = array(
'paypal_order_id' => $paypal_info['paypal_order_id'],
'transaction_id' => $response['TRANSACTIONID'],
'parent_id' => $paypal_info['authorization_id'],
'note' => '',
'msgsubid' => $response['MSGSUBID'],
'receipt_id' => '',
'payment_type' => $response['PAYMENTTYPE'],
'payment_status' => $response['PAYMENTSTATUS'],
'pending_reason' => (isset($response['PENDINGREASON']) ? $response['PENDINGREASON'] : ''),
'transaction_entity' => 'payment',
'amount' => $response['AMT'],
'debug_data' => json_encode($response)
);
$this->model_extension_payment_pp_express->addTransaction($transaction_data);
$captured = number_format($this->model_extension_payment_pp_express->getCapturedTotal($paypal_info['paypal_order_id']), 2);
$refunded = number_format($this->model_extension_payment_pp_express->getRefundedTotal($paypal_info['paypal_order_id']), 2);
$json['captured'] = $captured;
$json['refunded'] = $refunded;
$json['remaining'] = number_format($paypal_info['total'] - $captured, 2);
if ($this->request->post['complete'] == 1 || $json['remaining'] == 0.00) {
$json['capture_status'] = $this->language->get('text_complete');
$this->model_extension_payment_pp_express->editPayPalOrderStatus($order_id, 'Complete');
}
$json['success'] = $this->language->get('text_success');
} else {
$json['error'] = (isset($response_info['L_SHORTMESSAGE0']) ? $response_info['L_SHORTMESSAGE0'] : $this->language->get('error_transaction'));
}
} else {
$json['error'] = $this->language->get('error_not_found');
}
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function refund() {
$this->load->language('extension/payment/pp_express_refund');
$this->document->setTitle($this->language->get('heading_title'));
$data['heading_title'] = $this->language->get('heading_title');
$data['button_cancel'] = $this->language->get('button_cancel');
$data['entry_transaction_id'] = $this->language->get('entry_transaction_id');
$data['entry_full_refund'] = $this->language->get('entry_full_refund');
$data['entry_amount'] = $this->language->get('entry_amount');
$data['entry_message'] = $this->language->get('entry_message');
$data['button_refund'] = $this->language->get('button_refund');
$data['text_refund'] = $this->language->get('text_refund');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_pp_express'),
'href' => $this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/payment/pp_express/refund', 'token=' . $this->session->data['token'], true),
);
//button actions
$data['action'] = $this->url->link('extension/payment/pp_express/doRefund', 'token=' . $this->session->data['token'], true);
$data['cancel'] = $this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true);
$data['transaction_id'] = $this->request->get['transaction_id'];
$this->load->model('extension/payment/pp_express');
$pp_transaction = $this->model_extension_payment_pp_express->getTransaction($this->request->get['transaction_id']);
$data['amount_original'] = $pp_transaction['AMT'];
$data['currency_code'] = $pp_transaction['CURRENCYCODE'];
$refunded = number_format($this->model_extension_payment_pp_express->getRefundedTotalByParentId($this->request->get['transaction_id']), 2);
if ($refunded != 0.00) {
$data['refund_available'] = number_format($data['amount_original'] + $refunded, 2);
$data['attention'] = $this->language->get('text_current_refunds') . ': ' . $data['refund_available'];
} else {
$data['refund_available'] = '';
$data['attention'] = '';
}
$data['token'] = $this->session->data['token'];
if (isset($this->session->data['error'])) {
$data['error'] = $this->session->data['error'];
unset($this->session->data['error']);
} else {
$data['error'] = '';
}
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('extension/payment/pp_express_refund', $data));
}
public function doRefund() {
/**
* used to issue a refund for a captured payment
*
* refund can be full or partial
*/
if (isset($this->request->post['transaction_id']) && isset($this->request->post['refund_full'])) {
$this->load->model('extension/payment/pp_express');
$this->load->language('extension/payment/pp_express_refund');
if ($this->request->post['refund_full'] == 0 && $this->request->post['amount'] == 0) {
$this->session->data['error'] = $this->language->get('error_partial_amt');
} else {
$order_id = $this->model_extension_payment_pp_express->getOrderId($this->request->post['transaction_id']);
$paypal_order = $this->model_extension_payment_pp_express->getOrder($order_id);
if ($paypal_order) {
$call_data = array();
$call_data['METHOD'] = 'RefundTransaction';
$call_data['TRANSACTIONID'] = $this->request->post['transaction_id'];
$call_data['NOTE'] = urlencode($this->request->post['refund_message']);
$call_data['MSGSUBID'] = uniqid(mt_rand(), true);
$current_transaction = $this->model_extension_payment_pp_express->getLocalTransaction($this->request->post['transaction_id']);
if ($this->request->post['refund_full'] == 1) {
$call_data['REFUNDTYPE'] = 'Full';
} else {
$call_data['REFUNDTYPE'] = 'Partial';
$call_data['AMT'] = number_format($this->request->post['amount'], 2);
$call_data['CURRENCYCODE'] = $this->request->post['currency_code'];
}
$result = $this->model_extension_payment_pp_express->call($call_data);
$transaction = array(
'paypal_order_id' => $paypal_order['paypal_order_id'],
'transaction_id' => '',
'parent_transaction_id' => $this->request->post['transaction_id'],
'note' => $this->request->post['refund_message'],
'msgsubid' => $call_data['MSGSUBID'],
'receipt_id' => '',
'payment_type' => '',
'payment_status' => 'Refunded',
'transaction_entity' => 'payment',
'pending_reason' => '',
'amount' => '-' . (isset($call_data['AMT']) ? $call_data['AMT'] : $current_transaction['amount']),
'debug_data' => json_encode($result)
);
if ($result == false) {
$transaction['payment_status'] = 'Failed';
$this->model_extension_payment_pp_express->addTransaction($transaction, $call_data);
$this->response->redirect($this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $paypal_order['order_id'], true));
} else if ($result['ACK'] != 'Failure' && $result['ACK'] != 'FailureWithWarning') {
$transaction['transaction_id'] = $result['REFUNDTRANSACTIONID'];
$transaction['payment_type'] = $result['REFUNDSTATUS'];
$transaction['pending_reason'] = $result['PENDINGREASON'];
$transaction['amount'] = '-' . $result['GROSSREFUNDAMT'];
$this->model_extension_payment_pp_express->addTransaction($transaction);
//edit transaction to refunded status
if ($result['TOTALREFUNDEDAMOUNT'] == $this->request->post['amount_original']) {
$this->db->query("UPDATE `" . DB_PREFIX . "paypal_order_transaction` SET `payment_status` = 'Refunded' WHERE `transaction_id` = '" . $this->db->escape($this->request->post['transaction_id']) . "' LIMIT 1");
} else {
$this->db->query("UPDATE `" . DB_PREFIX . "paypal_order_transaction` SET `payment_status` = 'Partially-Refunded' WHERE `transaction_id` = '" . $this->db->escape($this->request->post['transaction_id']) . "' LIMIT 1");
}
//redirect back to the order
$this->response->redirect($this->url->link('sale/order/info', 'token=' . $this->session->data['token'] . '&order_id=' . $paypal_order['order_id'], true));
} else {
$this->model_extension_payment_pp_express->log(json_encode($result));
$this->session->data['error'] = (isset($result['L_SHORTMESSAGE0']) ? $result['L_SHORTMESSAGE0'] : 'There was an error') . (isset($result['L_LONGMESSAGE0']) ? '<br />' . $result['L_LONGMESSAGE0'] : '');
$this->response->redirect($this->url->link('extension/payment/pp_express/refund', 'token=' . $this->session->data['token'] . '&transaction_id=' . $this->request->post['transaction_id'], true));
}
} else {
$this->session->data['error'] = $this->language->get('error_data_missing');
$this->response->redirect($this->url->link('extension/payment/pp_express/refund', 'token=' . $this->session->data['token'] . '&transaction_id=' . $this->request->post['transaction_id'], true));
}
}
} else {
$this->session->data['error'] = $this->language->get('error_data');
$this->response->redirect($this->url->link('extension/payment/pp_express/refund', 'token=' . $this->session->data['token'] . '&transaction_id=' . $this->request->post['transaction_id'], true));
}
}
/**
* used to void an authorised payment
*/
public function void() {
$json = array();
$this->load->language('extension/payment/pp_express_order');
if (isset($this->request->get['order_id'])) {
$order_id = $this->request->get['order_id'];
} else {
$order_id = 0;
}
$this->load->model('extension/payment/pp_express');
$paypal_info = $this->model_extension_payment_pp_express->getOrder($order_id);
if ($paypal_info) {
$request = array(
'METHOD' => 'DoVoid',
'AUTHORIZATIONID' => $paypal_info['authorization_id'],
'MSGSUBID' => uniqid(mt_rand(), true)
);
$response_info = $this->model_extension_payment_pp_express->call($request);
if (isset($response_info['ACK']) && ($response_info['ACK'] != 'Failure') && ($response_info['ACK'] != 'FailureWithWarning')) {
$transaction = array(
'paypal_order_id' => $paypal_info['paypal_order_id'],
'transaction_id' => '',
'parent_id' => $paypal_info['authorization_id'],
'note' => '',
'msgsubid' => '',
'receipt_id' => '',
'payment_type' => 'void',
'payment_status' => 'Void',
'pending_reason' => '',
'transaction_entity' => 'auth',
'amount' => '',
'debug_data' => json_encode($response_info)
);
$this->model_extension_payment_pp_express->addTransaction($transaction);
$this->model_extension_payment_pp_express->editPayPalOrderStatus($order_id, 'Complete');
$json['capture_status'] = 'Complete';
$json['success'] = $this->language->get('text_success');
} else {
$json['error'] = (isset($result['L_SHORTMESSAGE0']) ? $result['L_SHORTMESSAGE0'] : $this->language->get('error_transaction'));
}
} else {
$json['error'] = $this->language->get('error_not_found');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
// Cancel an active recurring
public function recurringCancel() {
$json = array();
$this->load->language('extension/recurring/pp_express');
//cancel an active recurring
$this->load->model('account/recurring');
if (isset($this->request->get['order_recurring_id'])) {
$order_recurring_id = $this->request->get['order_recurring_id'];
} else {
$order_recurring_id = 0;
}
$recurring_info = $this->model_account_recurring->getOrderRecurring($order_recurring_id);
if ($recurring_info && $recurring_info['reference']) {
if ($this->config->get('pp_express_test')) {
$api_url = 'https://api-3t.sandbox.paypal.com/nvp';
$api_username = $this->config->get('pp_express_sandbox_username');
$api_password = $this->config->get('pp_express_sandbox_password');
$api_signature = $this->config->get('pp_express_sandbox_signature');
} else {
$api_url = 'https://api-3t.paypal.com/nvp';
$api_username = $this->config->get('pp_express_username');
$api_password = $this->config->get('pp_express_password');
$api_signature = $this->config->get('pp_express_signature');
}
$request = array(
'USER' => $api_username,
'PWD' => $api_password,
'SIGNATURE' => $api_signature,
'VERSION' => '109.0',
'BUTTONSOURCE' => 'OpenCart_2.0_EC',
'METHOD' => 'SetExpressCheckout',
'METHOD' => 'ManageRecurringPaymentsProfileStatus',
'PROFILEID' => $recurring_info['reference'],
'ACTION' => 'Cancel'
);
$curl = curl_init($api_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($curl);
if (!$response) {
$this->log(sprintf($this->language->get('error_curl'), curl_errno($curl), curl_error($curl)));
}
curl_close($curl);
$response_info = array();
parse_str($response, $response_info);
if (isset($response_info['PROFILEID'])) {
$this->model_account_recurring->editOrderRecurringStatus($order_recurring_id, 4);
$this->model_account_recurring->addOrderRecurringTransaction($order_recurring_id, 5);
$json['success'] = $this->language->get('text_cancelled');
} else {
$json['error'] = sprintf($this->language->get('error_not_cancelled'), $response_info['L_LONGMESSAGE0']);
}
} else {
$json['error'] = $this->language->get('error_not_found');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function resend() {
$json = array();
$this->load->language('extension/payment/pp_express');
if (isset($this->request->get['paypal_order_transaction_id'])) {
$paypal_order_transaction_id = $this->request->get['paypal_order_transaction_id'];
} else {
$paypal_order_transaction_id = 0;
}
$this->load->model('extension/payment/pp_express');
$transaction = $this->model_extension_payment_pp_express->getFailedTransaction($paypal_order_transaction_id);
if ($transaction) {
$call_data = json_decode($transaction['call_data'], true);
$result = $this->model_extension_payment_pp_express->call($call_data);
if ($response_info) {
$parent_transaction = $this->model_extension_payment_pp_express->getLocalTransaction($transaction['parent_id']);
if ($parent_transaction['amount'] == abs($transaction['amount'])) {
$this->db->query("UPDATE `" . DB_PREFIX . "paypal_order_transaction` SET `payment_status` = 'Refunded' WHERE `transaction_id` = '" . $this->db->escape($transaction['parent_id']) . "' LIMIT 1");
} else {
$this->db->query("UPDATE `" . DB_PREFIX . "paypal_order_transaction` SET `payment_status` = 'Partially-Refunded' WHERE `transaction_id` = '" . $this->db->escape($transaction['parent_id']) . "' LIMIT 1");
}
if (isset($result['REFUNDTRANSACTIONID'])) {
$transaction['transaction_id'] = $result['REFUNDTRANSACTIONID'];
} else {
$transaction['transaction_id'] = $result['TRANSACTIONID'];
}
if (isset($result['PAYMENTTYPE'])) {
$transaction['payment_type'] = $result['PAYMENTTYPE'];
} else {
$transaction['payment_type'] = $result['REFUNDSTATUS'];
}
if (isset($result['PAYMENTSTATUS'])) {
$transaction['payment_status'] = $result['PAYMENTSTATUS'];
} else {
$transaction['payment_status'] = 'Refunded';
}
if (isset($result['AMT'])) {
$transaction['amount'] = $result['AMT'];
} else {
$transaction['amount'] = $transaction['amount'];
}
$transaction['pending_reason'] = (isset($result['PENDINGREASON']) ? $result['PENDINGREASON'] : '');
$this->model_extension_payment_pp_express->updateTransaction($transaction);
$json['success'] = $this->language->get('success_transaction_resent');
} else {
$json['error'] = $this->language->get('error_timeout');
}
} else {
$json['error'] = $this->language->get('error_transaction_missing');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
public function search() {
$this->load->language('extension/payment/pp_express_search');
$this->document->setTitle($this->language->get('heading_title'));
$data['heading_title'] = $this->language->get('heading_title');
$data['text_buyer_info'] = $this->language->get('text_buyer_info');
$data['text_name'] = $this->language->get('text_name');
$data['text_searching'] = $this->language->get('text_searching');
$data['text_view'] = $this->language->get('text_view');
$data['text_format'] = $this->language->get('text_format');
$data['text_date_search'] = $this->language->get('text_date_search');
$data['text_no_results'] = $this->language->get('text_no_results');
$data['entry_date'] = $this->language->get('entry_date');
$data['entry_date_start'] = $this->language->get('entry_date_start');
$data['entry_date_end'] = $this->language->get('entry_date_end');
$data['entry_date_to'] = $this->language->get('entry_date_to');
$data['entry_transaction'] = $this->language->get('entry_transaction');
$data['entry_transaction_type'] = $this->language->get('entry_transaction_type');
$data['entry_transaction_status'] = $this->language->get('entry_transaction_status');
$data['entry_email'] = $this->language->get('entry_email');
$data['entry_email_buyer'] = $this->language->get('entry_email_buyer');
$data['entry_email_merchant'] = $this->language->get('entry_email_merchant');
$data['entry_receipt'] = $this->language->get('entry_receipt');
$data['entry_transaction_id'] = $this->language->get('entry_transaction_id');
$data['entry_invoice_no'] = $this->language->get('entry_invoice_no');
$data['entry_auction'] = $this->language->get('entry_auction');
$data['entry_amount'] = $this->language->get('entry_amount');
$data['entry_recurring_id'] = $this->language->get('entry_recurring_id');
$data['entry_firstname'] = $this->language->get('entry_firstname');
$data['entry_middlename'] = $this->language->get('entry_middlename');
$data['entry_lastname'] = $this->language->get('entry_lastname');
$data['entry_suffix'] = $this->language->get('entry_suffix');
$data['entry_salutation'] = $this->language->get('entry_salutation');
$data['entry_status_all'] = $this->language->get('entry_status_all');
$data['entry_status_pending'] = $this->language->get('entry_status_pending');
$data['entry_status_processing'] = $this->language->get('entry_status_processing');
$data['entry_status_success'] = $this->language->get('entry_status_success');
$data['entry_status_denied'] = $this->language->get('entry_status_denied');
$data['entry_status_reversed'] = $this->language->get('entry_status_reversed');
$data['entry_trans_all'] = $this->language->get('entry_trans_all');
$data['entry_trans_sent'] = $this->language->get('entry_trans_sent');
$data['entry_trans_received'] = $this->language->get('entry_trans_received');
$data['entry_trans_masspay'] = $this->language->get('entry_trans_masspay');
$data['entry_trans_money_req'] = $this->language->get('entry_trans_money_req');
$data['entry_trans_funds_add'] = $this->language->get('entry_trans_funds_add');
$data['entry_trans_funds_with'] = $this->language->get('entry_trans_funds_with');
$data['entry_trans_referral'] = $this->language->get('entry_trans_referral');
$data['entry_trans_fee'] = $this->language->get('entry_trans_fee');
$data['entry_trans_subscription'] = $this->language->get('entry_trans_subscription');
$data['entry_trans_dividend'] = $this->language->get('entry_trans_dividend');
$data['entry_trans_billpay'] = $this->language->get('entry_trans_billpay');
$data['entry_trans_refund'] = $this->language->get('entry_trans_refund');
$data['entry_trans_conv'] = $this->language->get('entry_trans_conv');
$data['entry_trans_bal_trans'] = $this->language->get('entry_trans_bal_trans');
$data['entry_trans_reversal'] = $this->language->get('entry_trans_reversal');
$data['entry_trans_shipping'] = $this->language->get('entry_trans_shipping');
$data['entry_trans_bal_affect'] = $this->language->get('entry_trans_bal_affect');
$data['entry_trans_echeque'] = $this->language->get('entry_trans_echeque');
$data['column_date'] = $this->language->get('column_date');
$data['column_type'] = $this->language->get('column_type');
$data['column_email'] = $this->language->get('column_email');
$data['column_name'] = $this->language->get('column_name');
$data['column_transid'] = $this->language->get('column_transid');
$data['column_status'] = $this->language->get('column_status');
$data['column_currency'] = $this->language->get('column_currency');
$data['column_amount'] = $this->language->get('column_amount');
$data['column_fee'] = $this->language->get('column_fee');
$data['column_netamt'] = $this->language->get('column_netamt');
$data['column_action'] = $this->language->get('column_action');
$data['button_search'] = $this->language->get('button_search');
$data['button_edit'] = $this->language->get('button_edit');
$data['token'] = $this->session->data['token'];
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_pp_express'),
'href' => $this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/payment/pp_express/search', 'token=' . $this->session->data['token'], true),
);
$this->load->model('extension/payment/pp_express');
$data['currency_codes'] = $this->model_extension_payment_pp_express->getCurrencies();
$data['default_currency'] = $this->config->get('pp_express_currency');
$data['date_start'] = date("Y-m-d", strtotime('-30 days'));
$data['date_end'] = date("Y-m-d");
$data['view_link'] = $this->url->link('extension/payment/pp_express/info', 'token=' . $this->session->data['token'], true);
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('extension/payment/pp_express_search', $data));
}
public function info() {
$this->load->language('extension/payment/pp_express_view');
$this->document->setTitle($this->language->get('heading_title'));
$data['heading_title'] = $this->language->get('heading_title');
$data['text_product_lines'] = $this->language->get('text_product_lines');
$data['text_ebay_txn_id'] = $this->language->get('text_ebay_txn_id');
$data['text_name'] = $this->language->get('text_name');
$data['text_qty'] = $this->language->get('text_qty');
$data['text_price'] = $this->language->get('text_price');
$data['text_number'] = $this->language->get('text_number');
$data['text_coupon_id'] = $this->language->get('text_coupon_id');
$data['text_coupon_amount'] = $this->language->get('text_coupon_amount');
$data['text_coupon_currency'] = $this->language->get('text_coupon_currency');
$data['text_loyalty_currency'] = $this->language->get('text_loyalty_currency');
$data['text_loyalty_disc_amt'] = $this->language->get('text_loyalty_disc_amt');
$data['text_options_name'] = $this->language->get('text_options_name');
$data['text_tax_amt'] = $this->language->get('text_tax_amt');
$data['text_currency_code'] = $this->language->get('text_currency_code');
$data['text_amount'] = $this->language->get('text_amount');
$data['text_gift_msg'] = $this->language->get('text_gift_msg');
$data['text_gift_receipt'] = $this->language->get('text_gift_receipt');
$data['text_gift_wrap_name'] = $this->language->get('text_gift_wrap_name');
$data['text_gift_wrap_amt'] = $this->language->get('text_gift_wrap_amt');
$data['text_buyer_email_market'] = $this->language->get('text_buyer_email_market');
$data['text_survey_question'] = $this->language->get('text_survey_question');
$data['text_survey_chosen'] = $this->language->get('text_survey_chosen');
$data['text_receiver_business'] = $this->language->get('text_receiver_business');
$data['text_receiver_email'] = $this->language->get('text_receiver_email');
$data['text_receiver_id'] = $this->language->get('text_receiver_id');
$data['text_buyer_email'] = $this->language->get('text_buyer_email');
$data['text_payer_id'] = $this->language->get('text_payer_id');
$data['text_payer_status'] = $this->language->get('text_payer_status');
$data['text_country_code'] = $this->language->get('text_country_code');
$data['text_payer_business'] = $this->language->get('text_payer_business');
$data['text_payer_salute'] = $this->language->get('text_payer_salute');
$data['text_payer_firstname'] = $this->language->get('text_payer_firstname');
$data['text_payer_middlename'] = $this->language->get('text_payer_middlename');
$data['text_payer_lastname'] = $this->language->get('text_payer_lastname');
$data['text_payer_suffix'] = $this->language->get('text_payer_suffix');
$data['text_address_owner'] = $this->language->get('text_address_owner');
$data['text_address_status'] = $this->language->get('text_address_status');
$data['text_ship_sec_name'] = $this->language->get('text_ship_sec_name');
$data['text_ship_name'] = $this->language->get('text_ship_name');
$data['text_ship_street1'] = $this->language->get('text_ship_street1');
$data['text_ship_street2'] = $this->language->get('text_ship_street2');
$data['text_ship_city'] = $this->language->get('text_ship_city');
$data['text_ship_state'] = $this->language->get('text_ship_state');
$data['text_ship_zip'] = $this->language->get('text_ship_zip');
$data['text_ship_country'] = $this->language->get('text_ship_country');
$data['text_ship_phone'] = $this->language->get('text_ship_phone');
$data['text_ship_sec_add1'] = $this->language->get('text_ship_sec_add1');
$data['text_ship_sec_add2'] = $this->language->get('text_ship_sec_add2');
$data['text_ship_sec_city'] = $this->language->get('text_ship_sec_city');
$data['text_ship_sec_state'] = $this->language->get('text_ship_sec_state');
$data['text_ship_sec_zip'] = $this->language->get('text_ship_sec_zip');
$data['text_ship_sec_country'] = $this->language->get('text_ship_sec_country');
$data['text_ship_sec_phone'] = $this->language->get('text_ship_sec_phone');
$data['text_trans_id'] = $this->language->get('text_trans_id');
$data['text_receipt_id'] = $this->language->get('text_receipt_id');
$data['text_parent_trans_id'] = $this->language->get('text_parent_trans_id');
$data['text_trans_type'] = $this->language->get('text_trans_type');
$data['text_payment_type'] = $this->language->get('text_payment_type');
$data['text_order_time'] = $this->language->get('text_order_time');
$data['text_fee_amount'] = $this->language->get('text_fee_amount');
$data['text_settle_amount'] = $this->language->get('text_settle_amount');
$data['text_tax_amount'] = $this->language->get('text_tax_amount');
$data['text_exchange'] = $this->language->get('text_exchange');
$data['text_payment_status'] = $this->language->get('text_payment_status');
$data['text_pending_reason'] = $this->language->get('text_pending_reason');
$data['text_reason_code'] = $this->language->get('text_reason_code');
$data['text_protect_elig'] = $this->language->get('text_protect_elig');
$data['text_protect_elig_type'] = $this->language->get('text_protect_elig_type');
$data['text_store_id'] = $this->language->get('text_store_id');
$data['text_terminal_id'] = $this->language->get('text_terminal_id');
$data['text_invoice_number'] = $this->language->get('text_invoice_number');
$data['text_custom'] = $this->language->get('text_custom');
$data['text_note'] = $this->language->get('text_note');
$data['text_sales_tax'] = $this->language->get('text_sales_tax');
$data['text_buyer_id'] = $this->language->get('text_buyer_id');
$data['text_close_date'] = $this->language->get('text_close_date');
$data['text_multi_item'] = $this->language->get('text_multi_item');
$data['text_sub_amt'] = $this->language->get('text_sub_amt');
$data['text_sub_period'] = $this->language->get('text_sub_period');
$data['button_cancel'] = $this->language->get('button_cancel');
$data['breadcrumbs'] = array();
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_home'),
'href' => $this->url->link('common/dashboard', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('text_pp_express'),
'href' => $this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true),
);
$data['breadcrumbs'][] = array(
'text' => $this->language->get('heading_title'),
'href' => $this->url->link('extension/payment/pp_express/info', 'token=' . $this->session->data['token'] . '&transaction_id=' . $this->request->get['transaction_id'], true),
);
$this->load->model('extension/payment/pp_express');
$data['transaction'] = $this->model_extension_payment_pp_express->getTransaction($this->request->get['transaction_id']);
$data['lines'] = $this->formatRows($data['transaction']);
$data['view_link'] = $this->url->link('extension/payment/pp_express/info', 'token=' . $this->session->data['token'], true);
$data['cancel'] = $this->url->link('extension/payment/pp_express/search', 'token=' . $this->session->data['token'], true);
$data['token'] = $this->session->data['token'];
$data['header'] = $this->load->controller('common/header');
$data['column_left'] = $this->load->controller('common/column_left');
$data['footer'] = $this->load->controller('common/footer');
$this->response->setOutput($this->load->view('extension/payment/pp_express_view', $data));
}
public function doSearch() {
/**
* used to search for transactions from a user account
*/
if (isset($this->request->post['date_start'])) {
$this->load->model('extension/payment/pp_express');
$call_data = array();
$call_data['METHOD'] = 'TransactionSearch';
$call_data['STARTDATE'] = gmdate($this->request->post['date_start'] . "\TH:i:s\Z");
if (!empty($this->request->post['date_end'])) {
$call_data['ENDDATE'] = gmdate($this->request->post['date_end'] . "\TH:i:s\Z");
}
if (!empty($this->request->post['transaction_class'])) {
$call_data['TRANSACTIONCLASS'] = $this->request->post['transaction_class'];
}
if (!empty($this->request->post['status'])) {
$call_data['STATUS'] = $this->request->post['status'];
}
if (!empty($this->request->post['buyer_email'])) {
$call_data['EMAIL'] = $this->request->post['buyer_email'];
}
if (!empty($this->request->post['merchant_email'])) {
$call_data['RECEIVER'] = $this->request->post['merchant_email'];
}
if (!empty($this->request->post['receipt_id'])) {
$call_data['RECEIPTID'] = $this->request->post['receipt_id'];
}
if (!empty($this->request->post['transaction_id'])) {
$call_data['TRANSACTIONID'] = $this->request->post['transaction_id'];
}
if (!empty($this->request->post['invoice_number'])) {
$call_data['INVNUM'] = $this->request->post['invoice_number'];
}
if (!empty($this->request->post['auction_item_number'])) {
$call_data['AUCTIONITEMNUMBER'] = $this->request->post['auction_item_number'];
}
if (!empty($this->request->post['amount'])) {
$call_data['AMT'] = number_format($this->request->post['amount'], 2);
$call_data['CURRENCYCODE'] = $this->request->post['currency_code'];
}
if (!empty($this->request->post['recurring_id'])) {
$call_data['PROFILEID'] = $this->request->post['recurring_id'];
}
if (!empty($this->request->post['name_salutation'])) {
$call_data['SALUTATION'] = $this->request->post['name_salutation'];
}
if (!empty($this->request->post['name_first'])) {
$call_data['FIRSTNAME'] = $this->request->post['name_first'];
}
if (!empty($this->request->post['name_middle'])) {
$call_data['MIDDLENAME'] = $this->request->post['name_middle'];
}
if (!empty($this->request->post['name_last'])) {
$call_data['LASTNAME'] = $this->request->post['name_last'];
}
if (!empty($this->request->post['name_suffix'])) {
$call_data['SUFFIX'] = $this->request->post['name_suffix'];
}
$result = $this->model_extension_payment_pp_express->call($call_data);
if ($result['ACK'] != 'Failure' && $result['ACK'] != 'FailureWithWarning' && $result['ACK'] != 'Warning') {
$response['error'] = false;
$response['result'] = $this->formatRows($result);
} else {
$response['error'] = true;
$response['error_msg'] = $result['L_LONGMESSAGE0'];
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($response));
} else {
$response['error'] = true;
$response['error_msg'] = 'Enter a start date';
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($response));
}
}
public function live() {
if (isset($this->request->get['merchantId'])) {
$this->load->language('extension/payment/pp_express');
$this->load->model('extension/payment/pp_express');
$this->load->model('setting/setting');
$token = $this->model_extension_payment_pp_express->getTokens('live');
if (isset($token->access_token)) {
$user_info = $this->model_extension_payment_pp_express->getUserInfo($this->request->get['merchantId'], 'live', $token->access_token);
} else {
$this->session->data['error_api'] = $this->language->get('error_api');
}
if (isset($user_info->api_user_name)) {
$this->model_setting_setting->editSettingValue('pp_express', 'pp_express_username', $user_info->api_user_name);
$this->model_setting_setting->editSettingValue('pp_express', 'pp_express_password', $user_info->api_password);
$this->model_setting_setting->editSettingValue('pp_express', 'pp_express_signature', $user_info->signature);
} else {
$this->session->data['error_api'] = $this->language->get('error_api');
}
}
$this->response->redirect($this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true));
}
public function sandbox() {
if (isset($this->request->get['merchantId'])) {
$this->load->language('extension/payment/pp_express');
$this->load->model('extension/payment/pp_express');
$this->load->model('setting/setting');
$token = $this->model_extension_payment_pp_express->getTokens('sandbox');
if (isset($token->access_token)) {
$user_info = $this->model_extension_payment_pp_express->getUserInfo($this->request->get['merchantId'], 'sandbox', $token->access_token);
} else {
$this->session->data['error_api'] = $this->language->get('error_api_sandbox');
}
if (isset($user_info->api_user_name)) {
$this->model_setting_setting->editSettingValue('pp_express', 'pp_express_sandbox_username', $user_info->api_user_name);
$this->model_setting_setting->editSettingValue('pp_express', 'pp_express_sandbox_password', $user_info->api_password);
$this->model_setting_setting->editSettingValue('pp_express', 'pp_express_sandbox_signature', $user_info->signature);
} else {
$this->session->data['error_api'] = $this->language->get('error_api_sandbox');
}
}
$this->response->redirect($this->url->link('extension/payment/pp_express', 'token=' . $this->session->data['token'], true));
}
private function formatRows($data) {
$return = array();
foreach ($data as $k => $v) {
$elements = preg_split("/(\d+)/", $k, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
if (isset($elements[1]) && isset($elements[0])) {
if ($elements[0] == 'L_TIMESTAMP') {
$v = str_replace('T', ' ', $v);
$v = str_replace('Z', '', $v);
}
$return[$elements[1]][$elements[0]] = $v;
}
}
return $return;
}
public function recurringButtons() {
$this->load->model('sale/recurring');
$recurring = $this->model_sale_recurring->getRecurring($this->request->get['order_recurring_id']);
$data['buttons'] = array();
if ($recurring['status'] == 2 || $recurring['status'] == 3) {
$data['buttons'][] = array(
'text' => $this->language->get('button_cancel_recurring'),
'link' => $this->url->link('extension/payment/pp_express/recurringCancel', 'order_recurring_id=' . $this->request->get['order_recurring_id'] . '&token=' . $this->request->get['token'], true)
);
}
return $this->load->view('sale/recurring_button', $data);
}
}
| gpl-3.0 |
royboy789/Stripe-for-WordPress | inc/stripe-api/stripe-lib/lib/BankAccount.php | 73 | <?php
namespace Stripe;
class BankAccount extends ExternalAccount
{
}
| gpl-3.0 |
SerCeMan/intellij-community | jps/standalone-builder/src/org/jetbrains/jps/gant/Log4jFileLoggerFactory.java | 3361 | /*
* Copyright 2000-2014 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jps.gant;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.apache.log4j.RollingFileAppender;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* @author nik
*/
public class Log4jFileLoggerFactory implements com.intellij.openapi.diagnostic.Logger.Factory {
private final RollingFileAppender myAppender;
private final List<String> myCategoriesWithDebugLevel;
public Log4jFileLoggerFactory(File logFile, String categoriesWithDebugLevel) throws IOException {
myCategoriesWithDebugLevel = categoriesWithDebugLevel.isEmpty() ? Collections.<String>emptyList() : Arrays.asList(categoriesWithDebugLevel.split(","));
PatternLayout pattern = new PatternLayout("%d [%7r] %6p - %30.30c - %m\n");
myAppender = new RollingFileAppender(pattern, logFile.getAbsolutePath());
myAppender.setMaxFileSize("20MB");
myAppender.setMaxBackupIndex(10);
}
@Override
public com.intellij.openapi.diagnostic.Logger getLoggerInstance(String category) {
final Logger logger = Logger.getLogger(category);
logger.addAppender(myAppender);
logger.setLevel(isDebugLevel(category) ? Level.DEBUG : Level.INFO);
return new com.intellij.openapi.diagnostic.Logger() {
@Override
public boolean isDebugEnabled() {
return logger.isDebugEnabled();
}
@Override
public void debug(@NonNls String message) {
logger.debug(message);
}
@Override
public void debug(@Nullable Throwable t) {
logger.debug(t);
}
@Override
public void debug(@NonNls String message, @Nullable Throwable t) {
logger.debug(message, t);
}
@Override
public void info(@NonNls String message) {
logger.info(message);
}
@Override
public void info(@NonNls String message, @Nullable Throwable t) {
logger.info(message, t);
}
@Override
public void warn(@NonNls String message, @Nullable Throwable t) {
logger.warn(message, t);
}
@Override
public void error(@NonNls String message, @Nullable Throwable t, @NonNls @NotNull String... details) {
logger.error(message, t);
}
@Override
public void setLevel(Level level) {
logger.setLevel(level);
}
};
}
private boolean isDebugLevel(String category) {
for (String debug : myCategoriesWithDebugLevel) {
if (category.startsWith(debug)) {
return true;
}
}
return false;
}
}
| apache-2.0 |
skapi1992/jmonkeyengine | jme3-examples/src/main/java/jme3test/post/TestFBOPassthrough.java | 3957 | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package jme3test.post;
import com.jme3.app.SimpleApplication;
import com.jme3.material.Material;
import com.jme3.renderer.RenderManager;
import com.jme3.renderer.Renderer;
import com.jme3.scene.Geometry;
import com.jme3.scene.Node;
import com.jme3.scene.shape.Sphere;
import com.jme3.texture.FrameBuffer;
import com.jme3.texture.Image.Format;
import com.jme3.texture.Texture2D;
import com.jme3.ui.Picture;
/**
* Demonstrates FrameBuffer usage.
* The scene is first rendered to an FB with a texture attached,
* the texture is then rendered onto the screen in ortho mode.
*
* @author Kirill
*/
public class TestFBOPassthrough extends SimpleApplication {
private Node fbNode = new Node("Framebuffer Node");
private FrameBuffer fb;
public static void main(String[] args){
TestFBOPassthrough app = new TestFBOPassthrough();
app.start();
}
@Override
public void simpleInitApp() {
int w = settings.getWidth();
int h = settings.getHeight();
//setup framebuffer
fb = new FrameBuffer(w, h, 1);
Texture2D fbTex = new Texture2D(w, h, Format.RGBA8);
fb.setDepthBuffer(Format.Depth);
fb.setColorTexture(fbTex);
// setup framebuffer's scene
Sphere sphMesh = new Sphere(20, 20, 1);
Material solidColor = assetManager.loadMaterial("Common/Materials/RedColor.j3m");
Geometry sphere = new Geometry("sphere", sphMesh);
sphere.setMaterial(solidColor);
fbNode.attachChild(sphere);
//setup main scene
Picture p = new Picture("Picture");
p.setPosition(0, 0);
p.setWidth(w);
p.setHeight(h);
p.setTexture(assetManager, fbTex, false);
rootNode.attachChild(p);
}
@Override
public void simpleUpdate(float tpf){
fbNode.updateLogicalState(tpf);
fbNode.updateGeometricState();
}
@Override
public void simpleRender(RenderManager rm){
Renderer r = rm.getRenderer();
//do FBO rendering
r.setFrameBuffer(fb);
rm.setCamera(cam, false); // FBO uses current camera
r.clearBuffers(true, true, true);
rm.renderScene(fbNode, viewPort);
rm.flushQueue(viewPort);
//go back to default rendering and let
//SimpleApplication render the default scene
r.setFrameBuffer(null);
}
}
| bsd-3-clause |
lateminer/bitcoin | src/crypto/siphash.cpp | 3595 | // Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <crypto/siphash.h>
#define ROTL(x, b) (uint64_t)(((x) << (b)) | ((x) >> (64 - (b))))
#define SIPROUND do { \
v0 += v1; v1 = ROTL(v1, 13); v1 ^= v0; \
v0 = ROTL(v0, 32); \
v2 += v3; v3 = ROTL(v3, 16); v3 ^= v2; \
v0 += v3; v3 = ROTL(v3, 21); v3 ^= v0; \
v2 += v1; v1 = ROTL(v1, 17); v1 ^= v2; \
v2 = ROTL(v2, 32); \
} while (0)
CSipHasher::CSipHasher(uint64_t k0, uint64_t k1)
{
v[0] = 0x736f6d6570736575ULL ^ k0;
v[1] = 0x646f72616e646f6dULL ^ k1;
v[2] = 0x6c7967656e657261ULL ^ k0;
v[3] = 0x7465646279746573ULL ^ k1;
count = 0;
tmp = 0;
}
CSipHasher& CSipHasher::Write(uint64_t data)
{
uint64_t v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
assert(count % 8 == 0);
v3 ^= data;
SIPROUND;
SIPROUND;
v0 ^= data;
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
count += 8;
return *this;
}
CSipHasher& CSipHasher::Write(const unsigned char* data, size_t size)
{
uint64_t v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
uint64_t t = tmp;
uint8_t c = count;
while (size--) {
t |= ((uint64_t)(*(data++))) << (8 * (c % 8));
c++;
if ((c & 7) == 0) {
v3 ^= t;
SIPROUND;
SIPROUND;
v0 ^= t;
t = 0;
}
}
v[0] = v0;
v[1] = v1;
v[2] = v2;
v[3] = v3;
count = c;
tmp = t;
return *this;
}
uint64_t CSipHasher::Finalize() const
{
uint64_t v0 = v[0], v1 = v[1], v2 = v[2], v3 = v[3];
uint64_t t = tmp | (((uint64_t)count) << 56);
v3 ^= t;
SIPROUND;
SIPROUND;
v0 ^= t;
v2 ^= 0xFF;
SIPROUND;
SIPROUND;
SIPROUND;
SIPROUND;
return v0 ^ v1 ^ v2 ^ v3;
}
uint64_t SipHashUint256(uint64_t k0, uint64_t k1, const uint256& val)
{
/* Specialized implementation for efficiency */
uint64_t d = val.GetUint64(0);
uint64_t v0 = 0x736f6d6570736575ULL ^ k0;
uint64_t v1 = 0x646f72616e646f6dULL ^ k1;
uint64_t v2 = 0x6c7967656e657261ULL ^ k0;
uint64_t v3 = 0x7465646279746573ULL ^ k1 ^ d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(1);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(2);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(3);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
v3 ^= ((uint64_t)4) << 59;
SIPROUND;
SIPROUND;
v0 ^= ((uint64_t)4) << 59;
v2 ^= 0xFF;
SIPROUND;
SIPROUND;
SIPROUND;
SIPROUND;
return v0 ^ v1 ^ v2 ^ v3;
}
uint64_t SipHashUint256Extra(uint64_t k0, uint64_t k1, const uint256& val, uint32_t extra)
{
/* Specialized implementation for efficiency */
uint64_t d = val.GetUint64(0);
uint64_t v0 = 0x736f6d6570736575ULL ^ k0;
uint64_t v1 = 0x646f72616e646f6dULL ^ k1;
uint64_t v2 = 0x6c7967656e657261ULL ^ k0;
uint64_t v3 = 0x7465646279746573ULL ^ k1 ^ d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(1);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(2);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = val.GetUint64(3);
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
d = (((uint64_t)36) << 56) | extra;
v3 ^= d;
SIPROUND;
SIPROUND;
v0 ^= d;
v2 ^= 0xFF;
SIPROUND;
SIPROUND;
SIPROUND;
SIPROUND;
return v0 ^ v1 ^ v2 ^ v3;
}
| mit |
Tatermen/librenms | includes/polling/mempools/alteonos.inc.php | 941 | <?php
/*
* LibreNMS
*
* Copyright (c) 2017 Simone Fini <[email protected]>
* 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. Please see LICENSE.txt at the top level of
* the source code distribution for details.
*/
// AlteonOs Memory
// mpMemStatsTotal 1.3.6.1.4.1.1872.2.5.1.2.8.1.0
// mpMemStatsFree 1.3.6.1.4.1.1872.2.5.1.2.8.3.0
$total = snmp_get($device, ".1.3.6.1.4.1.1872.2.5.1.2.8.1.0", '-OvQ');
$free = snmp_get($device, ".1.3.6.1.4.1.1872.2.5.1.2.8.3.0", '-OvQ');
$perc = ($total / $free) * 100;
$used = ($total - $free);
if (is_numeric($used) && is_numeric($free) && is_numeric($perc)) {
$mempool['total'] = $total;
$mempool['free'] = $free;
$mempool['used'] = $used;
$mempool['perc'] = $perc;
}
| gpl-3.0 |
alexandrul-ci/robotframework | atest/testdata/test_libraries/JavaLibUsingTimestamps.java | 628 | import java.util.GregorianCalendar;
public class JavaLibUsingTimestamps {
public void javaTimestamp() throws InterruptedException {
long timestamp = 1308419034931L;
GregorianCalendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(timestamp);
timestamp += 10800000 - calendar.getTimeZone().getOffset(calendar.getTimeInMillis());
System.out.println("*INFO:" + timestamp +"* Known timestamp");
System.out.println("*HTML:" +
System.currentTimeMillis() +
"*<b>Current</b>");
Thread.sleep(100);
}
}
| apache-2.0 |
pwoodworth/intellij-community | plugins/javaFX/src/org/jetbrains/plugins/javaFX/FxmlDataExternalizer.java | 1604 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.javaFX;
import com.intellij.util.io.DataExternalizer;
import com.intellij.util.io.DataInputOutputUtil;
import com.intellij.util.io.IOUtil;
import org.jetbrains.annotations.NotNull;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
/**
* User: anna
* Date: 3/14/13
*/
public class FxmlDataExternalizer implements DataExternalizer<Set<String>> {
@Override
public void save(@NotNull DataOutput out, Set<String> value) throws IOException {
DataInputOutputUtil.writeINT(out, value.size());
for (String s : value) {
IOUtil.writeUTF(out, s);
}
}
@Override
public Set<String> read(@NotNull DataInput in) throws IOException {
final int size = DataInputOutputUtil.readINT(in);
final Set<String> result = new HashSet<String>(size);
for (int i = 0; i < size; i++) {
final String s = IOUtil.readUTF(in);
result.add(s);
}
return result;
}
}
| apache-2.0 |
ashwinr/DefinitelyTyped | types/bintrees/bintrees-tests.ts | 1210 | /// <reference types="mocha" />
/// <reference types="node" />
import assert = require('assert');
import { BinTree, RBTree } from 'bintrees';
describe('bintrees', () => {
it('builds a simple tree', () => {
let treeA = new RBTree((a: number, b: number) => a - b);
treeA.insert(5);
treeA.insert(3);
treeA.remove(3);
assert.equal(treeA.size, 1);
});
it('builds a tree of strings', () => {
let treeB = new BinTree((a:string, b:string) => a.length - b.length);
treeB.insert('hi');
treeB.insert('there');
treeB.insert('how');
treeB.insert('are'); // ignored
treeB.remove('how');
assert.equal(treeB.size, 2);
assert.equal(treeB.min(), 'hi');
});
it('maintains a tree of objects', () => {
interface C {
id: number
}
let treeC = new BinTree<C>((a: C, b: C) => a.id - b.id);
treeC.insert({ id: 100 });
treeC.insert({ id: 110 });
treeC.insert({ id: 105 });
let ids: number[] = [];
treeC.each((val: C) => {
ids.push(val.id);
});
assert.deepEqual(ids, [100, 105, 110]);
});
});
| mit |
XieXianbin/openjdk | jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/CastCall.java | 3535 | /*
* reserved comment block
* DO NOT REMOVE OR ALTER!
*/
/*
* Copyright 2001-2004 The Apache Software Foundation.
*
* 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.
*/
/*
* $Id: CastCall.java,v 1.2.4.1 2005/09/01 11:47:58 pvedula Exp $
*/
package com.sun.org.apache.xalan.internal.xsltc.compiler;
import java.util.Vector;
import com.sun.org.apache.bcel.internal.generic.ConstantPoolGen;
import com.sun.org.apache.bcel.internal.generic.CHECKCAST;
import com.sun.org.apache.bcel.internal.generic.InstructionList;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ClassGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.MethodGenerator;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.Type;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ObjectType;
import com.sun.org.apache.xalan.internal.xsltc.compiler.util.TypeCheckError;
/**
* @author Santiago Pericas-Geertsen
*/
final class CastCall extends FunctionCall {
/**
* Name of the class that is the target of the cast. Must be a
* fully-qualified Java class Name.
*/
private String _className;
/**
* A reference to the expression being casted.
*/
private Expression _right;
/**
* Constructor.
*/
public CastCall(QName fname, Vector arguments) {
super(fname, arguments);
}
/**
* Type check the two parameters for this function
*/
public Type typeCheck(SymbolTable stable) throws TypeCheckError {
// Check that the function was passed exactly two arguments
if (argumentCount() != 2) {
throw new TypeCheckError(new ErrorMsg(ErrorMsg.ILLEGAL_ARG_ERR,
getName(), this));
}
// The first argument must be a literal String
Expression exp = argument(0);
if (exp instanceof LiteralExpr) {
_className = ((LiteralExpr) exp).getValue();
_type = Type.newObjectType(_className);
}
else {
throw new TypeCheckError(new ErrorMsg(ErrorMsg.NEED_LITERAL_ERR,
getName(), this));
}
// Second argument must be of type reference or object
_right = argument(1);
Type tright = _right.typeCheck(stable);
if (tright != Type.Reference &&
tright instanceof ObjectType == false)
{
throw new TypeCheckError(new ErrorMsg(ErrorMsg.DATA_CONVERSION_ERR,
tright, _type, this));
}
return _type;
}
public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
final ConstantPoolGen cpg = classGen.getConstantPool();
final InstructionList il = methodGen.getInstructionList();
_right.translate(classGen, methodGen);
il.append(new CHECKCAST(cpg.addClass(_className)));
}
}
| gpl-2.0 |
ssilvert/keycloak | core/src/main/java/org/keycloak/representations/idm/authorization/ClientPolicyRepresentation.java | 1411 | /*
* Copyright 2016 Red Hat, Inc. and/or its affiliates
* and other contributors as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.keycloak.representations.idm.authorization;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/**
* @author <a href="mailto:[email protected]">Pedro Igor</a>
*/
public class ClientPolicyRepresentation extends AbstractPolicyRepresentation {
private Set<String> clients;
@Override
public String getType() {
return "client";
}
public Set<String> getClients() {
return clients;
}
public void setClients(Set<String> clients) {
this.clients = clients;
}
public void addClient(String... id) {
if (this.clients == null) {
this.clients = new HashSet<>();
}
this.clients.addAll(Arrays.asList(id));
}
}
| apache-2.0 |
ocsbrandon/kubernetes | pkg/volume/iscsi/iscsi_util.go | 5602 | /*
Copyright 2015 The Kubernetes Authors All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package iscsi
import (
"errors"
"os"
"path"
"strings"
"time"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util/mount"
"github.com/GoogleCloudPlatform/kubernetes/pkg/volume"
"github.com/golang/glog"
)
// stat a path, if not exists, retry maxRetries times
func waitForPathToExist(devicePath string, maxRetries int) bool {
for i := 0; i < maxRetries; i++ {
_, err := os.Stat(devicePath)
if err == nil {
return true
}
if err != nil && !os.IsNotExist(err) {
return false
}
time.Sleep(time.Second)
}
return false
}
// getDevicePrefixRefCount: given a prefix of device path, find its reference count from /proc/mounts
// returns the reference count to the device and error code
// for services like iscsi construct multiple device paths with the same prefix pattern.
// this function aggregates all references to a service based on the prefix pattern
// More specifically, this prefix semantics is to aggregate disk paths that belong to the same iSCSI target/iqn pair.
// an iSCSI target could expose multiple LUNs through the same IQN, and Linux iSCSI initiator creates disk paths that start the same prefix but end with different LUN number
// When we decide whether it is time to logout a target, we have to see if none of the LUNs are used any more.
// That's where the prefix based ref count kicks in. If we only count the disks using exact match, we could log other disks out.
func getDevicePrefixRefCount(mounter mount.Interface, deviceNamePrefix string) (int, error) {
mps, err := mounter.List()
if err != nil {
return -1, err
}
// Find the number of references to the device.
refCount := 0
for i := range mps {
if strings.HasPrefix(mps[i].Device, deviceNamePrefix) {
refCount++
}
}
return refCount, nil
}
// make a directory like /var/lib/kubelet/plugins/kubernetes.io/pod/iscsi/portal-iqn-some_iqn-lun-0
func makePDNameInternal(host volume.VolumeHost, portal string, iqn string, lun string) string {
return path.Join(host.GetPluginDir(ISCSIPluginName), "iscsi", portal+"-iqn-"+iqn+"-lun-"+lun)
}
type ISCSIUtil struct{}
func (util *ISCSIUtil) MakeGlobalPDName(iscsi iscsiDisk) string {
return makePDNameInternal(iscsi.plugin.host, iscsi.portal, iscsi.iqn, iscsi.lun)
}
func (util *ISCSIUtil) AttachDisk(iscsi iscsiDisk) error {
devicePath := strings.Join([]string{"/dev/disk/by-path/ip", iscsi.portal, "iscsi", iscsi.iqn, "lun", iscsi.lun}, "-")
exist := waitForPathToExist(devicePath, 1)
if exist == false {
// discover iscsi target
out, err := iscsi.plugin.execCommand("iscsiadm", []string{"-m", "discovery", "-t", "sendtargets", "-p", iscsi.portal})
if err != nil {
glog.Errorf("iscsi: failed to sendtargets to portal %s error: %s", iscsi.portal, string(out))
return err
}
// login to iscsi target
out, err = iscsi.plugin.execCommand("iscsiadm", []string{"-m", "node", "-p", iscsi.portal, "-T", iscsi.iqn, "--login"})
if err != nil {
glog.Errorf("iscsi: failed to attach disk:Error: %s (%v)", string(out), err)
return err
}
exist = waitForPathToExist(devicePath, 10)
if !exist {
return errors.New("Could not attach disk: Timeout after 10s")
}
}
// mount it
globalPDPath := iscsi.manager.MakeGlobalPDName(iscsi)
mountpoint, err := iscsi.mounter.IsMountPoint(globalPDPath)
if mountpoint {
glog.Infof("iscsi: %s already mounted", globalPDPath)
return nil
}
if err := os.MkdirAll(globalPDPath, 0750); err != nil {
glog.Errorf("iscsi: failed to mkdir %s, error", globalPDPath)
return err
}
err = iscsi.mounter.Mount(devicePath, globalPDPath, iscsi.fsType, nil)
if err != nil {
glog.Errorf("iscsi: failed to mount iscsi volume %s [%s] to %s, error %v", devicePath, iscsi.fsType, globalPDPath, err)
}
return err
}
func (util *ISCSIUtil) DetachDisk(iscsi iscsiDisk, mntPath string) error {
device, cnt, err := mount.GetDeviceNameFromMount(iscsi.mounter, mntPath)
if err != nil {
glog.Errorf("iscsi detach disk: failed to get device from mnt: %s\nError: %v", mntPath, err)
return err
}
if err = iscsi.mounter.Unmount(mntPath); err != nil {
glog.Errorf("iscsi detach disk: failed to unmount: %s\nError: %v", mntPath, err)
return err
}
cnt--
// if device is no longer used, see if need to logout the target
if cnt == 0 {
// strip -lun- from device path
ind := strings.LastIndex(device, "-lun-")
prefix := device[:(ind - 1)]
refCount, err := getDevicePrefixRefCount(iscsi.mounter, prefix)
if err == nil && refCount == 0 {
// this portal/iqn are no longer referenced, log out
// extract portal and iqn from device path
ind1 := strings.LastIndex(device, "-iscsi-")
portal := device[(len("/dev/disk/by-path/ip-")):ind1]
iqn := device[ind1+len("-iscsi-") : ind]
glog.Infof("iscsi: log out target %s iqn %s", portal, iqn)
out, err := iscsi.plugin.execCommand("iscsiadm", []string{"-m", "node", "-p", portal, "-T", iqn, "--logout"})
if err != nil {
glog.Errorf("iscsi: failed to detach disk Error: %s", string(out))
}
}
}
return nil
}
| apache-2.0 |
NigelGreenway/phabricator | src/applications/doorkeeper/bridge/DoorkeeperBridgeJIRA.php | 4178 | <?php
final class DoorkeeperBridgeJIRA extends DoorkeeperBridge {
const APPTYPE_JIRA = 'jira';
const OBJTYPE_ISSUE = 'jira:issue';
public function canPullRef(DoorkeeperObjectRef $ref) {
if ($ref->getApplicationType() != self::APPTYPE_JIRA) {
return false;
}
$types = array(
self::OBJTYPE_ISSUE => true,
);
return isset($types[$ref->getObjectType()]);
}
public function pullRefs(array $refs) {
$id_map = mpull($refs, 'getObjectID', 'getObjectKey');
$viewer = $this->getViewer();
$provider = PhabricatorJIRAAuthProvider::getJIRAProvider();
if (!$provider) {
return;
}
$accounts = id(new PhabricatorExternalAccountQuery())
->setViewer($viewer)
->withUserPHIDs(array($viewer->getPHID()))
->withAccountTypes(array($provider->getProviderType()))
->requireCapabilities(
array(
PhabricatorPolicyCapability::CAN_VIEW,
PhabricatorPolicyCapability::CAN_EDIT,
))
->execute();
if (!$accounts) {
return $this->didFailOnMissingLink();
}
// TODO: When we support multiple JIRA instances, we need to disambiguate
// issues (perhaps with additional configuration) or cast a wide net
// (by querying all instances). For now, just query the one instance.
$account = head($accounts);
$futures = array();
foreach ($id_map as $key => $id) {
$futures[$key] = $provider->newJIRAFuture(
$account,
'rest/api/2/issue/'.phutil_escape_uri($id),
'GET');
}
$results = array();
$failed = array();
foreach (new FutureIterator($futures) as $key => $future) {
try {
$results[$key] = $future->resolveJSON();
} catch (Exception $ex) {
if (($ex instanceof HTTPFutureResponseStatus) &&
($ex->getStatusCode() == 404)) {
// This indicates that the object has been deleted (or never existed,
// or isn't visible to the current user) but it's a successful sync of
// an object which isn't visible.
} else {
// This is something else, so consider it a synchronization failure.
phlog($ex);
$failed[$key] = $ex;
}
}
}
foreach ($refs as $ref) {
$ref->setAttribute('name', pht('JIRA %s', $ref->getObjectID()));
$did_fail = idx($failed, $ref->getObjectKey());
if ($did_fail) {
$ref->setSyncFailed(true);
continue;
}
$result = idx($results, $ref->getObjectKey());
if (!$result) {
continue;
}
$fields = idx($result, 'fields', array());
$ref->setIsVisible(true);
$ref->setAttribute(
'fullname',
pht('JIRA %s %s', $result['key'], idx($fields, 'summary')));
$ref->setAttribute('title', idx($fields, 'summary'));
$ref->setAttribute('description', idx($result, 'description'));
$obj = $ref->getExternalObject();
if ($obj->getID()) {
continue;
}
$this->fillObjectFromData($obj, $result);
$unguarded = AphrontWriteGuard::beginScopedUnguardedWrites();
$obj->save();
unset($unguarded);
}
}
public function fillObjectFromData(DoorkeeperExternalObject $obj, $result) {
// Convert the "self" URI, which points at the REST endpoint, into a
// browse URI.
$self = idx($result, 'self');
$object_id = $obj->getObjectID();
$uri = self::getJIRAIssueBrowseURIFromJIRARestURI($self, $object_id);
if ($uri !== null) {
$obj->setObjectURI($uri);
}
}
public static function getJIRAIssueBrowseURIFromJIRARestURI(
$uri,
$object_id) {
$uri = new PhutilURI($uri);
// The JIRA install might not be at the domain root, so we may need to
// keep an initial part of the path, like "/jira/". Find the API specific
// part of the URI, strip it off, then replace it with the web version.
$path = $uri->getPath();
$pos = strrpos($path, 'rest/api/2/issue/');
if ($pos === false) {
return null;
}
$path = substr($path, 0, $pos);
$path = $path.'browse/'.$object_id;
$uri->setPath($path);
return (string)$uri;
}
}
| apache-2.0 |
redmunds/cdnjs | ajax/libs/bootstrap3-wysiwyg/0.3.0-alpha.2/locales/bootstrap-wysihtml5.il-HE.min.js | 819 | (function($){$.fn.wysihtml5.locale["il-HE"]={font_styles:{normal:"רגיל",h1:"כותרת 1",h2:"כותרת 2",h3:"כותרת 3",h4:"כותרת 4",h5:"כותרת 5",h6:"כותרת 6"},emphasis:{bold:"מודגש",italic:"טקסט נטוי",underline:"קו תחתון",small:"קטן"},lists:{unordered:"רשימה עם תבליטים",ordered:"רשימה ממוספרת",outdent:"הקטן כניסה",indent:"הגדל כניסה",indered:"הגדל כניסה"},link:{insert:"הכנס קישור",cancel:"בטל קישור"},image:{insert:"הוסף תמונה",cancel:"בטל"},html:{edit:"עורך HTML"},colours:{black:"שחור",silver:"כסף",gray:"אפור",maroon:"חום",red:"אדום",purple:"סגול",green:"ירוק",olive:"ירוק זית",navy:"כחול צי",blue:"כחול",orange:"כתום"}}})(jQuery); | mit |
FabriceAbbey/jesshotel | vendor/symfony/symfony/src/Symfony/Component/HttpKernel/Tests/Controller/ArgumentResolverTest.php | 8593 | <?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\HttpKernel\Tests\Controller;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\DefaultValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestAttributeValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\RequestValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentResolver\VariadicValueResolver;
use Symfony\Component\HttpKernel\Controller\ArgumentValueResolverInterface;
use Symfony\Component\HttpKernel\ControllerMetadata\ArgumentMetadataFactory;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\ExtendingRequest;
use Symfony\Component\HttpKernel\Tests\Fixtures\Controller\VariadicController;
use Symfony\Component\HttpFoundation\Request;
class ArgumentResolverTest extends \PHPUnit_Framework_TestCase
{
/** @var ArgumentResolver */
private static $resolver;
public static function setUpBeforeClass()
{
$factory = new ArgumentMetadataFactory();
$argumentValueResolvers = array(
new RequestAttributeValueResolver(),
new RequestValueResolver(),
new DefaultValueResolver(),
new VariadicValueResolver(),
);
self::$resolver = new ArgumentResolver($factory, $argumentValueResolvers);
}
public function testDefaultState()
{
$this->assertEquals(self::$resolver, new ArgumentResolver());
$this->assertNotEquals(self::$resolver, new ArgumentResolver(null, array(new RequestAttributeValueResolver())));
}
public function testGetArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFoo');
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller), '->getArguments() returns an array of arguments for the controller method');
}
public function testGetArgumentsReturnsEmptyArrayWhenNoArguments()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithoutArguments');
$this->assertEquals(array(), self::$resolver->getArguments($request, $controller), '->getArguments() returns an empty array if the method takes no arguments');
}
public function testGetArgumentsUsesDefaultValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller), '->getArguments() uses default values if present');
}
public function testGetArgumentsOverrideDefaultValueByRequestAttribute()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'bar');
$controller = array(new self(), 'controllerWithFooAndDefaultBar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller), '->getArguments() overrides default values if provided in the request attributes');
}
public function testGetArgumentsFromClosure()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo) {};
$this->assertEquals(array('foo'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsUsesDefaultValueFromClosure()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = function ($foo, $bar = 'bar') {};
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromInvokableObject()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$controller = new self();
$this->assertEquals(array('foo', null), self::$resolver->getArguments($request, $controller));
// Test default bar overridden by request attribute
$request->attributes->set('bar', 'bar');
$this->assertEquals(array('foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFromFunctionName()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = __NAMESPACE__.'\controller_function';
$this->assertEquals(array('foo', 'foobar'), self::$resolver->getArguments($request, $controller));
}
public function testGetArgumentsFailsOnUnresolvedValue()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('foobar', 'foobar');
$controller = array(new self(), 'controllerWithFooBarFoobar');
try {
self::$resolver->getArguments($request, $controller);
$this->fail('->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
} catch (\Exception $e) {
$this->assertInstanceOf('\RuntimeException', $e, '->getArguments() throws a \RuntimeException exception if it cannot determine the argument value');
}
}
public function testGetArgumentsInjectsRequest()
{
$request = Request::create('/');
$controller = array(new self(), 'controllerWithRequest');
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request');
}
public function testGetArgumentsInjectsExtendingRequest()
{
$request = ExtendingRequest::create('/');
$controller = array(new self(), 'controllerWithExtendingRequest');
$this->assertEquals(array($request), self::$resolver->getArguments($request, $controller), '->getArguments() injects the request when extended');
}
/**
* @requires PHP 5.6
*/
public function testGetVariadicArguments()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', array('foo', 'bar'));
$controller = array(new VariadicController(), 'action');
$this->assertEquals(array('foo', 'foo', 'bar'), self::$resolver->getArguments($request, $controller));
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetVariadicArgumentsWithoutArrayInRequest()
{
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array(new VariadicController(), 'action');
self::$resolver->getArguments($request, $controller);
}
/**
* @requires PHP 5.6
* @expectedException \InvalidArgumentException
*/
public function testGetArgumentWithoutArray()
{
$factory = new ArgumentMetadataFactory();
$valueResolver = $this->getMock(ArgumentValueResolverInterface::class);
$resolver = new ArgumentResolver($factory, array($valueResolver));
$valueResolver->expects($this->any())->method('supports')->willReturn(true);
$valueResolver->expects($this->any())->method('resolve')->willReturn('foo');
$request = Request::create('/');
$request->attributes->set('foo', 'foo');
$request->attributes->set('bar', 'foo');
$controller = array($this, 'controllerWithFooAndDefaultBar');
$resolver->getArguments($request, $controller);
}
public function __invoke($foo, $bar = null)
{
}
public function controllerWithFoo($foo)
{
}
public function controllerWithoutArguments()
{
}
protected function controllerWithFooAndDefaultBar($foo, $bar = null)
{
}
protected function controllerWithFooBarFoobar($foo, $bar, $foobar)
{
}
protected function controllerWithRequest(Request $request)
{
}
protected function controllerWithExtendingRequest(ExtendingRequest $request)
{
}
}
function controller_function($foo, $foobar)
{
}
| mit |
dominics/predis | tests/Predis/Command/ListPopFirstTest.php | 2704 | <?php
/*
* This file is part of the Predis package.
*
* (c) Daniele Alessandri <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Predis\Command;
use \PHPUnit_Framework_TestCase as StandardTestCase;
/**
* @group commands
* @group realm-list
*/
class ListPopFirstTest extends CommandTestCase
{
/**
* {@inheritdoc}
*/
protected function getExpectedCommand()
{
return 'Predis\Command\ListPopFirst';
}
/**
* {@inheritdoc}
*/
protected function getExpectedId()
{
return 'LPOP';
}
/**
* @group disconnected
*/
public function testFilterArguments()
{
$arguments = array('key');
$expected = array('key');
$command = $this->getCommand();
$command->setArguments($arguments);
$this->assertSame($expected, $command->getArguments());
}
/**
* @group disconnected
*/
public function testParseResponse()
{
$this->assertSame('element', $this->getCommand()->parseResponse('element'));
}
/**
* @group disconnected
*/
public function testPrefixKeys()
{
$arguments = array('key');
$expected = array('prefix:key');
$command = $this->getCommandWithArgumentsArray($arguments);
$command->prefixKeys('prefix:');
$this->assertSame($expected, $command->getArguments());
}
/**
* @group disconnected
*/
public function testPrefixKeysIgnoredOnEmptyArguments()
{
$command = $this->getCommand();
$command->prefixKeys('prefix:');
$this->assertSame(array(), $command->getArguments());
}
/**
* @group connected
*/
public function testPopsTheFirstElementFromList()
{
$redis = $this->getClient();
$redis->rpush('letters', 'a', 'b', 'c', 'd');
$this->assertSame('a', $redis->lpop('letters'));
$this->assertSame('b', $redis->lpop('letters'));
$this->assertSame(array('c', 'd'), $redis->lrange('letters', 0, -1));
}
/**
* @group connected
*/
public function testReturnsNullOnEmptyList()
{
$redis = $this->getClient();
$this->assertNull($redis->lpop('letters'));
}
/**
* @group connected
* @expectedException Predis\ServerException
* @expectedExceptionMessage Operation against a key holding the wrong kind of value
*/
public function testThrowsExceptionOnWrongType()
{
$redis = $this->getClient();
$redis->set('foo', 'bar');
$redis->lpop('foo');
}
}
| mit |
Pluto-tv/chromium-crosswalk | components/cronet/android/java/src/org/chromium/net/UploadDataSink.java | 1221 | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.net;
/**
* Interface with callbacks methods for {@link UploadDataProvider}. All methods
* may be called synchronously or asynchronously, on any thread.
*/
public interface UploadDataSink {
/**
* Called by {@link UploadDataProvider} when a read succeeds.
* @param finalChunk For chunked uploads, {@code true} if this is the final
* read. It must be {@code false} for non-chunked uploads.
*/
public void onReadSucceeded(boolean finalChunk);
/**
* Called by {@link UploadDataProvider} when a read fails.
* @param exception Exception passed on to the embedder.
*/
public void onReadError(Exception exception);
/**
* Called by {@link UploadDataProvider} when a rewind succeeds.
*/
public void onRewindSucceeded();
/**
* Called by {@link UploadDataProvider} when a rewind fails, or if rewinding
* uploads is not supported.
* @param exception Exception passed on to the embedder.
*/
public void onRewindError(Exception exception);
}
| bsd-3-clause |
nolsherry/cdnjs | ajax/libs/curl/0.5.2/curl-kitchen-sink/curl.js | 12631 | var v=null;
(function(c,g,l){var o,j;function e(b,i){return T.call(b).indexOf("[object "+i)==0}function n(b){function i(i){if(i in b)return i=b[i].charAt(0)!="."?(!b.path||p(b.path)?b.path:b.path+"/")+b[i]:z(b[i],b.path),D(i)}e(b,"String")&&(b=D(b),b={name:b,path:b,main:o,lib:j});b.path=b.path||"";b.i=i("lib");b.j=i("main");return b}function m(b){var i,a,B,f=[];k=b.baseUrl||"";if(b.debug)K=!0,r.cache=A,r.cfg=b,r.undefine=function(b){delete A[b]};var h=b.paths;for(i in h)a=D(i.replace("!","!/")),B=E[a]={path:D(h[i])},
B.g=(B.path.match(Q)||[]).length,f.push(a);h=b.packages;for(i in h)a=D(h[i].name||i),B=E[a]=n(h[i]),B.g=(B.path.match(Q)||[]).length,f.push(a);R=RegExp("^("+f.sort(function(b,i){return E[b].g<E[i].g}).join("|").replace(/\//g,"\\/")+")(?=\\/|$)");d=b.pluginPath||d}function w(){}function a(b){function i(b,i){return G(b,i||w,h)}function a(b){return H(s(z(b,f)),k)}var f=b.substr(0,b.lastIndexOf("/")),h={baseName:f},d={};h.d={exports:d,module:{id:z(b,f),uri:a(b),exports:d}};K&&(i.curl=r);h.f=h.d.require=
i;i.toUrl=a;return h}function C(){}function q(b){C.prototype=b;b=new C;C.prototype=x;return b}function F(){function b(b,i){k.push([b,i])}function i(b){f(!0,b)}function a(b){f(!1,b)}function f(h,B){b=h?function(b){b&&b(B)}:function(b,i){i&&i(B)};i=a=function(){throw Error("Promise already completed.");};for(var d,e=0;d=k[e++];)(d=d[h?0:1])&&d(B)}var h=this,k=[];this.c=function(i,a){b(i,a);return h};this.b=function(b){h.p=b;i(b)};this.a=function(b){h.v=b;a(b)}}function y(b){F.apply(this);this.name=
b}function p(b){return b.charAt(b.length-1)=="/"}function D(b){return p(b)?b.substr(0,b.length-1):b}function s(b,i){function a(b){h=b.replace(R,function(i){f=E[i]||{};d=!0;return f.j&&i==b?f.j:f.i?f.i:f.path||""})}var f,h,d;i&&a(i+"!/"+b);d||a(b);return h}function H(b,i,a){return(i&&!U.test(b)?(!i||p(i)?i:i+"/")+b:b)+(a&&!V.test(b)?".js":"")}function L(b,i,a){var f=g.createElement("script");f.type="text/javascript";f.onload=f[S]=function(a){a=a||c.event;if(a.type==="load"||W[this.readyState])delete M[b.name],
this.onload=this[S]=this.onerror=v,i(f)};f.onerror=function(){a(Error("Syntax error or http error: "+b.url))};f.charset=b.charset||"utf-8";f.async=!0;f.src=b.url;M[b.name]=f;h.insertBefore(f,h.firstChild)}function P(b){var a,f,h,d,k=b.length;h=b[k-1];d=e(h,"Function");k==2?e(b[0],"Array")?f=b[0]:a=b[0]:k==3&&(a=b[0],f=b[1]);!f&&d&&h.length>0&&(f=["require","exports","module"]);return{name:a,m:f||[],o:d?h:function(){return h}}}function N(b,f){K&&console&&console.log("curl: resolving",b.name);var h=
a(b.baseName||b.name);I(f.m,h,function(a){try{var d=f.o.apply(h.d.exports,a)||h.d.exports;K&&console&&console.log("curl: defined",b.name,d.toString().substr(0,50).replace(/\n/," "))}catch(k){b.a(k)}b.b(d)},b.a)}function u(b){L(b,function(){var a=J;J=x;b.q!==!1&&(a?a.h?b.a(Error(a.h.replace("${url}",b.url))):N(b,a):b.a(Error("define() not found or duplicates found: "+b.url)))},b.a)}function z(b,a){return b.replace(X,function(b,f,h){return(h?a.substr(0,a.lastIndexOf("/")):a)+"/"})}function O(b,f){var h,
e,j,c,n,E;e=b.indexOf("!");if(e>=0){j=b.substr(0,e);c=b.substr(e+1);var g=s(j);g.indexOf("/")<0&&(g=s((!d||p(d)?d:d+"/")+g));var m=A[j];if(!m)m=A[j]=new y(j),m.url=H(g,k,!0),m.baseName=g,u(m);f=a(f.baseName);f.f.toUrl=function(b){b=s(b,j);return H(b,k)};E=q(j?l.plugins&&l.plugins[j]:l)||{};var w=function(b){return z(b,f.baseName)};n=new y(b);m.c(function(a){var d;c=b.substr(e+1);c="normalize"in a?a.normalize(c,w,E):w(c);h=j+"!"+c;d=A[h];if(!d){d=new y(h);c&&!a.dynamic&&(A[h]=d);var k=d.b;k.resolve=
k;k.reject=d.a;a.load(c,f.f,k,E)}d.c(n.b,n.a)},n.a)}else if(c=h=z(b,f.baseName),n=A[c],!n)n=A[c]=new y(c),n.url=H(s(c),k,!0),u(n);return n}function I(b,a,f,h){for(var d=[],k=b.length,e=k,c=!1,j=0;j<e&&!c;j++)(function(b,e){e in a.d?(d[b]=a.d[e],k--):O(e,a).c(function(a){d[b]=a;--k==0&&(c=!0,f(d))},function(b){c=!0;h(b)})})(j,b[j]);k==0&&!c&&f(d)}function G(b,a,f){if(e(b,"String")){f=(f=A[b])&&f.p;if(f===x)throw Error("Module is not already resolved: "+b);return f}I(b,f,function(b){a.b?a.b(b):a.apply(v,
b)},function(b){if(a.a)a.a(b);else throw b;})}function r(){var b=Y.call(arguments),f,h;e(b[0],"Object")&&(l=b.shift(),m(l));f=[].concat(b[0]);b=b[1];h=a("");var d=new F,k={};k.then=function(b,a){d.c(function(a){b&&b.apply(v,a)},function(b){if(a)a(b);else throw b;});return k};k.next=function(b,a){var f=d;d=new F;f.c(function(){h.f(b,d,h)},function(b){d.a(b)});a&&d.c(function(b){a.apply(this,b)});return k};b&&k.then(b);h.f(f,d,h);return k}function f(){var b=P(arguments),f=b.name;if(f==v)if(J!==x)J=
{h:"Multiple anonymous defines found in ${url}."};else{var h;if(!e(c.opera,"Opera"))for(var d in M)if(M[d].readyState=="interactive"){h=d;break}if(!(f=h))J=b}if(f!=v)(h=A[f])||(h=A[f]=new y(f)),h.q=!1,"resolved"in h||N(h,b,a(f))}var h=g.head||g.getElementsByTagName("head")[0],k,d="curl/plugin",E={},A={},J,M={},T={}.toString,x,Y=[].slice,U=/^\/|^[^:]+:\/\//,X=/^(\.)(\.)?(\/|$)/,Q=/\//,V=/\?/,R,W={loaded:1,interactive:1,complete:1},S="onreadystatechange";o="./lib/main";j="./lib";var K;e(l,"Function")||
m(l);(l.apiContext||c)[l.apiName||"curl"]=r;c.define=r.define=f;r.version="0.5.2";f.amd={plugins:!0}})(this,document,this.curl||{});
(function(c,g){function l(){if(!g.body)return!1;s||(s=g.createTextNode(""));try{return g.body.removeChild(g.body.appendChild(s)),s=D,!0}catch(a){return!1}}function o(){var c;c=n[g[e]]&&l();if(!a&&c){a=!0;for(clearTimeout(p);F=y.pop();)F();w&&(g[e]="complete");for(var j;j=m.shift();)j()}return c}function j(){o();a||(p=setTimeout(j,C))}var e="readyState",n={loaded:1,interactive:1,complete:1},m=[],w=typeof g[e]!="string",a=!1,C=10,q,F,y=[],p,D,s;q="addEventListener"in c?function(a,c){a.addEventListener(c,
o,!1);return function(){a.removeEventListener(c,o,!1)}}:function(a,c){a.attachEvent("on"+c,o);return function(){a.detachEvent(c,o)}};g&&!o()&&(y=[q(c,"load"),q(g,"readystatechange"),q(c,"DOMContentLoaded")],p=setTimeout(j,C));define("curl/domReady",function(){function c(e){a?e():m.push(e)}c.then=c;c.amd=!0;return c})})(this,document);
(function(c){define("curl/dojo16Compat",["./domReady"],function(g){function l(c){c.ready||(c.ready=function(c){g(c)});c.nameToUrl||(c.nameToUrl=function(e,n){return c.toUrl(e+(n||""))});return c}var o=c.define;l(c.curl||c.require);c.define=function(){var c,e,n,m=[],g,a;c=[].slice.call(arguments);e=c.length;n=c[e-2];g=typeof c[e-1]=="function"?c[e-1]:v;if(n&&g){for(a=n.length-1;a>=0;a--)n[a]=="require"&&m.push(a);m.length>0&&(c[e-1]=function(){var c=[].slice.call(arguments);for(a=0;a<m.length;a++)c[m[a]]=
l(c[m[a]]);return g.apply(this,c)})}return o.apply(v,c)};return!0})})(this);
(function(c,g){function l(a,e,j){var l=g.createElement("script");l.type=a.k||"text/javascript";l.onload=l.onreadystatechange=function(a){a=a||c.event;if(a.type=="load"||n[this.readyState])this.onload=this.onreadystatechange=this.onerror=v,e(l)};l.onerror=function(){j&&j(Error("Script error or http error: "+a.url))};l.charset=a.charset||"utf-8";l.async=a.async;l.src=a.url;m.insertBefore(l,m.firstChild)}function o(a,c){l(a,function(a){var e=j.shift();w=j.length>0;e&&o.apply(v,e);c.resolve(a)},function(a){c.reject(a)})}
var j=[],e=g.createElement("script").async==!0,n={loaded:1,interactive:1,complete:1},m=g.head||g.getElementsByTagName("head")[0],w;define("js",{load:function(a,c,n,g){var m;m=a.indexOf("!order")>=0;g="prefetch"in g?g.prefetch:!0;a=m?a.substr(0,a.indexOf("!")):a;a={name:a,url:c.toUrl(a),async:!m,u:m};c=n.resolve?n:{resolve:function(a){n(a)},reject:function(a){throw a;}};if(m&&!e&&w){if(j.push([a,c]),g)a.k="text/cache",l(a,function(a){a.parentNode.removeChild(a)}),a.k=""}else w=w||m,o(a,c)}})})(this,
document);
define("text",function(){function c(){if(typeof XMLHttpRequest!=="undefined")c=function(){return new XMLHttpRequest};else for(var e=c=function(){throw Error("getXhr(): XMLHttpRequest not available");};j.length>0&&c===e;)(function(e){try{new ActiveXObject(e),c=function(){return new ActiveXObject(e)}}catch(g){}})(j.shift());return c()}function g(e,g,l){var a=c();a.open("GET",e,!0);a.onreadystatechange=function(){a.readyState===4&&(a.status<400?g(a.responseText):l(Error("fetchText() failed. status: "+a.statusText)))};
a.send(v)}function l(c){console&&(console.error?console.error(c):console.log(c.message))}function o(c){var e={34:'\\"',13:"\\r",12:"\\f",10:"\\n",9:"\\t",8:"\\b"};return c.replace(/(["\n\f\t\r\b])/g,function(c){return e[c.charCodeAt(0)]})}var j=["Msxml2.XMLHTTP","Microsoft.XMLHTTP","Msxml2.XMLHTTP.4.0"],e={};return{load:function(c,e,j){var a=j.b||j,j=j.a||l;g(e.toUrl(c),a,j)},s:function(c,g){return function(l,a,j){var q;q=j.toUrl(a.lastIndexOf(".")<=a.lastIndexOf("/")?a+".html":a);a=j.toAbsMid(a);
a in e||(e[a]=!0,q=o(g(q)),c('define("'+l+"!"+a+'", function () {\n\treturn "'+q+'";\n});\n'))}}}});define("async",function(){return{load:function(c,g,l){function o(c){typeof l.b=="function"?l.b(c):l(c)}function j(c){typeof l.a=="function"&&l.a(c)}g([c],function(c){typeof c.c=="function"?c.c(function(g){arguments.length==0&&(g=c);o(g)},j):o(c)})},analyze:function(c,g,l){l(c)}}});
(function(c){function g(a,c){var k=a.link;k[F]=k[y]=function(){if(!k.readyState||k.readyState=="complete")L["event-link-onload"]=!0,m(a),c()}}function l(a){for(var a=a.split("!"),c,k=1;c=a[k++];)c=c.split("=",2),a[c[0]]=c.length==2?c[1]:!0;return a}function o(a){if(document.createStyleSheet&&(I||(I=document.createStyleSheet()),document.styleSheets.length>=30)){var c,k,d,e=0;d=I;I=v;for(k=document.getElementsByTagName("link");c=k[e];)c.getAttribute("_curl_movable")?(d.addImport(c.href),c.parentNode&&
c.parentNode.removeChild(c)):e++}a=a[p]("link");a.rel="stylesheet";a.type="text/css";a.setAttribute("_curl_movable",!0);return a}function j(a){var c,k,d=!1;try{if(c=a.sheet||a.styleSheet,(d=(k=c.cssRules||c.rules)?k.length>0:k!==s)&&{}.toString.call(window.t)=="[object Chrome]"){c.insertRule("#_cssx_load_test{margin-top:-5px;}",0);if(!G)G=u[p]("div"),G.id="_cssx_load_test",z.appendChild(G);d=u.defaultView.getComputedStyle(G,v).marginTop=="-5px";c.deleteRule(0)}}catch(e){d=e.code==1E3||e.message.match(/security|denied/i)}return d}
function e(a,c){j(a.link)?(m(a),c()):D||setTimeout(function(){e(a,c)},a.r)}function n(a,c){function k(){d||(d=!0,c())}var d;g(a,k);L["event-link-onload"]||e(a,k)}function m(a){a=a.link;a[F]=a[y]=v}function w(a,c){return a.replace(N,function(a,f){var e=f;P.test(e)||(e=c+e);return'url("'+e+'")'})}function a(c){clearTimeout(a.l);a.e?a.e.push(c):(a.e=[c],r=u.createStyleSheet?u.createStyleSheet():z.appendChild(u.createElement("style")));a.l=setTimeout(function(){var c,f;c=r;r=s;f=a.e.join("\n");a.e=s;
f=f.replace(/.+charset[^;]+;/g,"");"cssText"in c?c.cssText=f:c.appendChild(u.createTextNode(f))},0);return r}function C(a){return{cssRules:function(){return a.cssRules||a.rules},insertRule:a.insertRule||function(c,e){var d=c.split(/\{|\}/g);a.addRule(d[0],d[1],e);return e},deleteRule:a.deleteRule||function(c){a.removeRule(c);return c},sheet:function(){return a}}}function q(a){var c={34:'\\"',13:"\\r",12:"\\f",10:"\\n",9:"\\t",8:"\\b"};return a.replace(/(["\n\f\t\r\b])/g,function(a){return c[a.charCodeAt(0)]})}
var F="onreadystatechange",y="onload",p="createElement",D=!1,s,H={},L={},P=/^\/|^[^:]*:\/\//,N=/url\s*\(['"]?([^'"\)]*)['"]?\)/g,u=c.document,z,O={};if(u)z=u.n||(u.n=u.getElementsByTagName("head")[0]);var I,G,r;define("css",{normalize:function(a,c){var e,d;if(!a)return a;e=a.split(",");d=[];for(var g=0,j=e.length;g<j;g++)d.push(c(e[g]));return d.join(",")},load:function(c,e,g,d){function j(){--s==0&&setTimeout(function(){g(C(p.sheet||p.styleSheet))},0)}var m=(c||"").split(","),s=m.length;if(c)for(var q=
m.length-1,r;q>=0;q--,r=!0){var c=m[q],c=l(c),x=c.shift(),x=e.toUrl(x.lastIndexOf(".")<=x.lastIndexOf("/")?x+".css":x),p=o(u),y={link:p,url:x,r:d.cssWatchPeriod||50};("nowait"in c?c.nowait!="false":d.cssDeferLoad)?g(C(p.sheet||p.styleSheet)):n(y,j);p.href=x;r?z.insertBefore(p,H[r].previousSibling):z.appendChild(p);H[x]=p}else g({translateUrls:function(a,c){var d;d=e.toUrl(c);d=d.substr(0,d.lastIndexOf("/")+1);return w(a,d)},injectStyle:function(c){return a(c)},proxySheet:function(a){if(a.sheet)a=
a.sheet;return C(a)}})},build:function(a,c){return function(e,d,g){d=l(d).shift();d=g.toAbsMid(d);d in O||(O[d]=!0,g=g.toUrl(d.lastIndexOf(".")<=d.lastIndexOf("/")?d+".css":d),g=q(c(g)),a('define("'+e+"!"+d+'", ["'+e+'!"], function (api) {\n\tvar cssText = "'+g+'";\n\tcssText = api.translateUrls(cssText, "'+d+'");\n\treturn api.proxySheet(api.injectStyle(cssText));\n});\n'))}}})})(this);define("domReady",["curl/domReady"],function(c){return{load:function(g,l,o){c(o)}}});
| mit |
chrissimpkins/jsdelivr | files/qoopido.nucleus/1.0.8/support/test/capability/touch.js | 390 | /*! /support/test/capability/touch 1.0.8 | http://nucleus.qoopido.com | (c) 2016 Dirk Lueth */
!function(e,n){"use strict";function o(o){var t=o.defer();return"ontouchstart"in e||"DocumentTouch"in e&&document instanceof DocumentTouch||n.maxTouchPoints>0||n.msMaxTouchPoints>0?t.resolve():t.reject(),t.pledge}provide(["/demand/pledge"],o)}(this,navigator);
//# sourceMappingURL=touch.js.map
| mit |
froala/cdnjs | ajax/libs/qoopido.nucleus/1.1.0/support/test/css/transition.js | 304 | /*! /support/test/css/transition 1.1.0 | http://nucleus.qoopido.com | (c) 2016 Dirk Lueth */
!function(){"use strict";function e(e,r){var t=e.defer(),n=r("transition");return n?t.resolve(n):t.reject(),t.pledge}provide(["/demand/pledge","../../css/property"],e)}();
//# sourceMappingURL=transition.js.map
| mit |
marchdoe/derose | core/test/integration/model/model_roles_spec.js | 2658 | /*globals describe, it, before, beforeEach, afterEach */
var testUtils = require('../../utils'),
should = require('should'),
errors = require('../../../server/errorHandling'),
// Stuff we are testing
Models = require('../../../server/models');
describe("Role Model", function () {
var RoleModel = Models.Role;
should.exist(RoleModel);
before(function (done) {
testUtils.clearData().then(function () {
done();
}, done);
});
beforeEach(function (done) {
testUtils.initData().then(function () {
done();
}, done);
});
afterEach(function (done) {
testUtils.clearData().then(function () {
done();
}, done);
});
it("can browse roles", function (done) {
RoleModel.browse().then(function (foundRoles) {
should.exist(foundRoles);
foundRoles.models.length.should.be.above(0);
done();
}).then(null, done);
});
it("can read roles", function (done) {
RoleModel.read({id: 1}).then(function (foundRole) {
should.exist(foundRole);
done();
}).then(null, done);
});
it("can edit roles", function (done) {
RoleModel.read({id: 1}).then(function (foundRole) {
should.exist(foundRole);
return foundRole.set({name: "updated"}).save();
}).then(function () {
return RoleModel.read({id: 1});
}).then(function (updatedRole) {
should.exist(updatedRole);
updatedRole.get("name").should.equal("updated");
done();
}).then(null, done);
});
it("can add roles", function (done) {
var newRole = {
name: "test1",
description: "test1 description"
};
RoleModel.add(newRole).then(function (createdRole) {
should.exist(createdRole);
createdRole.attributes.name.should.equal(newRole.name);
createdRole.attributes.description.should.equal(newRole.description);
done();
}).then(null, done);
});
it("can delete roles", function (done) {
RoleModel.read({id: 1}).then(function (foundRole) {
should.exist(foundRole);
return RoleModel['delete'](1);
}).then(function () {
return RoleModel.browse();
}).then(function (foundRoles) {
var hasRemovedId = foundRoles.any(function (role) {
return role.id === 1;
});
hasRemovedId.should.equal(false);
done();
}).then(null, done);
});
});
| mit |
laincortes/dolphin | Externals/wxWidgets3/src/osx/imaglist.cpp | 7829 | /////////////////////////////////////////////////////////////////////////////
// Name: src/osx/imaglist.cpp
// Purpose:
// Author: Robert Roebling
// Copyright: (c) 1998 Robert Roebling
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_IMAGLIST
#include "wx/imaglist.h"
#ifndef WX_PRECOMP
#include "wx/dc.h"
#include "wx/icon.h"
#include "wx/image.h"
#endif
wxIMPLEMENT_DYNAMIC_CLASS(wxImageList, wxObject);
wxImageList::wxImageList( int width, int height, bool mask, int initialCount )
{
(void)Create(width, height, mask, initialCount);
}
wxImageList::~wxImageList()
{
(void)RemoveAll();
}
int wxImageList::GetImageCount() const
{
return m_images.GetCount();
}
bool wxImageList::Create( int width, int height, bool WXUNUSED(mask), int WXUNUSED(initialCount) )
{
m_width = width;
m_height = height;
return Create();
}
bool wxImageList::Create()
{
return true;
}
int wxImageList::Add( const wxIcon &bitmap )
{
wxASSERT_MSG( (bitmap.GetWidth() == m_width && bitmap.GetHeight() == m_height)
|| (m_width == 0 && m_height == 0),
wxT("invalid bitmap size in wxImageList: this might work ")
wxT("on this platform but definitely won't under Windows.") );
m_images.Append( new wxIcon( bitmap ) );
if (m_width == 0 && m_height == 0)
{
m_width = bitmap.GetWidth();
m_height = bitmap.GetHeight();
}
return m_images.GetCount() - 1;
}
int wxImageList::Add( const wxBitmap &bitmap )
{
wxASSERT_MSG( (bitmap.GetScaledWidth() >= m_width && bitmap.GetScaledHeight() == m_height)
|| (m_width == 0 && m_height == 0),
wxT("invalid bitmap size in wxImageList: this might work ")
wxT("on this platform but definitely won't under Windows.") );
// Mimic behaviour of Windows ImageList_Add that automatically breaks up the added
// bitmap into sub-images of the correct size
if (m_width > 0 && bitmap.GetScaledWidth() > m_width && bitmap.GetScaledHeight() >= m_height)
{
int numImages = bitmap.GetScaledWidth() / m_width;
for (int subIndex = 0; subIndex < numImages; subIndex++)
{
wxRect rect(m_width * subIndex, 0, m_width, m_height);
wxBitmap tmpBmp = bitmap.GetSubBitmap(rect);
m_images.Append( new wxBitmap(tmpBmp) );
}
}
else
{
m_images.Append( new wxBitmap(bitmap) );
}
if (m_width == 0 && m_height == 0)
{
m_width = bitmap.GetScaledWidth();
m_height = bitmap.GetScaledHeight();
}
return m_images.GetCount() - 1;
}
int wxImageList::Add( const wxBitmap& bitmap, const wxBitmap& mask )
{
wxBitmap bmp( bitmap );
if (mask.IsOk())
bmp.SetMask( new wxMask( mask ) );
return Add( bmp );
}
int wxImageList::Add( const wxBitmap& bitmap, const wxColour& maskColour )
{
wxImage img = bitmap.ConvertToImage();
img.SetMaskColour( maskColour.Red(), maskColour.Green(), maskColour.Blue() );
return Add( wxBitmap( img ) );
}
// Get the bitmap
wxBitmap wxImageList::GetBitmap(int index) const
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, wxNullBitmap , wxT("wrong index in image list") );
wxObject* obj = (wxObject*) node->GetData();
if ( obj == NULL )
return wxNullBitmap ;
else if ( obj->IsKindOf(CLASSINFO(wxIcon)) )
return wxBitmap( *(static_cast<wxIcon*>(obj)) ) ;
else
return *(static_cast<wxBitmap*>(obj)) ;
}
// Get the icon
wxIcon wxImageList::GetIcon(int index) const
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, wxNullIcon , wxT("wrong index in image list") );
wxObject* obj = (wxObject*) node->GetData();
if ( obj == NULL )
return wxNullIcon ;
else if ( obj->IsKindOf(CLASSINFO(wxBitmap)) )
{
wxFAIL_MSG( wxT("cannot convert from bitmap to icon") ) ;
return wxNullIcon ;
}
else
return *(static_cast<wxIcon*>(obj)) ;
}
bool wxImageList::Replace( int index, const wxBitmap &bitmap )
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, false, wxT("wrong index in image list") );
wxBitmap* newBitmap = new wxBitmap( bitmap );
if (index == (int) m_images.GetCount() - 1)
{
delete node->GetData();
m_images.Erase( node );
m_images.Append( newBitmap );
}
else
{
wxList::compatibility_iterator next = node->GetNext();
delete node->GetData();
m_images.Erase( node );
m_images.Insert( next, newBitmap );
}
return true;
}
bool wxImageList::Replace( int index, const wxIcon &bitmap )
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, false, wxT("wrong index in image list") );
wxIcon* newBitmap = new wxIcon( bitmap );
if (index == (int) m_images.GetCount() - 1)
{
delete node->GetData();
m_images.Erase( node );
m_images.Append( newBitmap );
}
else
{
wxList::compatibility_iterator next = node->GetNext();
delete node->GetData();
m_images.Erase( node );
m_images.Insert( next, newBitmap );
}
return true;
}
bool wxImageList::Replace( int index, const wxBitmap &bitmap, const wxBitmap &mask )
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, false, wxT("wrong index in image list") );
wxBitmap* newBitmap = new wxBitmap(bitmap);
if (index == (int) m_images.GetCount() - 1)
{
delete node->GetData();
m_images.Erase( node );
m_images.Append( newBitmap );
}
else
{
wxList::compatibility_iterator next = node->GetNext();
delete node->GetData();
m_images.Erase( node );
m_images.Insert( next, newBitmap );
}
if (mask.IsOk())
newBitmap->SetMask(new wxMask(mask));
return true;
}
bool wxImageList::Remove( int index )
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, false, wxT("wrong index in image list") );
delete node->GetData();
m_images.Erase( node );
return true;
}
bool wxImageList::RemoveAll()
{
WX_CLEAR_LIST(wxList, m_images);
m_images.Clear();
return true;
}
bool wxImageList::GetSize( int index, int &width, int &height ) const
{
width = 0;
height = 0;
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, false, wxT("wrong index in image list") );
wxObject *obj = (wxObject*)node->GetData();
if (obj->IsKindOf(CLASSINFO(wxIcon)))
{
wxIcon *bm = static_cast< wxIcon* >(obj ) ;
width = bm->GetWidth();
height = bm->GetHeight();
}
else
{
wxBitmap *bm = static_cast< wxBitmap* >(obj ) ;
width = bm->GetScaledWidth();
height = bm->GetScaledHeight();
}
return true;
}
bool wxImageList::Draw(
int index, wxDC &dc, int x, int y,
int flags, bool WXUNUSED(solidBackground) )
{
wxList::compatibility_iterator node = m_images.Item( index );
wxCHECK_MSG( node, false, wxT("wrong index in image list") );
wxObject *obj = (wxObject*)node->GetData();
if (obj->IsKindOf(CLASSINFO(wxIcon)))
{
wxIcon *bm = static_cast< wxIcon* >(obj ) ;
dc.DrawIcon( *bm , x, y );
}
else
{
wxBitmap *bm = static_cast< wxBitmap* >(obj ) ;
dc.DrawBitmap( *bm, x, y, (flags & wxIMAGELIST_DRAW_TRANSPARENT) > 0 );
}
return true;
}
#endif // wxUSE_IMAGLIST
| gpl-2.0 |
kernow/ansible-modules-core | system/setup.py | 5577 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2012, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible 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.
#
# Ansible 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 Ansible. If not, see <http://www.gnu.org/licenses/>.
DOCUMENTATION = '''
---
module: setup
version_added: historical
short_description: Gathers facts about remote hosts
options:
gather_subset:
version_added: "2.1"
description:
- "if supplied, restrict the additional facts collected to the given subset.
Possible values: all, hardware, network, virtual, ohai, and
facter Can specify a list of values to specify a larger subset.
Values can also be used with an initial C(!) to specify that
that specific subset should not be collected. For instance:
!hardware, !network, !virtual, !ohai, !facter. Note that a few
facts are always collected. Use the filter parameter if you do
not want to display those."
required: false
default: 'all'
gather_timeout:
version_added: "2.2"
description:
- "Set the default timeout in seconds for individual fact gathering"
required: false
default: 10
filter:
version_added: "1.1"
description:
- if supplied, only return facts that match this shell-style (fnmatch) wildcard.
required: false
default: '*'
fact_path:
version_added: "1.3"
description:
- path used for local ansible facts (*.fact) - files in this dir
will be run (if executable) and their results be added to ansible_local facts
if a file is not executable it is read. Check notes for Windows options. (from 2.1 on)
File/results format can be json or ini-format
required: false
default: '/etc/ansible/facts.d'
description:
- This module is automatically called by playbooks to gather useful
variables about remote hosts that can be used in playbooks. It can also be
executed directly by C(/usr/bin/ansible) to check what variables are
available to a host. Ansible provides many I(facts) about the system,
automatically.
notes:
- More ansible facts will be added with successive releases. If I(facter) or
I(ohai) are installed, variables from these programs will also be snapshotted
into the JSON file for usage in templating. These variables are prefixed
with C(facter_) and C(ohai_) so it's easy to tell their source. All variables are
bubbled up to the caller. Using the ansible facts and choosing to not
install I(facter) and I(ohai) means you can avoid Ruby-dependencies on your
remote systems. (See also M(facter) and M(ohai).)
- The filter option filters only the first level subkey below ansible_facts.
- If the target host is Windows, you will not currently have the ability to use
C(filter) as this is provided by a simpler implementation of the module.
- If the target host is Windows you can now use C(fact_path). Make sure that this path
exists on the target host. Files in this path MUST be PowerShell scripts (``*.ps1``) and
their output must be formattable in JSON (Ansible will take care of this). Test the
output of your scripts.
This option was added in Ansible 2.1.
author:
- "Ansible Core Team"
- "Michael DeHaan"
- "David O'Brien @david_obrien davidobrien1985"
'''
EXAMPLES = """
# Display facts from all hosts and store them indexed by I(hostname) at C(/tmp/facts).
ansible all -m setup --tree /tmp/facts
# Display only facts regarding memory found by ansible on all hosts and output them.
ansible all -m setup -a 'filter=ansible_*_mb'
# Display only facts returned by facter.
ansible all -m setup -a 'filter=facter_*'
# Display only facts about certain interfaces.
ansible all -m setup -a 'filter=ansible_eth[0-2]'
# Restrict additional gathered facts to network and virtual.
ansible all -m setup -a 'gather_subset=network,virtual'
# Do not call puppet facter or ohai even if present.
ansible all -m setup -a 'gather_subset=!facter,!ohai'
# Only collect the minimum amount of facts:
ansible all -m setup -a 'gather_subset=!all'
# Display facts from Windows hosts with custom facts stored in C(C:\\custom_facts).
ansible windows -m setup -a "fact_path='c:\\custom_facts'"
"""
def main():
module = AnsibleModule(
argument_spec = dict(
gather_subset=dict(default=["all"], required=False, type='list'),
gather_timeout=dict(default=10, required=False, type='int'),
filter=dict(default="*", required=False),
fact_path=dict(default='/etc/ansible/facts.d', required=False),
),
supports_check_mode = True,
)
data = get_all_facts(module)
module.exit_json(**data)
# import module snippets
from ansible.module_utils.basic import *
from ansible.module_utils.facts import *
if __name__ == '__main__':
main()
| gpl-3.0 |
angelapper/edx-platform | lms/djangoapps/teams/static/teams/js/utils/team_analytics.js | 643 | /**
* Utility methods for emitting teams events. See the event spec:
* https://openedx.atlassian.net/wiki/display/AN/Teams+Feature+Event+Design
*/
(function(define) {
'use strict';
define([
'logger'
], function(Logger) {
var TeamAnalytics = {
emitPageViewed: function(page_name, topic_id, team_id) {
Logger.log('edx.team.page_viewed', {
page_name: page_name,
topic_id: topic_id,
team_id: team_id
});
}
};
return TeamAnalytics;
});
}).call(this, define || RequireJS.define);
| agpl-3.0 |
matsuu/server | vendor/symfony/vendor/phing/tasks/ext/XmlLintTask.php | 3055 | <?php
require_once 'phing/Task.php';
/**
* A XML lint task. Checking syntax of one or more XML files against an XML Schema using the DOM extension.
*
* @author Knut Urdalen <[email protected]>
* @package phing.tasks.ext
*/
class XmlLintTask extends Task {
protected $file; // the source file (from xml attribute)
protected $schema; // the schema file (from xml attribute)
protected $filesets = array(); // all fileset objects assigned to this task
/**
* File to be performed syntax check on
*
* @param PhingFile $file
*/
public function setFile(PhingFile $file) {
$this->file = $file;
}
/**
* XML Schema Description file to validate against
*
* @param PhingFile $schema
*/
public function setSchema(PhingFile $schema) {
$this->schema = $schema;
}
/**
* Nested creator, creates a FileSet for this task
*
* @return FileSet The created fileset object
*/
function createFileSet() {
$num = array_push($this->filesets, new FileSet());
return $this->filesets[$num-1];
}
/**
* Execute lint check against PhingFile or a FileSet
*/
public function main() {
if(!isset($this->schema)) {
throw new BuildException("Missing attribute 'schema'");
}
$schema = $this->schema->getPath();
if(!file_exists($schema)) {
throw new BuildException("File not found: ".$schema);
}
if(!isset($this->file) and count($this->filesets) == 0) {
throw new BuildException("Missing either a nested fileset or attribute 'file' set");
}
set_error_handler(array($this, 'errorHandler'));
if($this->file instanceof PhingFile) {
$this->lint($this->file->getPath());
} else { // process filesets
$project = $this->getProject();
foreach($this->filesets as $fs) {
$ds = $fs->getDirectoryScanner($project);
$files = $ds->getIncludedFiles();
$dir = $fs->getDir($this->project)->getPath();
foreach($files as $file) {
$this->lint($dir.DIRECTORY_SEPARATOR.$file);
}
}
}
restore_error_handler();
}
/**
* Performs validation
*
* @param string $file
* @return void
*/
protected function lint($file) {
if(file_exists($file)) {
if(is_readable($file)) {
$dom = new DOMDocument();
$dom->load($file);
if($dom->schemaValidate($this->schema->getPath())) {
$this->log($file.' validated', PROJECT_MSG_INFO);
} else {
$this->log($file.' fails to validate (See messages above)', PROJECT_MSG_ERR);
}
} else {
throw new BuildException('Permission denied: '.$file);
}
} else {
throw new BuildException('File not found: '.$file);
}
}
/**
* Local error handler to catch validation errors and log them through Phing
*
* @param int $level
* @param string $message
* @param string $file
* @param int $line
*/
public function errorHandler($level, $message, $file, $line, $context) {
$matches = array();
preg_match('/^.*\(\): (.*)$/', $message, $matches);
$this->log($matches[1], PROJECT_MSG_ERR);
}
}
?> | agpl-3.0 |
CodeDJ/qt5-hidpi | qt/qtbase/src/network/bearer/qbearerplugin.cpp | 2239 | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qbearerplugin_p.h"
#ifndef QT_NO_BEARERMANAGEMENT
QT_BEGIN_NAMESPACE
QBearerEnginePlugin::QBearerEnginePlugin(QObject *parent)
: QObject(parent)
{
}
QBearerEnginePlugin::~QBearerEnginePlugin()
{
}
QT_END_NAMESPACE
#endif // QT_NO_BEARERMANAGEMENT
| lgpl-2.1 |
lcp0578/kitcmf | vendor/ruflin/elastica/test/lib/Elastica/Test/Aggregation/StatsTest.php | 1183 | <?php
namespace Elastica\Test\Aggregation;
use Elastica\Aggregation\Stats;
use Elastica\Document;
use Elastica\Query;
class StatsTest extends BaseAggregationTest
{
protected function _getIndexForTest()
{
$index = $this->_createIndex();
$index->getType('test')->addDocuments(array(
new Document(1, array('price' => 5)),
new Document(2, array('price' => 8)),
new Document(3, array('price' => 1)),
new Document(4, array('price' => 3)),
));
$index->refresh();
return $index;
}
/**
* @group functional
*/
public function testStatsAggregation()
{
$agg = new Stats('stats');
$agg->setField('price');
$query = new Query();
$query->addAggregation($agg);
$results = $this->_getIndexForTest()->search($query)->getAggregation('stats');
$this->assertEquals(4, $results['count']);
$this->assertEquals(1, $results['min']);
$this->assertEquals(8, $results['max']);
$this->assertEquals((5 + 8 + 1 + 3) / 4.0, $results['avg']);
$this->assertEquals((5 + 8 + 1 + 3), $results['sum']);
}
}
| mit |
Dackng/eh-unmsm-client | node_modules/@angular/compiler/src/expression_parser/lexer.d.ts | 1047 | export declare enum TokenType {
Character = 0,
Identifier = 1,
Keyword = 2,
String = 3,
Operator = 4,
Number = 5,
Error = 6,
}
export declare class Lexer {
tokenize(text: string): Token[];
}
export declare class Token {
index: number;
type: TokenType;
numValue: number;
strValue: string;
constructor(index: number, type: TokenType, numValue: number, strValue: string);
isCharacter(code: number): boolean;
isNumber(): boolean;
isString(): boolean;
isOperator(operater: string): boolean;
isIdentifier(): boolean;
isKeyword(): boolean;
isKeywordLet(): boolean;
isKeywordAs(): boolean;
isKeywordNull(): boolean;
isKeywordUndefined(): boolean;
isKeywordTrue(): boolean;
isKeywordFalse(): boolean;
isKeywordThis(): boolean;
isError(): boolean;
toNumber(): number;
toString(): string;
}
export declare const EOF: Token;
export declare function isIdentifier(input: string): boolean;
export declare function isQuote(code: number): boolean;
| mit |
Masterjun3/dolphin | Externals/wxWidgets3/src/common/radiobtncmn.cpp | 3384 | /////////////////////////////////////////////////////////////////////////////
// Name: src/common/radiobtncmn.cpp
// Purpose: wxRadioButton common code
// Author: Julian Smart
// Modified by:
// Created: 04/01/98
// Copyright: (c) Julian Smart
// Licence: wxWindows licence
/////////////////////////////////////////////////////////////////////////////
// ============================================================================
// declarations
// ============================================================================
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#if wxUSE_RADIOBTN
#include "wx/radiobut.h"
#ifndef WX_PRECOMP
#include "wx/settings.h"
#include "wx/dcscreen.h"
#endif
extern WXDLLEXPORT_DATA(const char) wxRadioButtonNameStr[] = "radioButton";
extern WXDLLEXPORT_DATA(const char) wxBitmapRadioButtonNameStr[] = "radioButton";
// ----------------------------------------------------------------------------
// XTI
// ----------------------------------------------------------------------------
wxDEFINE_FLAGS( wxRadioButtonStyle )
wxBEGIN_FLAGS( wxRadioButtonStyle )
// new style border flags, we put them first to
// use them for streaming out
wxFLAGS_MEMBER(wxBORDER_SIMPLE)
wxFLAGS_MEMBER(wxBORDER_SUNKEN)
wxFLAGS_MEMBER(wxBORDER_DOUBLE)
wxFLAGS_MEMBER(wxBORDER_RAISED)
wxFLAGS_MEMBER(wxBORDER_STATIC)
wxFLAGS_MEMBER(wxBORDER_NONE)
// old style border flags
wxFLAGS_MEMBER(wxSIMPLE_BORDER)
wxFLAGS_MEMBER(wxSUNKEN_BORDER)
wxFLAGS_MEMBER(wxDOUBLE_BORDER)
wxFLAGS_MEMBER(wxRAISED_BORDER)
wxFLAGS_MEMBER(wxSTATIC_BORDER)
wxFLAGS_MEMBER(wxBORDER)
// standard window styles
wxFLAGS_MEMBER(wxTAB_TRAVERSAL)
wxFLAGS_MEMBER(wxCLIP_CHILDREN)
wxFLAGS_MEMBER(wxTRANSPARENT_WINDOW)
wxFLAGS_MEMBER(wxWANTS_CHARS)
wxFLAGS_MEMBER(wxFULL_REPAINT_ON_RESIZE)
wxFLAGS_MEMBER(wxALWAYS_SHOW_SB )
wxFLAGS_MEMBER(wxVSCROLL)
wxFLAGS_MEMBER(wxHSCROLL)
wxFLAGS_MEMBER(wxRB_GROUP)
wxEND_FLAGS( wxRadioButtonStyle )
wxIMPLEMENT_DYNAMIC_CLASS_XTI(wxRadioButton, wxControl, "wx/radiobut.h");
wxBEGIN_PROPERTIES_TABLE(wxRadioButton)
wxEVENT_PROPERTY( Click, wxEVT_RADIOBUTTON, wxCommandEvent )
wxPROPERTY( Font, wxFont, SetFont, GetFont , wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, \
wxT("Helpstring"), wxT("group"))
wxPROPERTY( Label,wxString, SetLabel, GetLabel, wxString(), 0 /*flags*/, \
wxT("Helpstring"), wxT("group") )
wxPROPERTY( Value,bool, SetValue, GetValue, wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, \
wxT("Helpstring"), wxT("group") )
wxPROPERTY_FLAGS( WindowStyle, wxRadioButtonStyle, long, SetWindowStyleFlag, \
GetWindowStyleFlag, wxEMPTY_PARAMETER_VALUE, 0 /*flags*/, \
wxT("Helpstring"), wxT("group")) // style
wxEND_PROPERTIES_TABLE()
wxEMPTY_HANDLERS_TABLE(wxRadioButton)
wxCONSTRUCTOR_6( wxRadioButton, wxWindow*, Parent, wxWindowID, Id, \
wxString, Label, wxPoint, Position, wxSize, Size, long, WindowStyle )
#endif // wxUSE_RADIOBTN
| gpl-2.0 |
dgoodwin/origin | cmd/cluster-capacity/go/src/github.com/kubernetes-incubator/cluster-capacity/vendor/k8s.io/kubernetes/pkg/kubelet/eviction/types.go | 6002 | /*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package eviction
import (
"time"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/kubernetes/pkg/api/v1"
statsapi "k8s.io/kubernetes/pkg/kubelet/apis/stats/v1alpha1"
evictionapi "k8s.io/kubernetes/pkg/kubelet/eviction/api"
)
// fsStatsType defines the types of filesystem stats to collect.
type fsStatsType string
const (
// fsStatsLocalVolumeSource identifies stats for pod local volume sources.
fsStatsLocalVolumeSource fsStatsType = "localVolumeSource"
// fsStatsLogs identifies stats for pod logs.
fsStatsLogs fsStatsType = "logs"
// fsStatsRoot identifies stats for pod container writable layers.
fsStatsRoot fsStatsType = "root"
)
// Config holds information about how eviction is configured.
type Config struct {
// PressureTransitionPeriod is duration the kubelet has to wait before transititioning out of a pressure condition.
PressureTransitionPeriod time.Duration
// Maximum allowed grace period (in seconds) to use when terminating pods in response to a soft eviction threshold being met.
MaxPodGracePeriodSeconds int64
// Thresholds define the set of conditions monitored to trigger eviction.
Thresholds []evictionapi.Threshold
// KernelMemcgNotification if true will integrate with the kernel memcg notification to determine if memory thresholds are crossed.
KernelMemcgNotification bool
}
// Manager evaluates when an eviction threshold for node stability has been met on the node.
type Manager interface {
// Start starts the control loop to monitor eviction thresholds at specified interval.
Start(diskInfoProvider DiskInfoProvider, podFunc ActivePodsFunc, podCleanedUpFunc PodCleanedUpFunc, nodeProvider NodeProvider, monitoringInterval time.Duration)
// IsUnderMemoryPressure returns true if the node is under memory pressure.
IsUnderMemoryPressure() bool
// IsUnderDiskPressure returns true if the node is under disk pressure.
IsUnderDiskPressure() bool
}
// DiskInfoProvider is responsible for informing the manager how disk is configured.
type DiskInfoProvider interface {
// HasDedicatedImageFs returns true if the imagefs is on a separate device from the rootfs.
HasDedicatedImageFs() (bool, error)
}
// NodeProvider is responsible for providing the node api object describing this node
type NodeProvider interface {
// GetNode returns the node info for this node
GetNode() (*v1.Node, error)
}
// ImageGC is responsible for performing garbage collection of unused images.
type ImageGC interface {
// DeleteUnusedImages deletes unused images and returns the number of bytes freed, and an error.
// This returns the bytes freed even if an error is returned.
DeleteUnusedImages() (int64, error)
}
// ContainerGC is responsible for performing garbage collection of unused containers.
type ContainerGC interface {
// DeleteAllUnusedContainers deletes all unused containers, even those that belong to pods that are terminated, but not deleted.
// It returns an error if it is unsuccessful.
DeleteAllUnusedContainers() error
}
// KillPodFunc kills a pod.
// The pod status is updated, and then it is killed with the specified grace period.
// This function must block until either the pod is killed or an error is encountered.
// Arguments:
// pod - the pod to kill
// status - the desired status to associate with the pod (i.e. why its killed)
// gracePeriodOverride - the grace period override to use instead of what is on the pod spec
type KillPodFunc func(pod *v1.Pod, status v1.PodStatus, gracePeriodOverride *int64) error
// ActivePodsFunc returns pods bound to the kubelet that are active (i.e. non-terminal state)
type ActivePodsFunc func() []*v1.Pod
// PodCleanedUpFunc returns true if all resources associated with a pod have been reclaimed.
type PodCleanedUpFunc func(*v1.Pod) bool
// statsFunc returns the usage stats if known for an input pod.
type statsFunc func(pod *v1.Pod) (statsapi.PodStats, bool)
// rankFunc sorts the pods in eviction order
type rankFunc func(pods []*v1.Pod, stats statsFunc)
// signalObservation is the observed resource usage
type signalObservation struct {
// The resource capacity
capacity *resource.Quantity
// The available resource
available *resource.Quantity
// Time at which the observation was taken
time metav1.Time
}
// signalObservations maps a signal to an observed quantity
type signalObservations map[evictionapi.Signal]signalObservation
// thresholdsObservedAt maps a threshold to a time that it was observed
type thresholdsObservedAt map[evictionapi.Threshold]time.Time
// nodeConditionsObservedAt maps a node condition to a time that it was observed
type nodeConditionsObservedAt map[v1.NodeConditionType]time.Time
// nodeReclaimFunc is a function that knows how to reclaim a resource from the node without impacting pods.
// Returns the quantity of resources reclaimed and an error, if applicable.
// nodeReclaimFunc return the resources reclaimed even if an error occurs.
type nodeReclaimFunc func() (*resource.Quantity, error)
// nodeReclaimFuncs is an ordered list of nodeReclaimFunc
type nodeReclaimFuncs []nodeReclaimFunc
// thresholdNotifierHandlerFunc is a function that takes action in response to a crossed threshold
type thresholdNotifierHandlerFunc func(thresholdDescription string)
// ThresholdNotifier notifies the user when an attribute crosses a threshold value
type ThresholdNotifier interface {
Start(stopCh <-chan struct{})
}
| apache-2.0 |
arowla/elasticsearch | src/main/java/org/elasticsearch/action/bench/BenchmarkExecutionException.java | 1641 | /*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.action.bench;
import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.rest.RestStatus;
import java.util.ArrayList;
import java.util.List;
/**
* Indicates a benchmark failure due to too many failures being encountered.
*/
public class BenchmarkExecutionException extends ElasticsearchException {
private List<String> errorMessages = new ArrayList<>();
public BenchmarkExecutionException(String msg, Throwable cause) {
super(msg, cause);
}
public BenchmarkExecutionException(String msg, List<String> errorMessages) {
super(msg);
this.errorMessages.addAll(errorMessages);
}
public List<String> errorMessages() {
return errorMessages;
}
@Override
public RestStatus status() {
return RestStatus.INTERNAL_SERVER_ERROR;
}
}
| apache-2.0 |
kingsj/todomvc | examples/sammyjs/js/routes/active.js | 154 | /*global TodoApp */
(function () {
'use strict';
TodoApp.route('get', '#/active', function () {
TodoApp.trigger('fetchTodos', 'active');
});
})();
| mit |
MingxuanChen/weiciyuan | src/org/qii/weiciyuan/support/file/FileUploaderHttpHelper.java | 264 | package org.qii.weiciyuan.support.file;
public class FileUploaderHttpHelper {
public static interface ProgressListener {
public void transferred(long data);
public void waitServerResponse();
public void completed();
}
}
| gpl-3.0 |
KanoComputing/nush | cherrypy/test/test_wsgi_vhost.py | 1127 | import cherrypy
from cherrypy.test import helper
class WSGI_VirtualHost_Test(helper.CPWebCase):
def setup_server():
class ClassOfRoot(object):
def __init__(self, name):
self.name = name
def index(self):
return "Welcome to the %s website!" % self.name
index.exposed = True
default = cherrypy.Application(None)
domains = {}
for year in range(1997, 2008):
app = cherrypy.Application(ClassOfRoot('Class of %s' % year))
domains['www.classof%s.example' % year] = app
cherrypy.tree.graft(cherrypy._cpwsgi.VirtualHost(default, domains))
setup_server = staticmethod(setup_server)
def test_welcome(self):
if not cherrypy.server.using_wsgi:
return self.skip("skipped (not using WSGI)... ")
for year in range(1997, 2008):
self.getPage("/", headers=[('Host', 'www.classof%s.example' % year)])
self.assertBody("Welcome to the Class of %s website!" % year)
| gpl-3.0 |
feisty2007/weiciyuan | src/org/qii/weiciyuan/dao/topic/UserTopicListDao.java | 2516 | package org.qii.weiciyuan.dao.topic;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import org.qii.weiciyuan.dao.URLHelper;
import org.qii.weiciyuan.support.debug.AppLogger;
import org.qii.weiciyuan.support.error.WeiboException;
import org.qii.weiciyuan.support.http.HttpMethod;
import org.qii.weiciyuan.support.http.HttpUtility;
import org.qii.weiciyuan.support.settinghelper.SettingUtility;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* User: qii
* Date: 12-11-18
*/
public class UserTopicListDao {
private String getMsgListJson() throws WeiboException {
String url = URLHelper.TOPIC_USER_LIST;
Map<String, String> map = new HashMap<String, String>();
map.put("access_token", access_token);
map.put("count", count);
map.put("page", page);
map.put("uid", uid);
String jsonData = null;
jsonData = HttpUtility.getInstance().executeNormalTask(HttpMethod.Get, url, map);
return jsonData;
}
public ArrayList<String> getGSONMsgList() throws WeiboException {
String json = getMsgListJson();
Gson gson = new Gson();
ArrayList<TopicBean> value = null;
try {
value = gson.fromJson(json, new TypeToken<List<TopicBean>>() {
}.getType());
} catch (JsonSyntaxException e) {
AppLogger.e(e.getMessage());
}
if (value != null) {
ArrayList<String> msgList = new ArrayList<String>();
for (TopicBean b : value) {
msgList.add(b.hotword);
}
return msgList;
}
return new ArrayList<String>();
}
private String access_token;
private String uid;
private String count;
private String page;
public UserTopicListDao(String access_token, String uid) {
this.access_token = access_token;
this.count = SettingUtility.getMsgCount();
this.uid = uid;
}
public UserTopicListDao setCount(String count) {
this.count = count;
return this;
}
public UserTopicListDao setPage(String page) {
this.page = page;
return this;
}
private static class TopicBean {
private String num;
private String trend_id;
private String hotword;
}
}
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.