code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
# -*- coding: utf-8 -*-
# __init__.py
# Copyright (C) 2013 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Key Manager is a Nicknym agent for LEAP client.
"""
# let's do a little sanity check to see if we're using the wrong gnupg
import sys
try:
from gnupg.gnupg import GPGUtilities
assert(GPGUtilities) # pyflakes happy
from gnupg import __version__
from distutils.version import LooseVersion as V
assert(V(__version__) >= V('1.2.3'))
except (ImportError, AssertionError):
print "*******"
print "Ooops! It looks like there is a conflict in the installed version "
print "of gnupg."
print
print "Disclaimer: Ideally, we would need to work a patch and propose the "
print "merge to upstream. But until then do: "
print
print "% pip uninstall python-gnupg"
print "% pip install gnupg"
print "*******"
sys.exit(1)
import logging
import requests
from leap.common.check import leap_assert, leap_assert_type
from leap.common.events import signal
from leap.common.events import events_pb2 as proto
from leap.keymanager.errors import KeyNotFound
from leap.keymanager.keys import (
EncryptionKey,
build_key_from_dict,
KEYMANAGER_KEY_TAG,
TAGS_PRIVATE_INDEX,
)
from leap.keymanager.openpgp import (
OpenPGPKey,
OpenPGPScheme,
)
logger = logging.getLogger(__name__)
#
# The Key Manager
#
class KeyManager(object):
#
# server's key storage constants
#
OPENPGP_KEY = 'openpgp'
PUBKEY_KEY = "user[public_key]"
def __init__(self, address, nickserver_uri, soledad, session_id=None,
ca_cert_path=None, api_uri=None, api_version=None, uid=None,
gpgbinary=None):
"""
Initialize a Key Manager for user's C{address} with provider's
nickserver reachable in C{url}.
:param address: The address of the user of this Key Manager.
:type address: str
:param url: The URL of the nickserver.
:type url: str
:param soledad: A Soledad instance for local storage of keys.
:type soledad: leap.soledad.Soledad
:param session_id: The session ID for interacting with the webapp API.
:type session_id: str
:param ca_cert_path: The path to the CA certificate.
:type ca_cert_path: str
:param api_uri: The URI of the webapp API.
:type api_uri: str
:param api_version: The version of the webapp API.
:type api_version: str
:param uid: The users' UID.
:type uid: str
:param gpgbinary: Name for GnuPG binary executable.
:type gpgbinary: C{str}
"""
self._address = address
self._nickserver_uri = nickserver_uri
self._soledad = soledad
self._session_id = session_id
self.ca_cert_path = ca_cert_path
self.api_uri = api_uri
self.api_version = api_version
self.uid = uid
# a dict to map key types to their handlers
self._wrapper_map = {
OpenPGPKey: OpenPGPScheme(soledad, gpgbinary=gpgbinary),
# other types of key will be added to this mapper.
}
# the following are used to perform https requests
self._fetcher = requests
self._session = self._fetcher.session()
#
# utilities
#
def _key_class_from_type(self, ktype):
"""
Return key class from string representation of key type.
"""
return filter(
lambda klass: str(klass) == ktype,
self._wrapper_map).pop()
def _get(self, uri, data=None):
"""
Send a GET request to C{uri} containing C{data}.
:param uri: The URI of the request.
:type uri: str
:param data: The body of the request.
:type data: dict, str or file
:return: The response to the request.
:rtype: requests.Response
"""
leap_assert(
self._ca_cert_path is not None,
'We need the CA certificate path!')
res = self._fetcher.get(uri, data=data, verify=self._ca_cert_path)
# Nickserver now returns 404 for key not found and 500 for
# other cases (like key too small), so we are skipping this
# check for the time being
# res.raise_for_status()
# Responses are now text/plain, although it's json anyway, but
# this will fail when it shouldn't
# leap_assert(
# res.headers['content-type'].startswith('application/json'),
# 'Content-type is not JSON.')
return res
def _put(self, uri, data=None):
"""
Send a PUT request to C{uri} containing C{data}.
The request will be sent using the configured CA certificate path to
verify the server certificate and the configured session id for
authentication.
:param uri: The URI of the request.
:type uri: str
:param data: The body of the request.
:type data: dict, str or file
:return: The response to the request.
:rtype: requests.Response
"""
leap_assert(
self._ca_cert_path is not None,
'We need the CA certificate path!')
leap_assert(
self._session_id is not None,
'We need a session_id to interact with webapp!')
res = self._fetcher.put(
uri, data=data, verify=self._ca_cert_path,
cookies={'_session_id': self._session_id})
# assert that the response is valid
res.raise_for_status()
return res
def _fetch_keys_from_server(self, address):
"""
Fetch keys bound to C{address} from nickserver and insert them in
local database.
:param address: The address bound to the keys.
:type address: str
@raise KeyNotFound: If the key was not found on nickserver.
"""
# request keys from the nickserver
res = None
try:
res = self._get(self._nickserver_uri, {'address': address})
server_keys = res.json()
# insert keys in local database
if self.OPENPGP_KEY in server_keys:
self._wrapper_map[OpenPGPKey].put_ascii_key(
server_keys['openpgp'])
except Exception as e:
logger.warning("Error retrieving the keys: %r" % (e,))
if res:
logger.warning("%s" % (res.content,))
#
# key management
#
def send_key(self, ktype):
"""
Send user's key of type C{ktype} to provider.
Public key bound to user's is sent to provider, which will sign it and
replace any prior keys for the same address in its database.
If C{send_private} is True, then the private key is encrypted with
C{password} and sent to server in the same request, together with a
hash string of user's address and password. The encrypted private key
will be saved in the server in a way it is publicly retrievable
through the hash string.
:param ktype: The type of the key.
:type ktype: KeyType
@raise KeyNotFound: If the key was not found in local database.
"""
leap_assert(
ktype is OpenPGPKey,
'For now we only know how to send OpenPGP public keys.')
# prepare the public key bound to address
pubkey = self.get_key(
self._address, ktype, private=False, fetch_remote=False)
data = {
self.PUBKEY_KEY: pubkey.key_data
}
uri = "%s/%s/users/%s.json" % (
self._api_uri,
self._api_version,
self._uid)
self._put(uri, data)
signal(proto.KEYMANAGER_DONE_UPLOADING_KEYS, self._address)
def get_key(self, address, ktype, private=False, fetch_remote=True):
"""
Return a key of type C{ktype} bound to C{address}.
First, search for the key in local storage. If it is not available,
then try to fetch from nickserver.
:param address: The address bound to the key.
:type address: str
:param ktype: The type of the key.
:type ktype: KeyType
:param private: Look for a private key instead of a public one?
:type private: bool
:return: A key of type C{ktype} bound to C{address}.
:rtype: EncryptionKey
@raise KeyNotFound: If the key was not found both locally and in
keyserver.
"""
leap_assert(
ktype in self._wrapper_map,
'Unkown key type: %s.' % str(ktype))
try:
signal(proto.KEYMANAGER_LOOKING_FOR_KEY, address)
# return key if it exists in local database
key = self._wrapper_map[ktype].get_key(address, private=private)
signal(proto.KEYMANAGER_KEY_FOUND, address)
return key
except KeyNotFound:
signal(proto.KEYMANAGER_KEY_NOT_FOUND, address)
# we will only try to fetch a key from nickserver if fetch_remote
# is True and the key is not private.
if fetch_remote is False or private is True:
raise
signal(proto.KEYMANAGER_LOOKING_FOR_KEY, address)
self._fetch_keys_from_server(address)
key = self._wrapper_map[ktype].get_key(address, private=False)
signal(proto.KEYMANAGER_KEY_FOUND, address)
return key
def get_all_keys_in_local_db(self, private=False):
"""
Return all keys stored in local database.
:return: A list with all keys in local db.
:rtype: list
"""
return map(
lambda doc: build_key_from_dict(
self._key_class_from_type(doc.content['type']),
doc.content['address'],
doc.content),
self._soledad.get_from_index(
TAGS_PRIVATE_INDEX,
KEYMANAGER_KEY_TAG,
'1' if private else '0'))
def refresh_keys(self):
"""
Fetch keys from nickserver and update them locally.
"""
addresses = set(map(
lambda doc: doc.address,
self.get_all_keys_in_local_db(private=False)))
for address in addresses:
# do not attempt to refresh our own key
if address == self._address:
continue
self._fetch_keys_from_server(address)
def gen_key(self, ktype):
"""
Generate a key of type C{ktype} bound to the user's address.
:param ktype: The type of the key.
:type ktype: KeyType
:return: The generated key.
:rtype: EncryptionKey
"""
signal(proto.KEYMANAGER_STARTED_KEY_GENERATION, self._address)
key = self._wrapper_map[ktype].gen_key(self._address)
signal(proto.KEYMANAGER_FINISHED_KEY_GENERATION, self._address)
return key
#
# Setters/getters
#
def _get_session_id(self):
return self._session_id
def _set_session_id(self, session_id):
self._session_id = session_id
session_id = property(
_get_session_id, _set_session_id, doc='The session id.')
def _get_ca_cert_path(self):
return self._ca_cert_path
def _set_ca_cert_path(self, ca_cert_path):
self._ca_cert_path = ca_cert_path
ca_cert_path = property(
_get_ca_cert_path, _set_ca_cert_path,
doc='The path to the CA certificate.')
def _get_api_uri(self):
return self._api_uri
def _set_api_uri(self, api_uri):
self._api_uri = api_uri
api_uri = property(
_get_api_uri, _set_api_uri, doc='The webapp API URI.')
def _get_api_version(self):
return self._api_version
def _set_api_version(self, api_version):
self._api_version = api_version
api_version = property(
_get_api_version, _set_api_version, doc='The webapp API version.')
def _get_uid(self):
return self._uid
def _set_uid(self, uid):
self._uid = uid
uid = property(
_get_uid, _set_uid, doc='The uid of the user.')
#
# encrypt/decrypt and sign/verify API
#
def encrypt(self, data, pubkey, passphrase=None, sign=None,
cipher_algo='AES256'):
"""
Encrypt C{data} using public @{key} and sign with C{sign} key.
:param data: The data to be encrypted.
:type data: str
:param pubkey: The key used to encrypt.
:type pubkey: EncryptionKey
:param sign: The key used for signing.
:type sign: EncryptionKey
:param cipher_algo: The cipher algorithm to use.
:type cipher_algo: str
:return: The encrypted data.
:rtype: str
"""
leap_assert_type(pubkey, EncryptionKey)
leap_assert(pubkey.__class__ in self._wrapper_map, 'Unknown key type.')
leap_assert(pubkey.private is False, 'Key is not public.')
return self._wrapper_map[pubkey.__class__].encrypt(
data, pubkey, passphrase, sign)
def decrypt(self, data, privkey, passphrase=None, verify=None):
"""
Decrypt C{data} using private @{privkey} and verify with C{verify} key.
:param data: The data to be decrypted.
:type data: str
:param privkey: The key used to decrypt.
:type privkey: OpenPGPKey
:param verify: The key used to verify a signature.
:type verify: OpenPGPKey
:return: The decrypted data.
:rtype: str
@raise InvalidSignature: Raised if unable to verify the signature with
C{verify} key.
"""
leap_assert_type(privkey, EncryptionKey)
leap_assert(
privkey.__class__ in self._wrapper_map,
'Unknown key type.')
leap_assert(privkey.private is True, 'Key is not private.')
return self._wrapper_map[privkey.__class__].decrypt(
data, privkey, passphrase, verify)
def sign(self, data, privkey, digest_algo='SHA512', clearsign=False,
detach=True, binary=False):
"""
Sign C{data} with C{privkey}.
:param data: The data to be signed.
:type data: str
:param privkey: The private key to be used to sign.
:type privkey: EncryptionKey
:param digest_algo: The hash digest to use.
:type digest_algo: str
:param clearsign: If True, create a cleartext signature.
:type clearsign: bool
:param detach: If True, create a detached signature.
:type detach: bool
:param binary: If True, do not ascii armour the output.
:type binary: bool
:return: The signed data.
:rtype: str
"""
leap_assert_type(privkey, EncryptionKey)
leap_assert(
privkey.__class__ in self._wrapper_map,
'Unknown key type.')
leap_assert(privkey.private is True, 'Key is not private.')
return self._wrapper_map[privkey.__class__].sign(
data, privkey, digest_algo=digest_algo, clearsign=clearsign,
detach=detach, binary=binary)
def verify(self, data, pubkey):
"""
Verify signed C{data} with C{pubkey}.
:param data: The data to be verified.
:type data: str
:param pubkey: The public key to be used on verification.
:type pubkey: EncryptionKey
:return: The signed data.
:rtype: str
"""
leap_assert_type(pubkey, EncryptionKey)
leap_assert(pubkey.__class__ in self._wrapper_map, 'Unknown key type.')
leap_assert(pubkey.private is False, 'Key is not public.')
return self._wrapper_map[pubkey.__class__].verify(data, pubkey)
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
|
ivanalejandro0/keymanager
|
src/leap/keymanager/__init__.py
|
Python
|
gpl-3.0
| 16,455
|
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2022 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM 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.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
Espo.define('views/fields/datetime-short', 'views/fields/datetime', function (Dep) {
return Dep.extend({
listTemplate: 'fields/datetime-short/list',
detailTemplate: 'fields/datetime-short/detail',
data: function () {
var data = Dep.prototype.data.call(this);
if (this.mode == 'list' || this.mode == 'detail') {
data.fullDateValue = Dep.prototype.getDateStringValue.call(this);
}
return data;
},
getDateStringValue: function () {
if (this.mode == 'list' || this.mode == 'detail') {
var value = this.model.get(this.name)
if (value) {
var string;
var timeFormat = this.getDateTime().timeFormat;
if (this.params.hasSeconds) {
timeFormat = timeFormat.replace(/:mm/, ':mm:ss');
}
var d = this.getDateTime().toMoment(value);
var now = moment().tz(this.getDateTime().timeZone || 'UTC');
if (d.unix() > now.clone().startOf('day').unix() && d.unix() < now.clone().add(1, 'days').startOf('day').unix()) {
string = d.format(timeFormat);
return string;
}
var readableFormat = this.getDateTime().getReadableShortDateFormat();
if (d.format('YYYY') == now.format('YYYY')) {
string = d.format(readableFormat);
} else {
string = d.format(readableFormat + ', YY');
}
return string;
}
}
return Dep.prototype.getDateStringValue.call(this);
}
});
});
|
espocrm/espocrm
|
client/src/views/fields/datetime-short.js
|
JavaScript
|
gpl-3.0
| 3,185
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="bucketlist, bucket-list">
<title>Bucket-List</title>
<!--<link rel="stylesheet" href="/css/bootstrap.min.css">-->
<link rel="stylesheet" href="css/bucklst.css">
</head>
<body>
<header>
<div class="container">
<div id="branding">
<h1><span class="highlight"> BuckList</span></h1>
</div>
<nav>
<ul>
<li><a href="index.html">Home</a></li>
<li><a href="about.html">About</a></li>
<li><a href="team.html">Team</a></li>
</ul>
</nav>
</div>
</header>
<!--<section id="newsletter">
<div class="container">
<h1>Subscribe to our newsletter</h1>
<form>
<input type="email" placeholder="Enter Email" />
<button type="submit" class="btn_subscribe">Subscribe</button>
</form>
</div>
</section>-->
<section id="main">
<div class="container">
<article id="main-col">
<h1 class="page-title">Edit Bucket List Item</h1>
<form class="form" action="#">
<fieldset>
<legend>Bucket List Item Details:</legend>
<div class="form-row">
<label for="name">Name:</label>
<input type="text" name="name"><br><br>
</div>
<div class="form-row">
<label for="description">Description:</label>
<input type="text" name="description"><br><br>
</div>
<div class="form-row">
<label for="date">Date:</label>
<input type="email" name="date"><br><br>
</div>
<input type="submit" value="Edit Item"><br/>
</fieldset>
</form>
</article>
</div>
</section>
<!-- Footer content -->
<footer id="footer">
<p>© 2017 Luqee. All Rights Reserved.</p>
</footer>
<!--<script src="/js/jquery-3.2.1.min.js" charset="utf-8"></script>
<script src="/js/bootstrap.min.js" charset="utf-8"></script>-->
</body>
</html>
|
luqee/BuckList
|
UI/edit_item.html
|
HTML
|
gpl-3.0
| 2,587
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.OptionsModel;
using Yavsc;
using Yavsc.Models;
using Yavsc.Services;
public class DiskUsageTracker : IDiskUsageTracker
{
public class DUTInfo
{
public DUTInfo()
{
Creation = DateTime.Now;
}
public long Usage { get; set; }
public long Quota { get; set; }
public readonly DateTime Creation;
}
readonly Dictionary<string, DUTInfo> DiskUsage;
readonly ApplicationDbContext context;
readonly int ulistLength;
public DiskUsageTracker(IOptions<SiteSettings> options, ApplicationDbContext context)
{
ulistLength = options.Value.DUUserListLen;
DiskUsage = new Dictionary<string, DUTInfo>();
this.context = context;
}
readonly static object userInfoLock = new object();
DUTInfo GetInfo(string username)
{
lock (userInfoLock)
{
if (!DiskUsage.ContainsKey(username))
{
var user = context.Users.SingleOrDefault(u => u.UserName == username);
if (user == null) throw new Exception($"Not an user : {username}");
DUTInfo usage = new DUTInfo
{
Usage = user.DiskUsage,
Quota = user.DiskQuota
};
DiskUsage.Add(username, usage);
if (DiskUsage.Count > ulistLength)
{
// remove the oldest
var oldestts = DateTime.Now;
DUTInfo oinfo = null;
string ouname = null;
foreach (var diskusage in DiskUsage)
{
if (oldestts > usage.Creation)
{
oldestts = diskusage.Value.Creation;
ouname = diskusage.Key;
oinfo = diskusage.Value;
}
}
var ouser = context.Users.SingleOrDefault(u => u.UserName == ouname);
ouser.DiskUsage = oinfo.Usage;
context.SaveChanges();
DiskUsage.Remove(ouname);
}
return usage;
}
return DiskUsage[username];
}
}
public bool GetSpace(string userName, long space)
{
var info = GetInfo(userName);
if (info.Quota < info.Usage + space) return false;
info.Usage += space;
#pragma warning disable CS4014
SaveUserUsage(userName,info.Usage);
#pragma warning restore CS4014
return true;
}
public void Release(string userName, long space)
{
var info = GetInfo(userName);
info.Usage -= space;
#pragma warning disable CS4014
SaveUserUsage(userName,info.Usage);
#pragma warning restore CS4014
}
async Task SaveUserUsage(string username, long usage)
{
await Task.Run(() =>
{
var ouser = context.Users.SingleOrDefault(u => u.UserName == username);
ouser.DiskUsage = usage;
context.SaveChanges();
});
}
}
|
pazof/yavsc
|
src/Yavsc/Services/DiskUsageTracker.cs
|
C#
|
gpl-3.0
| 3,154
|
/* -*- indent-tabs-mode:nil; coding: utf-8 -*-
Copyright (C) 2015
"Mu Lei" known as "NalaGinrut" <NalaGinrut@gmail.com>
Grandis is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License by the Free
Software Foundation, either version 3 of the License, or (at your
option) any later version.
Grandis is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program.
If not, see <http://www.gnu.org/licenses/>.
*/
var Class = easejs.Class;
var gensym = (function () {
var cnt = 0;
return function (name) { return name + cnt++; };
}) ();
function is_defined(x) {
return ((x !== 'undefined') && x);
}
function data2url(data) {
var ret = [];
for (var k in data) {
ret.push(k + '=' + data[k]);
}
return ret.join('&');
}
// (let ((cnt 0))
// ...)
// ==> (function () { var cnt = 0; ... }) ();
|
NalaGinrut/grandis
|
utils.js
|
JavaScript
|
gpl-3.0
| 1,146
|
/*
*Copyright (c) 2009 Eucalyptus Systems, Inc.
*
* 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, only version 3 of the License.
*
*
* This file is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Please contact Eucalyptus Systems, Inc., 130 Castilian
* Dr., Goleta, CA 93101 USA or visit <http://www.eucalyptus.com/licenses/>
* if you need additional information or have any questions.
*
* This file may incorporate work covered under the following copyright and
* permission notice:
*
* Software License Agreement (BSD License)
*
* Copyright (c) 2008, Regents of the University of California
* 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.
*
* 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. USERS OF
* THIS SOFTWARE ACKNOWLEDGE THE POSSIBLE PRESENCE OF OTHER OPEN SOURCE
* LICENSED MATERIAL, COPYRIGHTED MATERIAL OR PATENTED MATERIAL IN THIS
* SOFTWARE, AND IF ANY SUCH MATERIAL IS DISCOVERED THE PARTY DISCOVERING
* IT MAY INFORM DR. RICH WOLSKI AT THE UNIVERSITY OF CALIFORNIA, SANTA
* BARBARA WHO WILL THEN ASCERTAIN THE MOST APPROPRIATE REMEDY, WHICH IN
* THE REGENTS DISCRETION MAY INCLUDE, WITHOUT LIMITATION, REPLACEMENT
* OF THE CODE SO IDENTIFIED, LICENSING OF THE CODE SO IDENTIFIED, OR
* WITHDRAWAL OF THE CODE CAPABILITY TO THE EXTENT NEEDED TO COMPLY WITH
* ANY SUCH LICENSES OR RIGHTS.
*******************************************************************************/
/*
*
* Author: Neil Soman neil@eucalyptus.com
*/
package edu.ucsb.eucalyptus.cloud.entities;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import com.eucalyptus.configurable.ConfigurableClass;
import com.eucalyptus.configurable.ConfigurableField;
import com.eucalyptus.configurable.ConfigurableFieldType;
import com.eucalyptus.configurable.ConfigurableIdentifier;
import javax.persistence.*;
@PersistenceContext(name="hippo")
@Table( name = "AOEMetaInfo" )
@Entity
@Cache( usage = CacheConcurrencyStrategy.READ_WRITE )
@ConfigurableClass(root = "storage", description = "Storage controller AOE meta info", singleton=false, deferred = true)
public class AOEMetaInfo extends LVMMetaInfo {
@ConfigurableIdentifier
@Column(name = "hostname")
private String hostName;
@ConfigurableField( description = "AOE Major Number", displayName = "AOE Major Number", type = ConfigurableFieldType.PRIVATE)
@Column(name = "major_number")
private Integer majorNumber;
@ConfigurableField( description = "AOE Minor Number", displayName = "AOE Minor Number", type = ConfigurableFieldType.PRIVATE)
@Column(name = "minor_number")
private Integer minorNumber;
public AOEMetaInfo() {}
public AOEMetaInfo(String hostName) {
this.hostName = hostName;
}
public Integer getMajorNumber() {
return majorNumber;
}
public void setMajorNumber(Integer majorNumber) {
this.majorNumber = majorNumber;
}
public Integer getMinorNumber() {
return minorNumber;
}
public void setMinorNumber(Integer minorNumber) {
this.minorNumber = minorNumber;
}
public String getHostName() {
return hostName;
}
public void setHostName(String hostName) {
this.hostName = hostName;
}
}
|
Shebella/HIPPO
|
clc/modules/core/src/main/java/edu/ucsb/eucalyptus/cloud/entities/AOEMetaInfo.java
|
Java
|
gpl-3.0
| 4,964
|
/*
* This file is part of JustDoIt.
*
* Copyright 2011 Harald Held <harald.held@gmail.com>
*
* JustDoIt 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.
*
* JustDoIt 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 JustDoIt. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QtGui/QMainWindow>
#include <QModelIndex>
#include <QSystemTrayIcon>
class QTimer;
class QStringListModel;
class UserData;
class TaskTableModel;
class TaskTableStringListComboboxDelegate;
class TaskTableColorDoneDelegate;
class TaskSortFilterProxyModel;
class TaskTableDateTimeDelegate;
class TaskTableLineEditDelegate;
class TaskTableTextEditDelegate;
class TaskTableRecurrenceDelegate;
class Reminder;
class PrintView;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void setUsrData(UserData *uData);
void setSaveFileName(const QString &xmlOutFileName);
bool event(QEvent *event);
protected:
void changeEvent(QEvent *e);
void closeEvent(QCloseEvent *event);
void hideEvent(QHideEvent *event);
void showEvent(QShowEvent *);
private:
Ui::MainWindow *ui;
UserData *uData;
QStringListModel *model_categories;
QStringListModel *model_locations;
TaskTableModel *model_tasks;
TaskTableStringListComboboxDelegate *groupDelegate;
TaskTableStringListComboboxDelegate *locationDelegate;
TaskTableColorDoneDelegate *doneColorDelegate;
TaskSortFilterProxyModel *sortFilterTasksProxy;
TaskTableDateTimeDelegate *dueDate_delegate;
TaskTableLineEditDelegate *titleDelegate;
TaskTableTextEditDelegate *descriptionDelegate;
TaskTableRecurrenceDelegate *recurrenceDelegate;
QSystemTrayIcon *sti;
QMenu *trayIconMenu;
QAction *actStartVisibility;
QAction *actHideToSysTray;
QAction *actEnableReminders;
QAction *actShowHide;
QString saveFileName;
QTimer *timer_autoSave;
QTimer *timer_updateDefaultDueDateTime;
Reminder *reminderWidget;
QTimer *timer_reminder;
PrintView *printView;
QRect lastGeometry;
void permuteColumns();
int numOfUnfinishedTasks() const;
void initSystray();
void readSettings();
void writeSettings();
void purgeAllDoneTasks();
void center();
void handleRecurringTasks(const int &position);
bool saveNeeded;
bool startVisible;
bool remindersEnabled;
public slots:
void saveXML(const QString &fileName = QString());
void updateStatusMesg();
void toggleVisibility();
void updateDefaultDueDateTime();
void deselectAllRows();
void enableReminders(bool);
void disableReminders(bool);
private slots:
void saveData();
void groupData_changed();
void locationData_changed();
void taskData_changed(QModelIndex index);
void on_button_addCategory_clicked();
void on_button_insertCategory_clicked();
void on_button_deleteCategory_clicked();
void on_button_addLocation_clicked();
void on_button_insertLocation_clicked();
void on_button_deleteLocation_clicked();
void on_button_addTask_clicked();
void on_button_deleteTask_clicked();
void on_tabWidget_currentChanged(int index);
void on_button_add_clicked();
void on_button_clear_clicked();
void trayIcon_showHide_clicked();
void trayIcon_addTask_clicked();
void trayIcon_manageTasks_clicked();
void setStartVisible(bool visibleOnStart);
void sysTrayIconClicked(QSystemTrayIcon::ActivationReason reason);
void on_actionQuit_triggered();
void on_actionPurge_triggered();
void taskRowClicked(QModelIndex);
void showReminder();
void showAboutMsg();
void on_pushButton_addAsThoughtOnly_clicked();
void on_actionPrint_triggered();
};
#endif // MAINWINDOW_H
|
hheld/JustDoIt
|
MainWindow.h
|
C
|
gpl-3.0
| 4,331
|
import json
import random
import ssl
import string
import threading
import time
import websocket
import settings
from player import Player
class WebsocketPlayerControl(object):
def __init__(self, player, server=settings.WS_SERVER):
websocket.enableTrace(settings.DEBUG)
rand_chars = string.ascii_uppercase + string.digits
self.player_id = ''.join(random.choice(rand_chars) for _ in range(10))
self.player = player
self.ws = websocket.WebSocketApp(server,
on_open=self.on_open,
on_message=self.on_message,
on_error=self.on_error)
player.song_change_callback = self.song_change
def song_change(self, identifier):
data = {
'action': 'song_change',
'player': self.player_id,
'key': settings.CLIENT_TOKEN,
'playlist': settings.PLAYLIST_ID,
'identifier': identifier
}
self.ws.send(json.dumps(data))
def start(self):
while True:
if settings.DEBUG:
print('opening websocket connection...')
sslopt = {"cert_reqs": ssl.CERT_NONE}
self.ws.run_forever(ping_interval=60, sslopt=sslopt)
time.sleep(10)
def quit(self):
self.ws.send("client disconnect")
self.ws.close()
def on_open(self, ws):
try:
name = settings.CLIENT_NAME
except AttributeError:
name = 'Client'
data = {
'action': 'register',
'player': self.player_id,
'key': settings.CLIENT_TOKEN,
'playlist': settings.PLAYLIST_ID,
'name': name
}
ws.send(json.dumps(data))
def on_message(self, ws, message):
if settings.DEBUG:
print('message received:', message)
data = json.loads(message)
if data['action'] == 'play':
self.player.play()
elif data['action'] == 'pause':
self.player.pause()
elif data['action'] == 'update_playlist':
self.player.update_playlist()
elif data['action'] == 'next':
self.player.next()
elif data['action'] == 'play_song':
self.player.play_song(data['identifier'])
def on_error(self, ws, error):
print(error)
def main():
player = Player()
ws = WebsocketPlayerControl(player)
ws_thread = threading.Thread(name='ws', target=ws.start)
try:
ws_thread.start()
player.start()
except KeyboardInterrupt:
player.quit()
ws.quit()
ws_thread.join()
if __name__ == "__main__":
main()
|
Menollo/menosic
|
client/main.py
|
Python
|
gpl-3.0
| 2,756
|
Template.messages.helpers({
messages: [
{ title : "This feature is coming soon!" }
]
});
|
ak-org/rend_ez_vous
|
client/views/messages/messages.js
|
JavaScript
|
gpl-3.0
| 110
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_11) on Mon Jun 16 17:36:06 PDT 2014 -->
<title>Uses of Class javax.net.ssl.SNIServerName (Java Platform SE 8 )</title>
<meta name="date" content="2014-06-16">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class javax.net.ssl.SNIServerName (Java Platform SE 8 )";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/net/ssl/class-use/SNIServerName.html" target="_top">Frames</a></li>
<li><a href="SNIServerName.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class javax.net.ssl.SNIServerName" class="title">Uses of Class<br>javax.net.ssl.SNIServerName</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#javax.net.ssl">javax.net.ssl</a></td>
<td class="colLast">
<div class="block">Provides classes for the secure socket package.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="javax.net.ssl">
<!-- -->
</a>
<h3>Uses of <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a> in <a href="../../../../javax/net/ssl/package-summary.html">javax.net.ssl</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing subclasses, and an explanation">
<caption><span>Subclasses of <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a> in <a href="../../../../javax/net/ssl/package-summary.html">javax.net.ssl</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../../javax/net/ssl/SNIHostName.html" title="class in javax.net.ssl">SNIHostName</a></span></code>
<div class="block">Instances of this class represent a server name of type
<a href="../../../../javax/net/ssl/StandardConstants.html#SNI_HOST_NAME"><code>host_name</code></a> in a Server Name
Indication (SNI) extension.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../javax/net/ssl/package-summary.html">javax.net.ssl</a> that return types with arguments of type <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../java/util/List.html" title="interface in java.util">List</a><<a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a>></code></td>
<td class="colLast"><span class="typeNameLabel">ExtendedSSLSession.</span><code><span class="memberNameLink"><a href="../../../../javax/net/ssl/ExtendedSSLSession.html#getRequestedServerNames--">getRequestedServerNames</a></span>()</code>
<div class="block">Obtains a <a href="../../../../java/util/List.html" title="interface in java.util"><code>List</code></a> containing all <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl"><code>SNIServerName</code></a>s
of the requested Server Name Indication (SNI) extension.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../java/util/List.html" title="interface in java.util">List</a><<a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a>></code></td>
<td class="colLast"><span class="typeNameLabel">SSLParameters.</span><code><span class="memberNameLink"><a href="../../../../javax/net/ssl/SSLParameters.html#getServerNames--">getServerNames</a></span>()</code>
<div class="block">Returns a <a href="../../../../java/util/List.html" title="interface in java.util"><code>List</code></a> containing all <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl"><code>SNIServerName</code></a>s of the
Server Name Indication (SNI) parameter, or null if none has been set.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../javax/net/ssl/package-summary.html">javax.net.ssl</a> with parameters of type <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>abstract boolean</code></td>
<td class="colLast"><span class="typeNameLabel">SNIMatcher.</span><code><span class="memberNameLink"><a href="../../../../javax/net/ssl/SNIMatcher.html#matches-javax.net.ssl.SNIServerName-">matches</a></span>(<a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a> serverName)</code>
<div class="block">Attempts to match the given <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl"><code>SNIServerName</code></a>.</div>
</td>
</tr>
</tbody>
</table>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../javax/net/ssl/package-summary.html">javax.net.ssl</a> with type arguments of type <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="typeNameLabel">SSLParameters.</span><code><span class="memberNameLink"><a href="../../../../javax/net/ssl/SSLParameters.html#setServerNames-java.util.List-">setServerNames</a></span>(<a href="../../../../java/util/List.html" title="interface in java.util">List</a><<a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">SNIServerName</a>> serverNames)</code>
<div class="block">Sets the desired <a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl"><code>SNIServerName</code></a>s of the Server Name
Indication (SNI) parameter.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../javax/net/ssl/SNIServerName.html" title="class in javax.net.ssl">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?javax/net/ssl/class-use/SNIServerName.html" target="_top">Frames</a></li>
<li><a href="SNIServerName.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
|
DeanAaron/jdk8
|
jdk8en_us/docs/api/javax/net/ssl/class-use/SNIServerName.html
|
HTML
|
gpl-3.0
| 11,730
|
package org.tellervo.desktop.setupwizard;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JDialog;
import javax.swing.JFrame;
import org.tellervo.desktop.core.App;
import org.tellervo.desktop.gui.widgets.AbstractWizardDialog;
import org.tellervo.desktop.gui.widgets.AbstractWizardPanel;
import org.tellervo.desktop.ui.Builder;
public class SetupWizard extends AbstractWizardDialog implements ActionListener{
private static final long serialVersionUID = 1L;
public SetupWizard(JFrame parent, ArrayList<AbstractWizardPanel> pages) {
super(parent,pages, "Setup Wizard", Builder.getImageAsIcon("sidebar.png"));
}
public static void launchWizard()
{
App.init();
ArrayList<AbstractWizardPanel> pages = new ArrayList<AbstractWizardPanel>();
pages.add(new WizardWelcome());
pages.add(new WizardModeChooser());
pages.add(new WizardProxy());
pages.add(new WizardServer());
pages.add(new WizardHardwareAsk());
pages.add(new WizardHardwareDo());
pages.add(new WizardHardwareTest());
pages.add(new WizardFinish());
JDialog dialog = new SetupWizard(null, pages);
dialog.setVisible(true);
}
public static void launchFirstRunWizard()
{
App.init();
ArrayList<AbstractWizardPanel> pages = new ArrayList<AbstractWizardPanel>();
pages.add(new WizardFirstRunWelcome());
pages.add(new WizardProxy());
pages.add(new WizardServer());
pages.add(new WizardHardwareAsk());
pages.add(new WizardHardwareDo());
pages.add(new WizardFinish());
JDialog dialog = new SetupWizard(null, pages);
dialog.setVisible(true);
}
}
|
petebrew/tellervo
|
src/main/java/org/tellervo/desktop/setupwizard/SetupWizard.java
|
Java
|
gpl-3.0
| 1,619
|
# *- coding: utf-8 -*-
# mailbox.py
# Copyright (C) 2013-2015 LEAP
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
IMAP Mailbox.
"""
import re
import os
import io
import cStringIO
import StringIO
import time
from collections import defaultdict
from email.utils import formatdate
from twisted.internet import defer
from twisted.internet import reactor
from twisted.logger import Logger
from twisted.mail import imap4
from zope.interface import implements
from leap.common.check import leap_assert
from leap.common.check import leap_assert_type
from leap.bitmask.mail.constants import INBOX_NAME, MessageFlags
from leap.bitmask.mail.imap.messages import IMAPMessage
# TODO LIST
# [ ] finish the implementation of IMailboxListener
# [ ] implement the rest of ISearchableMailbox
INIT_FLAGS = (MessageFlags.RECENT_FLAG, MessageFlags.LIST_FLAG)
def make_collection_listener(mailbox):
"""
Wrap a mailbox in a class that can be hashed according to the mailbox name.
This means that dicts or sets will use this new equality rule, so we won't
collect multiple instances of the same mailbox in collections like the
MessageCollection set where we keep track of listeners.
"""
class HashableMailbox(object):
def __init__(self, mbox):
self.mbox = mbox
# See #8083, pixelated adaptor introduces conflicts in the usage
self.mailbox_name = self.mbox.mbox_name + 'IMAP'
def __hash__(self):
return hash(self.mailbox_name)
def __eq__(self, other):
return self.mailbox_name == other.mbox.mbox_name + 'IMAP'
def notify_new(self):
self.mbox.notify_new()
return HashableMailbox(mailbox)
class IMAPMailbox(object):
"""
A Soledad-backed IMAP mailbox.
Implements the high-level method needed for the Mailbox interfaces.
The low-level database methods are contained in the generic
MessageCollection class. We receive an instance of it and it is made
accessible in the `collection` attribute.
"""
implements(
imap4.IMailbox,
imap4.IMailboxInfo,
imap4.ISearchableMailbox,
# XXX I think we do not need to implement CloseableMailbox, do we?
# We could remove ourselves from the collectionListener, although I
# think it simply will be garbage collected.
# imap4.ICloseableMailbox
imap4.IMessageCopier)
init_flags = INIT_FLAGS
CMD_MSG = "MESSAGES"
CMD_RECENT = "RECENT"
CMD_UIDNEXT = "UIDNEXT"
CMD_UIDVALIDITY = "UIDVALIDITY"
CMD_UNSEEN = "UNSEEN"
log = Logger()
# TODO we should turn this into a datastructure with limited capacity
_listeners = defaultdict(set)
def __init__(self, collection, rw=1):
"""
:param collection: instance of MessageCollection
:type collection: MessageCollection
:param rw: read-and-write flag for this mailbox
:type rw: int
"""
self.rw = rw
self._uidvalidity = None
self.collection = collection
self.collection.addListener(make_collection_listener(self))
@property
def mbox_name(self):
return self.collection.mbox_name
@property
def listeners(self):
"""
Returns listeners for this mbox.
The server itself is a listener to the mailbox.
so we can notify it (and should!) after changes in flags
and number of messages.
:rtype: set
"""
return self._listeners[self.mbox_name]
def get_imap_message(self, message):
d = defer.Deferred()
IMAPMessage(message, store=self.collection.store, d=d)
return d
# FIXME this grows too crazily when many instances are fired, like
# during imaptest stress testing. Should have a queue of limited size
# instead.
def addListener(self, listener):
"""
Add a listener to the listeners queue.
The server adds itself as a listener when there is a SELECT,
so it can send EXIST commands.
:param listener: listener to add
:type listener: an object that implements IMailboxListener
"""
listeners = self.listeners
self.log.debug('Adding mailbox listener: %s. Total: %s' % (
listener, len(listeners)))
listeners.add(listener)
def removeListener(self, listener):
"""
Remove a listener from the listeners queue.
:param listener: listener to remove
:type listener: an object that implements IMailboxListener
"""
self.listeners.remove(listener)
def getFlags(self):
"""
Returns the flags defined for this mailbox.
:returns: tuple of flags for this mailbox
:rtype: tuple of str
"""
flags = self.collection.mbox_wrapper.flags
if not flags:
flags = self.init_flags
flags_str = map(str, flags)
return flags_str
def setFlags(self, flags):
"""
Sets flags for this mailbox.
:param flags: a tuple with the flags
:type flags: tuple of str
"""
# XXX this is setting (overriding) old flags.
# Better pass a mode flag
leap_assert(isinstance(flags, tuple),
"flags expected to be a tuple")
return self.collection.set_mbox_attr("flags", flags)
def getUIDValidity(self):
"""
Return the unique validity identifier for this mailbox.
:return: unique validity identifier
:rtype: int
"""
return self.collection.get_mbox_attr("created")
def getUID(self, message_number):
"""
Return the UID of a message in the mailbox
.. note:: this implementation does not make much sense RIGHT NOW,
but in the future will be useful to get absolute UIDs from
message sequence numbers.
:param message: the message sequence number.
:type message: int
:rtype: int
:return: the UID of the message.
"""
# TODO support relative sequences. The (imap) message should
# receive a sequence number attribute: a deferred is not expected
return message_number
def getUIDNext(self):
"""
Return the likely UID for the next message added to this
mailbox. Currently it returns the higher UID incremented by
one.
:return: deferred with int
:rtype: Deferred
"""
d = self.collection.get_uid_next()
return d
def getMessageCount(self):
"""
Returns the total count of messages in this mailbox.
:return: deferred with int
:rtype: Deferred
"""
return self.collection.count()
def getUnseenCount(self):
"""
Returns the number of messages with the 'Unseen' flag.
:return: count of messages flagged `unseen`
:rtype: int
"""
return self.collection.count_unseen()
def getRecentCount(self):
"""
Returns the number of messages with the 'Recent' flag.
:return: count of messages flagged `recent`
:rtype: int
"""
return self.collection.count_recent()
def isWriteable(self):
"""
Get the read/write status of the mailbox.
:return: 1 if mailbox is read-writeable, 0 otherwise.
:rtype: int
"""
# XXX We don't need to store it in the mbox doc, do we?
# return int(self.collection.get_mbox_attr('rw'))
return self.rw
def getHierarchicalDelimiter(self):
"""
Returns the character used to delimite hierarchies in mailboxes.
:rtype: str
"""
return '/'
def requestStatus(self, names):
"""
Handles a status request by gathering the output of the different
status commands.
:param names: a list of strings containing the status commands
:type names: iter
"""
r = {}
maybe = defer.maybeDeferred
if self.CMD_MSG in names:
r[self.CMD_MSG] = maybe(self.getMessageCount)
if self.CMD_RECENT in names:
r[self.CMD_RECENT] = maybe(self.getRecentCount)
if self.CMD_UIDNEXT in names:
r[self.CMD_UIDNEXT] = maybe(self.getUIDNext)
if self.CMD_UIDVALIDITY in names:
r[self.CMD_UIDVALIDITY] = maybe(self.getUIDValidity)
if self.CMD_UNSEEN in names:
r[self.CMD_UNSEEN] = maybe(self.getUnseenCount)
def as_a_dict(values):
return dict(zip(r.keys(), values))
d = defer.gatherResults(r.values())
d.addCallback(as_a_dict)
return d
def addMessage(self, message, flags, date=None):
"""
Adds a message to this mailbox.
:param message: the raw message
:type message: str
:param flags: flag list
:type flags: list of str
:param date: timestamp
:type date: str, or None
:return: a deferred that will be triggered with the UID of the added
message.
"""
# TODO should raise ReadOnlyMailbox if not rw.
# TODO have a look at the cases for internal date in the rfc
# XXX we could treat the message as an IMessage from here
# TODO -- fast appends should be definitely solved by Blobs.
# A better solution will probably involve implementing MULTIAPPEND
# extension or patching imap server to support pipelining.
if isinstance(message,
(cStringIO.OutputType, StringIO.StringIO, io.BytesIO)):
message = message.getvalue()
leap_assert_type(message, basestring)
if flags is None:
flags = tuple()
else:
flags = tuple(str(flag) for flag in flags)
if date is None:
date = formatdate(time.time())
d = self.collection.add_msg(message, flags, date=date)
d.addCallback(lambda message: message.get_uid())
d.addErrback(
lambda failure: self.log.failure('Error while adding msg'))
return d
def notify_new(self, *args):
"""
Notify of new messages to all the listeners.
This will be called indirectly by the underlying collection, that will
notify this IMAPMailbox whenever there are changes in the number of
messages in the collection, since we have added ourselves to the
collection listeners.
:param args: ignored.
"""
def cbNotifyNew(result):
exists, recent = result
for listener in self.listeners:
listener.newMessages(exists, recent)
d = self._get_notify_count()
d.addCallback(cbNotifyNew)
d.addCallback(self.collection.cb_signal_unread_to_ui)
d.addErrback(lambda failure: self.log.failure('Error while notify'))
def _get_notify_count(self):
"""
Get message count and recent count for this mailbox.
:return: a deferred that will fire with a tuple, with number of
messages and number of recent messages.
:rtype: Deferred
"""
# XXX this is way too expensive in cases like multiple APPENDS.
# We should have a way of keep a cache or do a self-increment for that
# kind of calls.
d_exists = defer.maybeDeferred(self.getMessageCount)
d_recent = defer.maybeDeferred(self.getRecentCount)
d_list = [d_exists, d_recent]
def log_num_msg(result):
exists, recent = tuple(result)
self.log.debug(
'NOTIFY (%r): there are %s messages, %s recent' % (
self.mbox_name, exists, recent))
return result
d = defer.gatherResults(d_list)
d.addCallback(log_num_msg)
return d
# commands, do not rename methods
def destroy(self):
"""
Called before this mailbox is permanently deleted.
Should cleanup resources, and set the \\Noselect flag
on the mailbox.
"""
# XXX this will overwrite all the existing flags
# should better simply addFlag
self.setFlags((MessageFlags.NOSELECT_FLAG,))
def remove_mbox(_):
uuid = self.collection.mbox_uuid
d = self.collection.mbox_wrapper.delete(self.collection.store)
d.addCallback(
lambda _: self.collection.mbox_indexer.delete_table(uuid))
return d
d = self.deleteAllDocs()
d.addCallback(remove_mbox)
return d
def expunge(self):
"""
Remove all messages flagged \\Deleted
"""
if not self.isWriteable():
raise imap4.ReadOnlyMailbox
return self.collection.delete_all_flagged()
def _get_message_fun(self, uid):
"""
Return the proper method to get a message for this mailbox, depending
on the passed uid flag.
:param uid: If true, the IDs specified in the query are UIDs;
otherwise they are message sequence IDs.
:type uid: bool
:rtype: callable
"""
get_message_fun = [
self.collection.get_message_by_sequence_number,
self.collection.get_message_by_uid][uid]
return get_message_fun
def _get_messages_range(self, messages_asked, uid=True):
def get_range(messages_asked):
return self._filter_msg_seq(messages_asked)
d = self._bound_seq(messages_asked, uid)
if uid:
d.addCallback(get_range)
d.addErrback(
lambda f: self.log.failure('Error getting msg range'))
return d
def _bound_seq(self, messages_asked, uid):
"""
Put an upper bound to a messages sequence if this is open.
:param messages_asked: IDs of the messages.
:type messages_asked: MessageSet
:return: a Deferred that will fire with a MessageSet
"""
def set_last_uid(last_uid):
messages_asked.last = last_uid
return messages_asked
def set_last_seq(all_uid):
messages_asked.last = len(all_uid)
return messages_asked
if not messages_asked.last:
try:
iter(messages_asked)
except TypeError:
# looks like we cannot iterate
if uid:
d = self.collection.get_last_uid()
d.addCallback(set_last_uid)
else:
d = self.collection.all_uid_iter()
d.addCallback(set_last_seq)
return d
return defer.succeed(messages_asked)
def _filter_msg_seq(self, messages_asked):
"""
Filter a message sequence returning only the ones that do exist in the
collection.
:param messages_asked: IDs of the messages.
:type messages_asked: MessageSet
:rtype: set
"""
# TODO we could pass the asked sequence to the indexer
# all_uid_iter, and bound the sql query instead.
def filter_by_asked(all_msg_uid):
set_asked = set(messages_asked)
set_exist = set(all_msg_uid)
return set_asked.intersection(set_exist)
d = self.collection.all_uid_iter()
d.addCallback(filter_by_asked)
return d
def fetch(self, messages_asked, uid):
"""
Retrieve one or more messages in this mailbox.
from rfc 3501: The data items to be fetched can be either a single atom
or a parenthesized list.
:param messages_asked: IDs of the messages to retrieve information
about
:type messages_asked: MessageSet
:param uid: If true, the IDs are UIDs. They are message sequence IDs
otherwise.
:type uid: bool
:rtype: deferred with a generator that yields...
"""
get_msg_fun = self._get_message_fun(uid)
getimapmsg = self.get_imap_message
def get_imap_messages_for_range(msg_range):
def _get_imap_msg(messages):
d_imapmsg = []
# just in case we got bad data in here
for msg in filter(None, messages):
d_imapmsg.append(getimapmsg(msg))
return defer.gatherResults(d_imapmsg, consumeErrors=True)
def _zip_msgid(imap_messages):
zipped = zip(
list(msg_range), imap_messages)
return (item for item in zipped)
# XXX not called??
def _unset_recent(sequence):
reactor.callLater(0, self.unset_recent_flags, sequence)
return sequence
d_msg = []
for msgid in msg_range:
# XXX We want cdocs because we "probably" are asked for the
# body. We should be smarter at do_FETCH and pass a parameter
# to this method in order not to prefetch cdocs if they're not
# going to be used.
d_msg.append(get_msg_fun(msgid, get_cdocs=True))
d = defer.gatherResults(d_msg, consumeErrors=True)
d.addCallback(_get_imap_msg)
d.addCallback(_zip_msgid)
d.addErrback(
lambda failure: self.log.error(
'Error getting msg for range'))
return d
d = self._get_messages_range(messages_asked, uid)
d.addCallback(get_imap_messages_for_range)
d.addErrback(
lambda failure: self.log.failure('Error on fetch'))
return d
def fetch_flags(self, messages_asked, uid):
"""
A fast method to fetch all flags, tricking just the
needed subset of the MIME interface that's needed to satisfy
a generic FLAGS query.
Given how LEAP Mail is supposed to work without local cache,
this query is going to be quite common, and also we expect
it to be in the form 1:* at the beginning of a session, so
it's not bad to fetch all the FLAGS docs at once.
:param messages_asked: IDs of the messages to retrieve information
about
:type messages_asked: MessageSet
:param uid: If 1, the IDs are UIDs. They are message sequence IDs
otherwise.
:type uid: int
:return: A tuple of two-tuples of message sequence numbers and
flagsPart, which is a only a partial implementation of
MessagePart.
:rtype: tuple
"""
# is_sequence = True if uid == 0 else False
# XXX FIXME -----------------------------------------------------
# imap/tests, or muas like mutt, it will choke until we implement
# sequence numbers. This is an easy hack meanwhile.
is_sequence = False
# ---------------------------------------------------------------
if is_sequence:
raise NotImplementedError(
"FETCH FLAGS NOT IMPLEMENTED FOR MESSAGE SEQUENCE NUMBERS YET")
d = defer.Deferred()
reactor.callLater(0, self._do_fetch_flags, messages_asked, uid, d)
return d
def _do_fetch_flags(self, messages_asked, uid, d):
"""
:param messages_asked: IDs of the messages to retrieve information
about
:type messages_asked: MessageSet
:param uid: If 1, the IDs are UIDs. They are message sequence IDs
otherwise.
:type uid: int
:param d: deferred whose callback will be called with result.
:type d: Deferred
:rtype: A generator that yields two-tuples of message sequence numbers
and flagsPart
"""
class flagsPart(object):
def __init__(self, uid, flags):
self.uid = uid
self.flags = flags
def getUID(self):
return self.uid
def getFlags(self):
return map(str, self.flags)
def pack_flags(result):
_uid, _flags = result
return _uid, flagsPart(_uid, _flags)
def get_flags_for_seq(sequence):
d_all_flags = []
for msgid in sequence:
# TODO implement sequence numbers here too
d_flags_per_uid = self.collection.get_flags_by_uid(msgid)
d_flags_per_uid.addCallback(pack_flags)
d_all_flags.append(d_flags_per_uid)
gotflags = defer.gatherResults(d_all_flags)
gotflags.addCallback(get_uid_flag_generator)
return gotflags
def get_uid_flag_generator(result):
generator = (item for item in result)
d.callback(generator)
d_seq = self._get_messages_range(messages_asked, uid)
d_seq.addCallback(get_flags_for_seq)
return d_seq
@defer.inlineCallbacks
def fetch_headers(self, messages_asked, uid):
"""
A fast method to fetch all headers, tricking just the
needed subset of the MIME interface that's needed to satisfy
a generic HEADERS query.
Given how LEAP Mail is supposed to work without local cache,
this query is going to be quite common, and also we expect
it to be in the form 1:* at the beginning of a session, so
**MAYBE** it's not too bad to fetch all the HEADERS docs at once.
:param messages_asked: IDs of the messages to retrieve information
about
:type messages_asked: MessageSet
:param uid: If true, the IDs are UIDs. They are message sequence IDs
otherwise.
:type uid: bool
:return: A tuple of two-tuples of message sequence numbers and
headersPart, which is a only a partial implementation of
MessagePart.
:rtype: tuple
"""
# TODO implement sequences
is_sequence = True if uid == 0 else False
if is_sequence:
raise NotImplementedError(
"FETCH HEADERS NOT IMPLEMENTED FOR SEQUENCE NUMBER YET")
class headersPart(object):
def __init__(self, uid, headers):
self.uid = uid
self.headers = headers
def getUID(self):
return self.uid
def getHeaders(self, _):
return dict(
(str(key), str(value))
for key, value in
self.headers.items())
messages_asked = yield self._bound_seq(messages_asked, uid)
seq_messg = yield self._filter_msg_seq(messages_asked)
result = []
for msgid in seq_messg:
msg = yield self.collection.get_message_by_uid(msgid)
headers = headersPart(msgid, msg.get_headers())
result.append((msgid, headers))
defer.returnValue(iter(result))
def store(self, messages_asked, flags, mode, uid):
"""
Sets the flags of one or more messages.
:param messages: The identifiers of the messages to set the flags
:type messages: A MessageSet object with the list of messages requested
:param flags: The flags to set, unset, or add.
:type flags: sequence of str
:param mode: If mode is -1, these flags should be removed from the
specified messages. If mode is 1, these flags should be
added to the specified messages. If mode is 0, all
existing flags should be cleared and these flags should be
added.
:type mode: -1, 0, or 1
:param uid: If true, the IDs specified in the query are UIDs;
otherwise they are message sequence IDs.
:type uid: bool
:return: A deferred, that will be called with a dict mapping message
sequence numbers to sequences of str representing the flags
set on the message after this operation has been performed.
:rtype: deferred
:raise ReadOnlyMailbox: Raised if this mailbox is not open for
read-write.
"""
if not self.isWriteable():
self.log.info('Read only mailbox!')
raise imap4.ReadOnlyMailbox
d = defer.Deferred()
reactor.callLater(0, self._do_store, messages_asked, flags,
mode, uid, d)
d.addCallback(self.collection.cb_signal_unread_to_ui)
d.addErrback(lambda f: self.log.error('Error on store'))
return d
def _do_store(self, messages_asked, flags, mode, uid, observer):
"""
Helper method, invoke set_flags method in the IMAPMessageCollection.
See the documentation for the `store` method for the parameters.
:param observer: a deferred that will be called with the dictionary
mapping UIDs to flags after the operation has been
done.
:type observer: deferred
"""
# TODO we should prevent client from setting Recent flag
get_msg_fun = self._get_message_fun(uid)
leap_assert(not isinstance(flags, basestring),
"flags cannot be a string")
flags = tuple(flags)
def set_flags_for_seq(sequence):
def return_result_dict(list_of_flags):
result = dict(zip(list(sequence), list_of_flags))
observer.callback(result)
return result
d_all_set = []
for msgid in sequence:
d = get_msg_fun(msgid)
d.addCallback(lambda msg: self.collection.update_flags(
msg, flags, mode))
d_all_set.append(d)
got_flags_setted = defer.gatherResults(d_all_set)
got_flags_setted.addCallback(return_result_dict)
return got_flags_setted
d_seq = self._get_messages_range(messages_asked, uid)
d_seq.addCallback(set_flags_for_seq)
return d_seq
# ISearchableMailbox
def search(self, query, uid):
"""
Search for messages that meet the given query criteria.
Warning: this is half-baked, and it might give problems since
it offers the SearchableInterface.
We'll be implementing it asap.
:param query: The search criteria
:type query: list
:param uid: If true, the IDs specified in the query are UIDs;
otherwise they are message sequence IDs.
:type uid: bool
:return: A list of message sequence numbers or message UIDs which
match the search criteria or a C{Deferred} whose callback
will be invoked with such a list.
:rtype: C{list} or C{Deferred}
"""
# TODO see if we can raise w/o interrupting flow
# :raise IllegalQueryError: Raised when query is not valid.
# example query:
# ['UNDELETED', 'HEADER', 'Message-ID',
# XXX fixme, does not exist
# '52D44F11.9060107@dev.bitmask.net']
# TODO hardcoding for now! -- we'll support generic queries later on
# but doing a quickfix for avoiding duplicate saves in the draft
# folder. # See issue #4209
if len(query) > 2:
if query[1] == 'HEADER' and query[2].lower() == "message-id":
msgid = str(query[3]).strip()
self.log.debug('Searching for %s' % (msgid,))
d = self.collection.get_uid_from_msgid(str(msgid))
d.addCallback(lambda result: [result])
return d
# nothing implemented for any other query
self.log.warn('Cannot process query: %s' % (query,))
return []
# IMessageCopier
def copy(self, message):
"""
Copy the given message object into this mailbox.
:param message: an IMessage implementor
:type message: LeapMessage
:return: a deferred that will be fired with the message
uid when the copy succeed.
:rtype: Deferred
"""
d = self.collection.copy_msg(
message.message, self.collection.mbox_uuid)
return d
# convenience fun
def deleteAllDocs(self):
"""
Delete all docs in this mailbox
"""
# FIXME not implemented
return self.collection.delete_all_docs()
def unset_recent_flags(self, uid_seq):
"""
Unset Recent flag for a sequence of UIDs.
"""
# FIXME not implemented
return self.collection.unset_recent_flags(uid_seq)
def __repr__(self):
"""
Representation string for this mailbox.
"""
return u"<IMAPMailbox: mbox '%s' (%s)>" % (
self.mbox_name, self.collection.count())
_INBOX_RE = re.compile(INBOX_NAME, re.IGNORECASE)
def normalize_mailbox(name):
"""
Return a normalized representation of the mailbox ``name``.
This method ensures that an eventual initial 'inbox' part of a
mailbox name is made uppercase.
:param name: the name of the mailbox
:type name: unicode
:rtype: unicode
"""
# XXX maybe it would make sense to normalize common folders too:
# trash, sent, drafts, etc...
if _INBOX_RE.match(name):
# ensure inital INBOX is uppercase
return INBOX_NAME + name[len(INBOX_NAME):]
return name
|
leapcode/bitmask-dev
|
src/leap/bitmask/mail/imap/mailbox.py
|
Python
|
gpl-3.0
| 30,254
|
<?php
class AccesoDatos
{
private static $_objetoAccesoDatos;
private $_objetoPDO;
private function __construct()
{
try {
$this->_objetoPDO = new PDO('mysql:host=localhost;dbname=cdcol;charset=utf8', 'root', '', array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$this->_objetoPDO->exec("SET CHARACTER SET utf8");
} catch (PDOException $e) {
print "Error!!!<br/>" . $e->getMessage();
die();
}
}
public function RetornarConsulta($sql)
{
return $this->_objetoPDO->prepare($sql);
}
public static function DameUnObjetoAcceso()//singleton
{
if (!isset(self::$_objetoAccesoDatos)) {
self::$_objetoAccesoDatos = new AccesoDatos();
}
return self::$_objetoAccesoDatos;
}
// Evita que el objeto se pueda clonar
public function __clone()
{
trigger_error('La clonación de este objeto no está permitida!!!', E_USER_ERROR);
}
}
?>
|
1caruxx/Ejercicios_PHP
|
H._PDO/ejemplo/clases/AccesoDatos.php
|
PHP
|
gpl-3.0
| 1,088
|
/* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2011 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h
*/
/* @(#) $Id$ */
#ifndef ZCONF_H
#define ZCONF_H
/*
* If you *really* need a unique prefix for all types and library functions,
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
* Even better than compiling with -DZ_PREFIX would be to use configure to set
* this permanently in zconf.h using "./configure --zprefix".
*/
#ifdef Z_PREFIX /* may be set to #if 1 by ./configure */
# define Z_PREFIX_SET
/* all linked symbols */
# define _dist_code z__dist_code
# define _length_code z__length_code
# define _tr_align z__tr_align
# define _tr_flush_block z__tr_flush_block
# define _tr_init z__tr_init
# define _tr_stored_block z__tr_stored_block
# define _tr_tally z__tr_tally
# define adler32 z_adler32
# define adler32_combine z_adler32_combine
# define adler32_combine64 z_adler32_combine64
# define compress z_compress
# define compress2 z_compress2
# define compressBound z_compressBound
# define crc32 z_crc32
# define crc32_combine z_crc32_combine
# define crc32_combine64 z_crc32_combine64
# define deflate z_deflate
# define deflateBound z_deflateBound
# define deflateCopy z_deflateCopy
# define deflateEnd z_deflateEnd
# define deflateInit2_ z_deflateInit2_
# define deflateInit_ z_deflateInit_
# define deflateParams z_deflateParams
# define deflatePending z_deflatePending
# define deflatePrime z_deflatePrime
# define deflateReset z_deflateReset
# define deflateSetDictionary z_deflateSetDictionary
# define deflateSetHeader z_deflateSetHeader
# define deflateTune z_deflateTune
# define deflate_copyright z_deflate_copyright
# define get_crc_table z_get_crc_table
# define gz_error z_gz_error
# define gz_intmax z_gz_intmax
# define gz_strwinerror z_gz_strwinerror
# define gzbuffer z_gzbuffer
# define gzclearerr z_gzclearerr
# define gzclose z_gzclose
# define gzclose_r z_gzclose_r
# define gzclose_w z_gzclose_w
# define gzdirect z_gzdirect
# define gzdopen z_gzdopen
# define gzeof z_gzeof
# define gzerror z_gzerror
# define gzflush z_gzflush
# define gzgetc z_gzgetc
# define gzgets z_gzgets
# define gzoffset z_gzoffset
# define gzoffset64 z_gzoffset64
# define gzopen z_gzopen
# define gzopen64 z_gzopen64
# define gzprintf z_gzprintf
# define gzputc z_gzputc
# define gzputs z_gzputs
# define gzread z_gzread
# define gzrewind z_gzrewind
# define gzseek z_gzseek
# define gzseek64 z_gzseek64
# define gzsetparams z_gzsetparams
# define gztell z_gztell
# define gztell64 z_gztell64
# define gzungetc z_gzungetc
# define gzwrite z_gzwrite
# define inflate z_inflate
# define inflateBack z_inflateBack
# define inflateBackEnd z_inflateBackEnd
# define inflateBackInit_ z_inflateBackInit_
# define inflateCopy z_inflateCopy
# define inflateEnd z_inflateEnd
# define inflateGetHeader z_inflateGetHeader
# define inflateInit2_ z_inflateInit2_
# define inflateInit_ z_inflateInit_
# define inflateMark z_inflateMark
# define inflatePrime z_inflatePrime
# define inflateReset z_inflateReset
# define inflateReset2 z_inflateReset2
# define inflateSetDictionary z_inflateSetDictionary
# define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint
# define inflateUndermine z_inflateUndermine
# define inflate_copyright z_inflate_copyright
# define inflate_fast z_inflate_fast
# define inflate_table z_inflate_table
# define uncompress z_uncompress
# define zError z_zError
# define zcalloc z_zcalloc
# define zcfree z_zcfree
# define zlibCompileFlags z_zlibCompileFlags
# define zlibVersion z_zlibVersion
/* all zlib typedefs in zlib.h and zconf.h */
# define Byte z_Byte
# define Bytef z_Bytef
# define alloc_func z_alloc_func
# define charf z_charf
# define free_func z_free_func
# define gzFile z_gzFile
# define gz_header z_gz_header
# define gz_headerp z_gz_headerp
# define in_func z_in_func
# define intf z_intf
# define out_func z_out_func
# define uInt z_uInt
# define uIntf z_uIntf
# define uLong z_uLong
# define uLongf z_uLongf
# define voidp z_voidp
# define voidpc z_voidpc
# define voidpf z_voidpf
/* all zlib structs in zlib.h and zconf.h */
# define gz_header_s z_gz_header_s
# define internal_state z_internal_state
#endif
#if defined(__MSDOS__) && !defined(MSDOS)
# define MSDOS
#endif
#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
# define OS2
#endif
#if defined(_WINDOWS) && !defined(WINDOWS)
# define WINDOWS
#endif
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
# ifndef WIN32
# define WIN32
# endif
#endif
#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
# if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
# ifndef SYS16BIT
# define SYS16BIT
# endif
# endif
#endif
/*
* Compile with -DMAXSEG_64K if the alloc function cannot allocate more
* than 64k bytes at a time (needed on systems with 16-bit int).
*/
#ifdef SYS16BIT
# define MAXSEG_64K
#endif
#ifdef MSDOS
# define UNALIGNED_OK
#endif
#ifdef __STDC_VERSION__
# ifndef STDC
# define STDC
# endif
# if __STDC_VERSION__ >= 199901L
# ifndef STDC99
# define STDC99
# endif
# endif
#endif
#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
# define STDC
#endif
#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
# define STDC
#endif
#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
# define STDC
#endif
#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
# define STDC
#endif
#if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
# define STDC
#endif
#ifndef STDC
# ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
# define const /* note: need a more gentle solution here */
# endif
#endif
/* Some Mac compilers merge all .h files incorrectly: */
#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
# define NO_DUMMY_DECL
#endif
/* Maximum value for memLevel in deflateInit2 */
#ifndef MAX_MEM_LEVEL
# ifdef MAXSEG_64K
# define MAX_MEM_LEVEL 8
# else
# define MAX_MEM_LEVEL 9
# endif
#endif
/* Maximum value for windowBits in deflateInit2 and inflateInit2.
* WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
* created by gzip. (Files created by minigzip can still be extracted by
* gzip.)
*/
#ifndef MAX_WBITS
# define MAX_WBITS 15 /* 32K LZ77 window */
#endif
/* The memory requirements for deflate are (in bytes):
(1 << (windowBits+2)) + (1 << (memLevel+9))
that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
plus a few kilobytes for small objects. For example, if you want to reduce
the default memory requirements from 256K to 128K, compile with
make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
Of course this will generally degrade compression (there's no free lunch).
The memory requirements for inflate are (in bytes) 1 << windowBits
that is, 32K for windowBits=15 (default value) plus a few kilobytes
for small objects.
*/
/* Type declarations */
#ifndef OF /* function prototypes */
# ifdef STDC
# define OF(args) args
# else
# define OF(args) ()
# endif
#endif
#ifndef ON /* function prototypes for stdarg */
# if defined(STDC) || defined(Z_HAVE_STDARG_H)
# define ON(args) args
# else
# define ON(args) ()
# endif
#endif
/* The following definitions for FAR are needed only for MSDOS mixed
* model programming (small or medium model with some far allocations).
* This was tested only with MSC; for other MSDOS compilers you may have
* to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
* just define FAR to be empty.
*/
#ifdef SYS16BIT
# if defined(M_I86SM) || defined(M_I86MM)
/* MSC small or medium model */
# define SMALL_MEDIUM
# ifdef _MSC_VER
# define FAR _far
# else
# define FAR far
# endif
# endif
# if (defined(__SMALL__) || defined(__MEDIUM__))
/* Turbo C small or medium model */
# define SMALL_MEDIUM
# ifdef __BORLANDC__
# define FAR _far
# else
# define FAR far
# endif
# endif
#endif
#if defined(WINDOWS) || defined(WIN32)
/* If building or using zlib as a DLL, define ZLIB_DLL.
* This is not mandatory, but it offers a little performance increase.
*/
# ifdef ZLIB_DLL
# if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
# ifdef ZLIB_INTERNAL
# define ZEXTERN extern __declspec(dllexport)
# else
# define ZEXTERN extern __declspec(dllimport)
# endif
# endif
# endif /* ZLIB_DLL */
/* If building or using zlib with the WINAPI/WINAPIV calling convention,
* define ZLIB_WINAPI.
* Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
*/
# ifdef ZLIB_WINAPI
# ifdef FAR
# undef FAR
# endif
# include <windows.h>
/* No need for _export, use ZLIB.DEF instead. */
/* For complete Windows compatibility, use WINAPI, not __stdcall. */
# define ZEXPORT WINAPI
# ifdef WIN32
# define ZEXPORTVA WINAPIV
# else
# define ZEXPORTVA FAR CDECL
# endif
# endif
#endif
#if defined (__BEOS__)
# ifdef ZLIB_DLL
# ifdef ZLIB_INTERNAL
# define ZEXPORT __declspec(dllexport)
# define ZEXPORTVA __declspec(dllexport)
# else
# define ZEXPORT __declspec(dllimport)
# define ZEXPORTVA __declspec(dllimport)
# endif
# endif
#endif
#ifndef ZEXTERN
# define ZEXTERN extern
#endif
#ifndef ZEXPORT
# define ZEXPORT
#endif
#ifndef ZEXPORTVA
# define ZEXPORTVA
#endif
#ifndef FAR
# define FAR
#endif
#if !defined(__MACTYPES__)
typedef unsigned char Byte; /* 8 bits */
#endif
typedef unsigned int uInt; /* 16 bits or more */
typedef unsigned long uLong; /* 32 bits or more */
#ifdef SMALL_MEDIUM
/* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
# define Bytef Byte FAR
#else
typedef Byte FAR Bytef;
#endif
typedef char FAR charf;
typedef int FAR intf;
typedef uInt FAR uIntf;
typedef uLong FAR uLongf;
#ifdef STDC
typedef void const *voidpc;
typedef void FAR *voidpf;
typedef void *voidp;
#else
typedef Byte const *voidpc;
typedef Byte FAR *voidpf;
typedef Byte *voidp;
#endif
#ifdef HAVE_UNISTD_H /* may be set to #if 1 by ./configure */
# define Z_HAVE_UNISTD_H
#endif
#ifdef HAVE_STDARG_H /* may be set to #if 1 by ./configure */
# define Z_HAVE_STDARG_H
#endif
#ifdef STDC
# include <sys/types.h> /* for off_t */
#endif
/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
* "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
* though the former does not conform to the LFS document), but considering
* both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
* equivalently requesting no 64-bit operations
*/
#if -_LARGEFILE64_SOURCE - -1 == 1
# undef _LARGEFILE64_SOURCE
#endif
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
# define Z_LARGE
#endif
#if defined(Z_HAVE_UNISTD_H) || defined(Z_LARGE)
# include <unistd.h> /* for SEEK_* and off_t */
# ifdef VMS
# include <unixio.h> /* for off_t */
# endif
# ifndef z_off_t
# define z_off_t off_t
# endif
#endif
#ifndef SEEK_SET
# define SEEK_SET 0 /* Seek from beginning of file. */
# define SEEK_CUR 1 /* Seek from current position. */
# define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
#endif
#ifndef z_off_t
# define z_off_t long
#endif
#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
# define z_off64_t off64_t
#else
# define z_off64_t z_off_t
#endif
#if defined(__OS400__)
# define NO_vsnprintf
#endif
#if defined(__MVS__)
# define NO_vsnprintf
#endif
/* MVS linker does not support external names larger than 8 bytes */
#if defined(__MVS__)
#pragma map(deflateInit_,"DEIN")
#pragma map(deflateInit2_,"DEIN2")
#pragma map(deflateEnd,"DEEND")
#pragma map(deflateBound,"DEBND")
#pragma map(inflateInit_,"ININ")
#pragma map(inflateInit2_,"ININ2")
#pragma map(inflateEnd,"INEND")
#pragma map(inflateSync,"INSY")
#pragma map(inflateSetDictionary,"INSEDI")
#pragma map(compressBound,"CMBND")
#pragma map(inflate_table,"INTABL")
#pragma map(inflate_fast,"INFA")
#pragma map(inflate_copyright,"INCOPY")
#endif
#endif /* ZCONF_H */
|
SakuraSinojun/codeinside
|
svnspot.com/sakurasinojun.codeinside/client/render/zlib/zconf.h
|
C
|
gpl-3.0
| 13,788
|
/*
* Copyright (C) 2001 Sistina Software (UK) Limited.
* Copyright (C) 2004-2008 Red Hat, Inc. All rights reserved.
*
* This file is released under the GPL.
*/
#include "dm-core.h"
#include <linux/module.h>
#include <linux/vmalloc.h>
#include <linux/blkdev.h>
#include <linux/namei.h>
#include <linux/ctype.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/mutex.h>
#include <linux/delay.h>
#include <linux/atomic.h>
#include <linux/blk-mq.h>
#include <linux/mount.h>
#define DM_MSG_PREFIX "table"
#define MAX_DEPTH 16
#define NODE_SIZE L1_CACHE_BYTES
#define KEYS_PER_NODE (NODE_SIZE / sizeof(sector_t))
#define CHILDREN_PER_NODE (KEYS_PER_NODE + 1)
struct dm_table
{
struct mapped_device *md;
unsigned type;
/* btree table */
unsigned int depth;
unsigned int counts[MAX_DEPTH]; /* in nodes */
sector_t *index[MAX_DEPTH];
unsigned int num_targets;
unsigned int num_allocated;
sector_t *highs;
struct dm_target *targets;
struct target_type *immutable_target_type;
bool integrity_supported: 1;
bool singleton: 1;
bool all_blk_mq: 1;
/*
* Indicates the rw permissions for the new logical
* device. This should be a combination of FMODE_READ
* and FMODE_WRITE.
*/
fmode_t mode;
/* a list of devices used by this table */
struct list_head devices;
/* events get handed up using this callback */
void (*event_fn)(void *);
void *event_context;
struct dm_md_mempools *mempools;
struct list_head target_callbacks;
};
/*
* Similar to ceiling(log_size(n))
*/
static unsigned int int_log(unsigned int n, unsigned int base)
{
int result = 0;
while (n > 1)
{
n = dm_div_up(n, base);
result++;
}
return result;
}
/*
* Calculate the index of the child node of the n'th node k'th key.
*/
static inline unsigned int get_child(unsigned int n, unsigned int k)
{
return (n * CHILDREN_PER_NODE) + k;
}
/*
* Return the n'th node of level l from table t.
*/
static inline sector_t *get_node(struct dm_table *t,
unsigned int l, unsigned int n)
{
return t->index[l] + (n * KEYS_PER_NODE);
}
/*
* Return the highest key that you could lookup from the n'th
* node on level l of the btree.
*/
static sector_t high(struct dm_table *t, unsigned int l, unsigned int n)
{
for (; l < t->depth - 1; l++)
{
n = get_child(n, CHILDREN_PER_NODE - 1);
}
if (n >= t->counts[l])
{
return (sector_t) - 1;
}
return get_node(t, l, n)[KEYS_PER_NODE - 1];
}
/*
* Fills in a level of the btree based on the highs of the level
* below it.
*/
static int setup_btree_index(unsigned int l, struct dm_table *t)
{
unsigned int n, k;
sector_t *node;
for (n = 0U; n < t->counts[l]; n++)
{
node = get_node(t, l, n);
for (k = 0U; k < KEYS_PER_NODE; k++)
{
node[k] = high(t, l + 1, get_child(n, k));
}
}
return 0;
}
void *dm_vcalloc(unsigned long nmemb, unsigned long elem_size)
{
unsigned long size;
void *addr;
/*
* Check that we're not going to overflow.
*/
if (nmemb > (ULONG_MAX / elem_size))
{
return NULL;
}
size = nmemb * elem_size;
addr = vzalloc(size);
return addr;
}
EXPORT_SYMBOL(dm_vcalloc);
/*
* highs, and targets are managed as dynamic arrays during a
* table load.
*/
static int alloc_targets(struct dm_table *t, unsigned int num)
{
sector_t *n_highs;
struct dm_target *n_targets;
/*
* Allocate both the target array and offset array at once.
* Append an empty entry to catch sectors beyond the end of
* the device.
*/
n_highs = (sector_t *) dm_vcalloc(num + 1, sizeof(struct dm_target) +
sizeof(sector_t));
if (!n_highs)
{
return -ENOMEM;
}
n_targets = (struct dm_target *) (n_highs + num);
memset(n_highs, -1, sizeof(*n_highs) * num);
vfree(t->highs);
t->num_allocated = num;
t->highs = n_highs;
t->targets = n_targets;
return 0;
}
int dm_table_create(struct dm_table **result, fmode_t mode,
unsigned num_targets, struct mapped_device *md)
{
struct dm_table *t = kzalloc(sizeof(*t), GFP_KERNEL);
if (!t)
{
return -ENOMEM;
}
INIT_LIST_HEAD(&t->devices);
INIT_LIST_HEAD(&t->target_callbacks);
if (!num_targets)
{
num_targets = KEYS_PER_NODE;
}
num_targets = dm_round_up(num_targets, KEYS_PER_NODE);
if (!num_targets)
{
kfree(t);
return -ENOMEM;
}
if (alloc_targets(t, num_targets))
{
kfree(t);
return -ENOMEM;
}
t->type = DM_TYPE_NONE;
t->mode = mode;
t->md = md;
*result = t;
return 0;
}
static void free_devices(struct list_head *devices, struct mapped_device *md)
{
struct list_head *tmp, *next;
list_for_each_safe(tmp, next, devices)
{
struct dm_dev_internal *dd =
list_entry(tmp, struct dm_dev_internal, list);
DMWARN("%s: dm_table_destroy: dm_put_device call missing for %s",
dm_device_name(md), dd->dm_dev->name);
dm_put_table_device(md, dd->dm_dev);
kfree(dd);
}
}
void dm_table_destroy(struct dm_table *t)
{
unsigned int i;
if (!t)
{
return;
}
/* free the indexes */
if (t->depth >= 2)
{
vfree(t->index[t->depth - 2]);
}
/* free the targets */
for (i = 0; i < t->num_targets; i++)
{
struct dm_target *tgt = t->targets + i;
if (tgt->type->dtr)
{
tgt->type->dtr(tgt);
}
dm_put_target_type(tgt->type);
}
vfree(t->highs);
/* free the device list */
free_devices(&t->devices, t->md);
dm_free_md_mempools(t->mempools);
kfree(t);
}
/*
* See if we've already got a device in the list.
*/
static struct dm_dev_internal *find_device(struct list_head *l, dev_t dev)
{
struct dm_dev_internal *dd;
list_for_each_entry (dd, l, list)
if (dd->dm_dev->bdev->bd_dev == dev)
{
return dd;
}
return NULL;
}
/*
* If possible, this checks an area of a destination device is invalid.
*/
static int device_area_is_invalid(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q;
struct queue_limits *limits = data;
struct block_device *bdev = dev->bdev;
sector_t dev_size =
i_size_read(bdev->bd_inode) >> SECTOR_SHIFT;
unsigned short logical_block_size_sectors =
limits->logical_block_size >> SECTOR_SHIFT;
char b[BDEVNAME_SIZE];
/*
* Some devices exist without request functions,
* such as loop devices not yet bound to backing files.
* Forbid the use of such devices.
*/
q = bdev_get_queue(bdev);
if (!q || !q->make_request_fn)
{
DMWARN("%s: %s is not yet initialised: "
"start=%llu, len=%llu, dev_size=%llu",
dm_device_name(ti->table->md), bdevname(bdev, b),
(unsigned long long)start,
(unsigned long long)len,
(unsigned long long)dev_size);
return 1;
}
if (!dev_size)
{
return 0;
}
if ((start >= dev_size) || (start + len > dev_size))
{
DMWARN("%s: %s too small for target: "
"start=%llu, len=%llu, dev_size=%llu",
dm_device_name(ti->table->md), bdevname(bdev, b),
(unsigned long long)start,
(unsigned long long)len,
(unsigned long long)dev_size);
return 1;
}
if (logical_block_size_sectors <= 1)
{
return 0;
}
if (start & (logical_block_size_sectors - 1))
{
DMWARN("%s: start=%llu not aligned to h/w "
"logical block size %u of %s",
dm_device_name(ti->table->md),
(unsigned long long)start,
limits->logical_block_size, bdevname(bdev, b));
return 1;
}
if (len & (logical_block_size_sectors - 1))
{
DMWARN("%s: len=%llu not aligned to h/w "
"logical block size %u of %s",
dm_device_name(ti->table->md),
(unsigned long long)len,
limits->logical_block_size, bdevname(bdev, b));
return 1;
}
return 0;
}
/*
* This upgrades the mode on an already open dm_dev, being
* careful to leave things as they were if we fail to reopen the
* device and not to touch the existing bdev field in case
* it is accessed concurrently inside dm_table_any_congested().
*/
static int upgrade_mode(struct dm_dev_internal *dd, fmode_t new_mode,
struct mapped_device *md)
{
int r;
struct dm_dev *old_dev, *new_dev;
old_dev = dd->dm_dev;
r = dm_get_table_device(md, dd->dm_dev->bdev->bd_dev,
dd->dm_dev->mode | new_mode, &new_dev);
if (r)
{
return r;
}
dd->dm_dev = new_dev;
dm_put_table_device(md, old_dev);
return 0;
}
/*
* Convert the path to a device
*/
dev_t dm_get_dev_t(const char *path)
{
dev_t uninitialized_var(dev);
struct block_device *bdev;
bdev = lookup_bdev(path);
if (IS_ERR(bdev))
{
dev = name_to_dev_t(path);
}
else
{
dev = bdev->bd_dev;
bdput(bdev);
}
return dev;
}
EXPORT_SYMBOL_GPL(dm_get_dev_t);
/*
* Add a device to the list, or just increment the usage count if
* it's already present.
*/
int dm_get_device(struct dm_target *ti, const char *path, fmode_t mode,
struct dm_dev **result)
{
int r;
dev_t dev;
struct dm_dev_internal *dd;
struct dm_table *t = ti->table;
BUG_ON(!t);
dev = dm_get_dev_t(path);
if (!dev)
{
return -ENODEV;
}
dd = find_device(&t->devices, dev);
if (!dd)
{
dd = kmalloc(sizeof(*dd), GFP_KERNEL);
if (!dd)
{
return -ENOMEM;
}
if ((r = dm_get_table_device(t->md, dev, mode, &dd->dm_dev)))
{
kfree(dd);
return r;
}
atomic_set(&dd->count, 0);
list_add(&dd->list, &t->devices);
}
else if (dd->dm_dev->mode != (mode | dd->dm_dev->mode))
{
r = upgrade_mode(dd, mode, t->md);
if (r)
{
return r;
}
}
atomic_inc(&dd->count);
*result = dd->dm_dev;
return 0;
}
EXPORT_SYMBOL(dm_get_device);
static int dm_set_device_limits(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct queue_limits *limits = data;
struct block_device *bdev = dev->bdev;
struct request_queue *q = bdev_get_queue(bdev);
char b[BDEVNAME_SIZE];
if (unlikely(!q))
{
DMWARN("%s: Cannot set limits for nonexistent device %s",
dm_device_name(ti->table->md), bdevname(bdev, b));
return 0;
}
if (bdev_stack_limits(limits, bdev, start) < 0)
DMWARN("%s: adding target device %s caused an alignment inconsistency: "
"physical_block_size=%u, logical_block_size=%u, "
"alignment_offset=%u, start=%llu",
dm_device_name(ti->table->md), bdevname(bdev, b),
q->limits.physical_block_size,
q->limits.logical_block_size,
q->limits.alignment_offset,
(unsigned long long) start << SECTOR_SHIFT);
return 0;
}
/*
* Decrement a device's use count and remove it if necessary.
*/
void dm_put_device(struct dm_target *ti, struct dm_dev *d)
{
int found = 0;
struct list_head *devices = &ti->table->devices;
struct dm_dev_internal *dd;
list_for_each_entry(dd, devices, list)
{
if (dd->dm_dev == d)
{
found = 1;
break;
}
}
if (!found)
{
DMWARN("%s: device %s not in table devices list",
dm_device_name(ti->table->md), d->name);
return;
}
if (atomic_dec_and_test(&dd->count))
{
dm_put_table_device(ti->table->md, d);
list_del(&dd->list);
kfree(dd);
}
}
EXPORT_SYMBOL(dm_put_device);
/*
* Checks to see if the target joins onto the end of the table.
*/
static int adjoin(struct dm_table *table, struct dm_target *ti)
{
struct dm_target *prev;
if (!table->num_targets)
{
return !ti->begin;
}
prev = &table->targets[table->num_targets - 1];
return (ti->begin == (prev->begin + prev->len));
}
/*
* Used to dynamically allocate the arg array.
*
* We do first allocation with GFP_NOIO because dm-mpath and dm-thin must
* process messages even if some device is suspended. These messages have a
* small fixed number of arguments.
*
* On the other hand, dm-switch needs to process bulk data using messages and
* excessive use of GFP_NOIO could cause trouble.
*/
static char **realloc_argv(unsigned *array_size, char **old_argv)
{
char **argv;
unsigned new_size;
gfp_t gfp;
if (*array_size)
{
new_size = *array_size * 2;
gfp = GFP_KERNEL;
}
else
{
new_size = 8;
gfp = GFP_NOIO;
}
argv = kmalloc(new_size * sizeof(*argv), gfp);
if (argv)
{
memcpy(argv, old_argv, *array_size * sizeof(*argv));
*array_size = new_size;
}
kfree(old_argv);
return argv;
}
/*
* Destructively splits up the argument list to pass to ctr.
*/
int dm_split_args(int *argc, char ***argvp, char *input)
{
char *start, *end = input, *out, **argv = NULL;
unsigned array_size = 0;
*argc = 0;
if (!input)
{
*argvp = NULL;
return 0;
}
argv = realloc_argv(&array_size, argv);
if (!argv)
{
return -ENOMEM;
}
while (1)
{
/* Skip whitespace */
start = skip_spaces(end);
if (!*start)
{
break; /* success, we hit the end */
}
/* 'out' is used to remove any back-quotes */
end = out = start;
while (*end)
{
/* Everything apart from '\0' can be quoted */
if (*end == '\\' && *(end + 1))
{
*out++ = *(end + 1);
end += 2;
continue;
}
if (isspace(*end))
{
break; /* end of token */
}
*out++ = *end++;
}
/* have we already filled the array ? */
if ((*argc + 1) > array_size)
{
argv = realloc_argv(&array_size, argv);
if (!argv)
{
return -ENOMEM;
}
}
/* we know this is whitespace */
if (*end)
{
end++;
}
/* terminate the string and put it in the array */
*out = '\0';
argv[*argc] = start;
(*argc)++;
}
*argvp = argv;
return 0;
}
/*
* Impose necessary and sufficient conditions on a devices's table such
* that any incoming bio which respects its logical_block_size can be
* processed successfully. If it falls across the boundary between
* two or more targets, the size of each piece it gets split into must
* be compatible with the logical_block_size of the target processing it.
*/
static int validate_hardware_logical_block_alignment(struct dm_table *table,
struct queue_limits *limits)
{
/*
* This function uses arithmetic modulo the logical_block_size
* (in units of 512-byte sectors).
*/
unsigned short device_logical_block_size_sects =
limits->logical_block_size >> SECTOR_SHIFT;
/*
* Offset of the start of the next table entry, mod logical_block_size.
*/
unsigned short next_target_start = 0;
/*
* Given an aligned bio that extends beyond the end of a
* target, how many sectors must the next target handle?
*/
unsigned short remaining = 0;
struct dm_target *uninitialized_var(ti);
struct queue_limits ti_limits;
unsigned i = 0;
/*
* Check each entry in the table in turn.
*/
while (i < dm_table_get_num_targets(table))
{
ti = dm_table_get_target(table, i++);
blk_set_stacking_limits(&ti_limits);
/* combine all target devices' limits */
if (ti->type->iterate_devices)
ti->type->iterate_devices(ti, dm_set_device_limits,
&ti_limits);
/*
* If the remaining sectors fall entirely within this
* table entry are they compatible with its logical_block_size?
*/
if (remaining < ti->len &&
remaining & ((ti_limits.logical_block_size >>
SECTOR_SHIFT) - 1))
{
break; /* Error */
}
next_target_start =
(unsigned short) ((next_target_start + ti->len) &
(device_logical_block_size_sects - 1));
remaining = next_target_start ?
device_logical_block_size_sects - next_target_start : 0;
}
if (remaining)
{
DMWARN("%s: table line %u (start sect %llu len %llu) "
"not aligned to h/w logical block size %u",
dm_device_name(table->md), i,
(unsigned long long) ti->begin,
(unsigned long long) ti->len,
limits->logical_block_size);
return -EINVAL;
}
return 0;
}
int dm_table_add_target(struct dm_table *t, const char *type,
sector_t start, sector_t len, char *params)
{
int r = -EINVAL, argc;
char **argv;
struct dm_target *tgt;
if (t->singleton)
{
DMERR("%s: target type %s must appear alone in table",
dm_device_name(t->md), t->targets->type->name);
return -EINVAL;
}
BUG_ON(t->num_targets >= t->num_allocated);
tgt = t->targets + t->num_targets;
memset(tgt, 0, sizeof(*tgt));
if (!len)
{
DMERR("%s: zero-length target", dm_device_name(t->md));
return -EINVAL;
}
tgt->type = dm_get_target_type(type);
if (!tgt->type)
{
DMERR("%s: %s: unknown target type", dm_device_name(t->md), type);
return -EINVAL;
}
if (dm_target_needs_singleton(tgt->type))
{
if (t->num_targets)
{
tgt->error = "singleton target type must appear alone in table";
goto bad;
}
t->singleton = true;
}
if (dm_target_always_writeable(tgt->type) && !(t->mode & FMODE_WRITE))
{
tgt->error = "target type may not be included in a read-only table";
goto bad;
}
if (t->immutable_target_type)
{
if (t->immutable_target_type != tgt->type)
{
tgt->error = "immutable target type cannot be mixed with other target types";
goto bad;
}
}
else if (dm_target_is_immutable(tgt->type))
{
if (t->num_targets)
{
tgt->error = "immutable target type cannot be mixed with other target types";
goto bad;
}
t->immutable_target_type = tgt->type;
}
tgt->table = t;
tgt->begin = start;
tgt->len = len;
tgt->error = "Unknown error";
/*
* Does this target adjoin the previous one ?
*/
if (!adjoin(t, tgt))
{
tgt->error = "Gap in table";
goto bad;
}
r = dm_split_args(&argc, &argv, params);
if (r)
{
tgt->error = "couldn't split parameters (insufficient memory)";
goto bad;
}
r = tgt->type->ctr(tgt, argc, argv);
kfree(argv);
if (r)
{
goto bad;
}
t->highs[t->num_targets++] = tgt->begin + tgt->len - 1;
if (!tgt->num_discard_bios && tgt->discards_supported)
DMWARN("%s: %s: ignoring discards_supported because num_discard_bios is zero.",
dm_device_name(t->md), type);
return 0;
bad:
DMERR("%s: %s: %s", dm_device_name(t->md), type, tgt->error);
dm_put_target_type(tgt->type);
return r;
}
/*
* Target argument parsing helpers.
*/
static int validate_next_arg(struct dm_arg *arg, struct dm_arg_set *arg_set,
unsigned *value, char **error, unsigned grouped)
{
const char *arg_str = dm_shift_arg(arg_set);
char dummy;
if (!arg_str ||
(sscanf(arg_str, "%u%c", value, &dummy) != 1) ||
(*value < arg->min) ||
(*value > arg->max) ||
(grouped && arg_set->argc < *value))
{
*error = arg->error;
return -EINVAL;
}
return 0;
}
int dm_read_arg(struct dm_arg *arg, struct dm_arg_set *arg_set,
unsigned *value, char **error)
{
return validate_next_arg(arg, arg_set, value, error, 0);
}
EXPORT_SYMBOL(dm_read_arg);
int dm_read_arg_group(struct dm_arg *arg, struct dm_arg_set *arg_set,
unsigned *value, char **error)
{
return validate_next_arg(arg, arg_set, value, error, 1);
}
EXPORT_SYMBOL(dm_read_arg_group);
const char *dm_shift_arg(struct dm_arg_set *as)
{
char *r;
if (as->argc)
{
as->argc--;
r = *as->argv;
as->argv++;
return r;
}
return NULL;
}
EXPORT_SYMBOL(dm_shift_arg);
void dm_consume_args(struct dm_arg_set *as, unsigned num_args)
{
BUG_ON(as->argc < num_args);
as->argc -= num_args;
as->argv += num_args;
}
EXPORT_SYMBOL(dm_consume_args);
static bool __table_type_bio_based(unsigned table_type)
{
return (table_type == DM_TYPE_BIO_BASED ||
table_type == DM_TYPE_DAX_BIO_BASED);
}
static bool __table_type_request_based(unsigned table_type)
{
return (table_type == DM_TYPE_REQUEST_BASED ||
table_type == DM_TYPE_MQ_REQUEST_BASED);
}
void dm_table_set_type(struct dm_table *t, unsigned type)
{
t->type = type;
}
EXPORT_SYMBOL_GPL(dm_table_set_type);
static int device_supports_dax(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && blk_queue_dax(q);
}
static bool dm_table_supports_dax(struct dm_table *t)
{
struct dm_target *ti;
unsigned i = 0;
/* Ensure that all targets support DAX. */
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (!ti->type->direct_access)
{
return false;
}
if (!ti->type->iterate_devices ||
!ti->type->iterate_devices(ti, device_supports_dax, NULL))
{
return false;
}
}
return true;
}
static int dm_table_determine_type(struct dm_table *t)
{
unsigned i;
unsigned bio_based = 0, request_based = 0, hybrid = 0;
bool verify_blk_mq = false;
struct dm_target *tgt;
struct dm_dev_internal *dd;
struct list_head *devices = dm_table_get_devices(t);
unsigned live_md_type = dm_get_md_type(t->md);
if (t->type != DM_TYPE_NONE)
{
/* target already set the table's type */
if (t->type == DM_TYPE_BIO_BASED)
{
return 0;
}
BUG_ON(t->type == DM_TYPE_DAX_BIO_BASED);
goto verify_rq_based;
}
for (i = 0; i < t->num_targets; i++)
{
tgt = t->targets + i;
if (dm_target_hybrid(tgt))
{
hybrid = 1;
}
else if (dm_target_request_based(tgt))
{
request_based = 1;
}
else
{
bio_based = 1;
}
if (bio_based && request_based)
{
DMWARN("Inconsistent table: different target types"
" can't be mixed up");
return -EINVAL;
}
}
if (hybrid && !bio_based && !request_based)
{
/*
* The targets can work either way.
* Determine the type from the live device.
* Default to bio-based if device is new.
*/
if (__table_type_request_based(live_md_type))
{
request_based = 1;
}
else
{
bio_based = 1;
}
}
if (bio_based)
{
/* We must use this table as bio-based */
t->type = DM_TYPE_BIO_BASED;
if (dm_table_supports_dax(t) ||
(list_empty(devices) && live_md_type == DM_TYPE_DAX_BIO_BASED))
{
t->type = DM_TYPE_DAX_BIO_BASED;
}
return 0;
}
BUG_ON(!request_based); /* No targets in this table */
if (list_empty(devices) && __table_type_request_based(live_md_type))
{
/* inherit live MD type */
t->type = live_md_type;
return 0;
}
/*
* The only way to establish DM_TYPE_MQ_REQUEST_BASED is by
* having a compatible target use dm_table_set_type.
*/
t->type = DM_TYPE_REQUEST_BASED;
verify_rq_based:
/*
* Request-based dm supports only tables that have a single target now.
* To support multiple targets, request splitting support is needed,
* and that needs lots of changes in the block-layer.
* (e.g. request completion process for partial completion.)
*/
if (t->num_targets > 1)
{
DMWARN("Request-based dm doesn't support multiple targets yet");
return -EINVAL;
}
/* Non-request-stackable devices can't be used for request-based dm */
list_for_each_entry(dd, devices, list)
{
struct request_queue *q = bdev_get_queue(dd->dm_dev->bdev);
if (!blk_queue_stackable(q))
{
DMERR("table load rejected: including"
" non-request-stackable devices");
return -EINVAL;
}
if (q->mq_ops)
{
verify_blk_mq = true;
}
}
if (verify_blk_mq)
{
/* verify _all_ devices in the table are blk-mq devices */
list_for_each_entry(dd, devices, list)
if (!bdev_get_queue(dd->dm_dev->bdev)->mq_ops)
{
DMERR("table load rejected: not all devices"
" are blk-mq request-stackable");
return -EINVAL;
}
t->all_blk_mq = true;
}
return 0;
}
unsigned dm_table_get_type(struct dm_table *t)
{
return t->type;
}
struct target_type *dm_table_get_immutable_target_type(struct dm_table *t)
{
return t->immutable_target_type;
}
struct dm_target *dm_table_get_immutable_target(struct dm_table *t)
{
/* Immutable target is implicitly a singleton */
if (t->num_targets > 1 ||
!dm_target_is_immutable(t->targets[0].type))
{
return NULL;
}
return t->targets;
}
struct dm_target *dm_table_get_wildcard_target(struct dm_table *t)
{
struct dm_target *uninitialized_var(ti);
unsigned i = 0;
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (dm_target_is_wildcard(ti->type))
{
return ti;
}
}
return NULL;
}
bool dm_table_bio_based(struct dm_table *t)
{
return __table_type_bio_based(dm_table_get_type(t));
}
bool dm_table_request_based(struct dm_table *t)
{
return __table_type_request_based(dm_table_get_type(t));
}
bool dm_table_all_blk_mq_devices(struct dm_table *t)
{
return t->all_blk_mq;
}
static int dm_table_alloc_md_mempools(struct dm_table *t, struct mapped_device *md)
{
unsigned type = dm_table_get_type(t);
unsigned per_io_data_size = 0;
struct dm_target *tgt;
unsigned i;
if (unlikely(type == DM_TYPE_NONE))
{
DMWARN("no table type is set, can't allocate mempools");
return -EINVAL;
}
if (__table_type_bio_based(type))
for (i = 0; i < t->num_targets; i++)
{
tgt = t->targets + i;
per_io_data_size = max(per_io_data_size, tgt->per_io_data_size);
}
t->mempools = dm_alloc_md_mempools(md, type, t->integrity_supported, per_io_data_size);
if (!t->mempools)
{
return -ENOMEM;
}
return 0;
}
void dm_table_free_md_mempools(struct dm_table *t)
{
dm_free_md_mempools(t->mempools);
t->mempools = NULL;
}
struct dm_md_mempools *dm_table_get_md_mempools(struct dm_table *t)
{
return t->mempools;
}
static int setup_indexes(struct dm_table *t)
{
int i;
unsigned int total = 0;
sector_t *indexes;
/* allocate the space for *all* the indexes */
for (i = t->depth - 2; i >= 0; i--)
{
t->counts[i] = dm_div_up(t->counts[i + 1], CHILDREN_PER_NODE);
total += t->counts[i];
}
indexes = (sector_t *) dm_vcalloc(total, (unsigned long) NODE_SIZE);
if (!indexes)
{
return -ENOMEM;
}
/* set up internal nodes, bottom-up */
for (i = t->depth - 2; i >= 0; i--)
{
t->index[i] = indexes;
indexes += (KEYS_PER_NODE * t->counts[i]);
setup_btree_index(i, t);
}
return 0;
}
/*
* Builds the btree to index the map.
*/
static int dm_table_build_index(struct dm_table *t)
{
int r = 0;
unsigned int leaf_nodes;
/* how many indexes will the btree have ? */
leaf_nodes = dm_div_up(t->num_targets, KEYS_PER_NODE);
t->depth = 1 + int_log(leaf_nodes, CHILDREN_PER_NODE);
/* leaf layer has already been set up */
t->counts[t->depth - 1] = leaf_nodes;
t->index[t->depth - 1] = t->highs;
if (t->depth >= 2)
{
r = setup_indexes(t);
}
return r;
}
static bool integrity_profile_exists(struct gendisk *disk)
{
return !!blk_get_integrity(disk);
}
/*
* Get a disk whose integrity profile reflects the table's profile.
* Returns NULL if integrity support was inconsistent or unavailable.
*/
static struct gendisk *dm_table_get_integrity_disk(struct dm_table *t)
{
struct list_head *devices = dm_table_get_devices(t);
struct dm_dev_internal *dd = NULL;
struct gendisk *prev_disk = NULL, *template_disk = NULL;
list_for_each_entry(dd, devices, list)
{
template_disk = dd->dm_dev->bdev->bd_disk;
if (!integrity_profile_exists(template_disk))
{
goto no_integrity;
}
else if (prev_disk &&
blk_integrity_compare(prev_disk, template_disk) < 0)
{
goto no_integrity;
}
prev_disk = template_disk;
}
return template_disk;
no_integrity:
if (prev_disk)
DMWARN("%s: integrity not set: %s and %s profile mismatch",
dm_device_name(t->md),
prev_disk->disk_name,
template_disk->disk_name);
return NULL;
}
/*
* Register the mapped device for blk_integrity support if the
* underlying devices have an integrity profile. But all devices may
* not have matching profiles (checking all devices isn't reliable
* during table load because this table may use other DM device(s) which
* must be resumed before they will have an initialized integity
* profile). Consequently, stacked DM devices force a 2 stage integrity
* profile validation: First pass during table load, final pass during
* resume.
*/
static int dm_table_register_integrity(struct dm_table *t)
{
struct mapped_device *md = t->md;
struct gendisk *template_disk = NULL;
template_disk = dm_table_get_integrity_disk(t);
if (!template_disk)
{
return 0;
}
if (!integrity_profile_exists(dm_disk(md)))
{
t->integrity_supported = true;
/*
* Register integrity profile during table load; we can do
* this because the final profile must match during resume.
*/
blk_integrity_register(dm_disk(md),
blk_get_integrity(template_disk));
return 0;
}
/*
* If DM device already has an initialized integrity
* profile the new profile should not conflict.
*/
if (blk_integrity_compare(dm_disk(md), template_disk) < 0)
{
DMWARN("%s: conflict with existing integrity profile: "
"%s profile mismatch",
dm_device_name(t->md),
template_disk->disk_name);
return 1;
}
/* Preserve existing integrity profile */
t->integrity_supported = true;
return 0;
}
/*
* Prepares the table for use by building the indices,
* setting the type, and allocating mempools.
*/
int dm_table_complete(struct dm_table *t)
{
int r;
r = dm_table_determine_type(t);
if (r)
{
DMERR("unable to determine table type");
return r;
}
r = dm_table_build_index(t);
if (r)
{
DMERR("unable to build btrees");
return r;
}
r = dm_table_register_integrity(t);
if (r)
{
DMERR("could not register integrity profile.");
return r;
}
r = dm_table_alloc_md_mempools(t, t->md);
if (r)
{
DMERR("unable to allocate mempools");
}
return r;
}
static DEFINE_MUTEX(_event_lock);
void dm_table_event_callback(struct dm_table *t,
void (*fn)(void *), void *context)
{
mutex_lock(&_event_lock);
t->event_fn = fn;
t->event_context = context;
mutex_unlock(&_event_lock);
}
void dm_table_event(struct dm_table *t)
{
/*
* You can no longer call dm_table_event() from interrupt
* context, use a bottom half instead.
*/
BUG_ON(in_interrupt());
mutex_lock(&_event_lock);
if (t->event_fn)
{
t->event_fn(t->event_context);
}
mutex_unlock(&_event_lock);
}
EXPORT_SYMBOL(dm_table_event);
sector_t dm_table_get_size(struct dm_table *t)
{
return t->num_targets ? (t->highs[t->num_targets - 1] + 1) : 0;
}
EXPORT_SYMBOL(dm_table_get_size);
struct dm_target *dm_table_get_target(struct dm_table *t, unsigned int index)
{
if (index >= t->num_targets)
{
return NULL;
}
return t->targets + index;
}
/*
* Search the btree for the correct target.
*
* Caller should check returned pointer with dm_target_is_valid()
* to trap I/O beyond end of device.
*/
struct dm_target *dm_table_find_target(struct dm_table *t, sector_t sector)
{
unsigned int l, n = 0, k = 0;
sector_t *node;
for (l = 0; l < t->depth; l++)
{
n = get_child(n, k);
node = get_node(t, l, n);
for (k = 0; k < KEYS_PER_NODE; k++)
if (node[k] >= sector)
{
break;
}
}
return &t->targets[(KEYS_PER_NODE * n) + k];
}
static int count_device(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
unsigned *num_devices = data;
(*num_devices)++;
return 0;
}
/*
* Check whether a table has no data devices attached using each
* target's iterate_devices method.
* Returns false if the result is unknown because a target doesn't
* support iterate_devices.
*/
bool dm_table_has_no_data_devices(struct dm_table *table)
{
struct dm_target *uninitialized_var(ti);
unsigned i = 0, num_devices = 0;
while (i < dm_table_get_num_targets(table))
{
ti = dm_table_get_target(table, i++);
if (!ti->type->iterate_devices)
{
return false;
}
ti->type->iterate_devices(ti, count_device, &num_devices);
if (num_devices)
{
return false;
}
}
return true;
}
/*
* Establish the new table's queue_limits and validate them.
*/
int dm_calculate_queue_limits(struct dm_table *table,
struct queue_limits *limits)
{
struct dm_target *uninitialized_var(ti);
struct queue_limits ti_limits;
unsigned i = 0;
blk_set_stacking_limits(limits);
while (i < dm_table_get_num_targets(table))
{
blk_set_stacking_limits(&ti_limits);
ti = dm_table_get_target(table, i++);
if (!ti->type->iterate_devices)
{
goto combine_limits;
}
/*
* Combine queue limits of all the devices this target uses.
*/
ti->type->iterate_devices(ti, dm_set_device_limits,
&ti_limits);
/* Set I/O hints portion of queue limits */
if (ti->type->io_hints)
{
ti->type->io_hints(ti, &ti_limits);
}
/*
* Check each device area is consistent with the target's
* overall queue limits.
*/
if (ti->type->iterate_devices(ti, device_area_is_invalid,
&ti_limits))
{
return -EINVAL;
}
combine_limits:
/*
* Merge this target's queue limits into the overall limits
* for the table.
*/
if (blk_stack_limits(limits, &ti_limits, 0) < 0)
DMWARN("%s: adding target device "
"(start sect %llu len %llu) "
"caused an alignment inconsistency",
dm_device_name(table->md),
(unsigned long long) ti->begin,
(unsigned long long) ti->len);
}
return validate_hardware_logical_block_alignment(table, limits);
}
/*
* Verify that all devices have an integrity profile that matches the
* DM device's registered integrity profile. If the profiles don't
* match then unregister the DM device's integrity profile.
*/
static void dm_table_verify_integrity(struct dm_table *t)
{
struct gendisk *template_disk = NULL;
if (t->integrity_supported)
{
/*
* Verify that the original integrity profile
* matches all the devices in this table.
*/
template_disk = dm_table_get_integrity_disk(t);
if (template_disk &&
blk_integrity_compare(dm_disk(t->md), template_disk) >= 0)
{
return;
}
}
if (integrity_profile_exists(dm_disk(t->md)))
{
DMWARN("%s: unable to establish an integrity profile",
dm_device_name(t->md));
blk_integrity_unregister(dm_disk(t->md));
}
}
static int device_flush_capable(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
unsigned long flush = (unsigned long) data;
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && (q->queue_flags & flush);
}
static bool dm_table_supports_flush(struct dm_table *t, unsigned long flush)
{
struct dm_target *ti;
unsigned i = 0;
/*
* Require at least one underlying device to support flushes.
* t->devices includes internal dm devices such as mirror logs
* so we need to use iterate_devices here, which targets
* supporting flushes must provide.
*/
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (!ti->num_flush_bios)
{
continue;
}
if (ti->flush_supported)
{
return true;
}
if (ti->type->iterate_devices &&
ti->type->iterate_devices(ti, device_flush_capable, (void *) flush))
{
return true;
}
}
return false;
}
static bool dm_table_discard_zeroes_data(struct dm_table *t)
{
struct dm_target *ti;
unsigned i = 0;
/* Ensure that all targets supports discard_zeroes_data. */
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (ti->discard_zeroes_data_unsupported)
{
return false;
}
}
return true;
}
static int device_is_nonrot(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && blk_queue_nonrot(q);
}
static int device_is_not_random(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && !blk_queue_add_random(q);
}
static int queue_supports_sg_merge(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && !test_bit(QUEUE_FLAG_NO_SG_MERGE, &q->queue_flags);
}
static bool dm_table_all_devices_attribute(struct dm_table *t,
iterate_devices_callout_fn func)
{
struct dm_target *ti;
unsigned i = 0;
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (!ti->type->iterate_devices ||
!ti->type->iterate_devices(ti, func, NULL))
{
return false;
}
}
return true;
}
static int device_not_write_same_capable(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && !q->limits.max_write_same_sectors;
}
static bool dm_table_supports_write_same(struct dm_table *t)
{
struct dm_target *ti;
unsigned i = 0;
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (!ti->num_write_same_bios)
{
return false;
}
if (!ti->type->iterate_devices ||
ti->type->iterate_devices(ti, device_not_write_same_capable, NULL))
{
return false;
}
}
return true;
}
static int device_discard_capable(struct dm_target *ti, struct dm_dev *dev,
sector_t start, sector_t len, void *data)
{
struct request_queue *q = bdev_get_queue(dev->bdev);
return q && blk_queue_discard(q);
}
static bool dm_table_supports_discards(struct dm_table *t)
{
struct dm_target *ti;
unsigned i = 0;
/*
* Unless any target used by the table set discards_supported,
* require at least one underlying device to support discards.
* t->devices includes internal dm devices such as mirror logs
* so we need to use iterate_devices here, which targets
* supporting discard selectively must provide.
*/
while (i < dm_table_get_num_targets(t))
{
ti = dm_table_get_target(t, i++);
if (!ti->num_discard_bios)
{
continue;
}
if (ti->discards_supported)
{
return true;
}
if (ti->type->iterate_devices &&
ti->type->iterate_devices(ti, device_discard_capable, NULL))
{
return true;
}
}
return false;
}
void dm_table_set_restrictions(struct dm_table *t, struct request_queue *q,
struct queue_limits *limits)
{
bool wc = false, fua = false;
/*
* Copy table's limits to the DM device's request_queue
*/
q->limits = *limits;
if (!dm_table_supports_discards(t))
{
queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, q);
}
else
{
queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, q);
}
if (dm_table_supports_flush(t, (1UL << QUEUE_FLAG_WC)))
{
wc = true;
if (dm_table_supports_flush(t, (1UL << QUEUE_FLAG_FUA)))
{
fua = true;
}
}
blk_queue_write_cache(q, wc, fua);
if (!dm_table_discard_zeroes_data(t))
{
q->limits.discard_zeroes_data = 0;
}
/* Ensure that all underlying devices are non-rotational. */
if (dm_table_all_devices_attribute(t, device_is_nonrot))
{
queue_flag_set_unlocked(QUEUE_FLAG_NONROT, q);
}
else
{
queue_flag_clear_unlocked(QUEUE_FLAG_NONROT, q);
}
if (!dm_table_supports_write_same(t))
{
q->limits.max_write_same_sectors = 0;
}
if (dm_table_all_devices_attribute(t, queue_supports_sg_merge))
{
queue_flag_clear_unlocked(QUEUE_FLAG_NO_SG_MERGE, q);
}
else
{
queue_flag_set_unlocked(QUEUE_FLAG_NO_SG_MERGE, q);
}
dm_table_verify_integrity(t);
/*
* Determine whether or not this queue's I/O timings contribute
* to the entropy pool, Only request-based targets use this.
* Clear QUEUE_FLAG_ADD_RANDOM if any underlying device does not
* have it set.
*/
if (blk_queue_add_random(q) && dm_table_all_devices_attribute(t, device_is_not_random))
{
queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, q);
}
/*
* QUEUE_FLAG_STACKABLE must be set after all queue settings are
* visible to other CPUs because, once the flag is set, incoming bios
* are processed by request-based dm, which refers to the queue
* settings.
* Until the flag set, bios are passed to bio-based dm and queued to
* md->deferred where queue settings are not needed yet.
* Those bios are passed to request-based dm at the resume time.
*/
smp_mb();
if (dm_table_request_based(t))
{
queue_flag_set_unlocked(QUEUE_FLAG_STACKABLE, q);
}
}
unsigned int dm_table_get_num_targets(struct dm_table *t)
{
return t->num_targets;
}
struct list_head *dm_table_get_devices(struct dm_table *t)
{
return &t->devices;
}
fmode_t dm_table_get_mode(struct dm_table *t)
{
return t->mode;
}
EXPORT_SYMBOL(dm_table_get_mode);
enum suspend_mode
{
PRESUSPEND,
PRESUSPEND_UNDO,
POSTSUSPEND,
};
static void suspend_targets(struct dm_table *t, enum suspend_mode mode)
{
int i = t->num_targets;
struct dm_target *ti = t->targets;
while (i--)
{
switch (mode)
{
case PRESUSPEND:
if (ti->type->presuspend)
{
ti->type->presuspend(ti);
}
break;
case PRESUSPEND_UNDO:
if (ti->type->presuspend_undo)
{
ti->type->presuspend_undo(ti);
}
break;
case POSTSUSPEND:
if (ti->type->postsuspend)
{
ti->type->postsuspend(ti);
}
break;
}
ti++;
}
}
void dm_table_presuspend_targets(struct dm_table *t)
{
if (!t)
{
return;
}
suspend_targets(t, PRESUSPEND);
}
void dm_table_presuspend_undo_targets(struct dm_table *t)
{
if (!t)
{
return;
}
suspend_targets(t, PRESUSPEND_UNDO);
}
void dm_table_postsuspend_targets(struct dm_table *t)
{
if (!t)
{
return;
}
suspend_targets(t, POSTSUSPEND);
}
int dm_table_resume_targets(struct dm_table *t)
{
int i, r = 0;
for (i = 0; i < t->num_targets; i++)
{
struct dm_target *ti = t->targets + i;
if (!ti->type->preresume)
{
continue;
}
r = ti->type->preresume(ti);
if (r)
{
DMERR("%s: %s: preresume failed, error = %d",
dm_device_name(t->md), ti->type->name, r);
return r;
}
}
for (i = 0; i < t->num_targets; i++)
{
struct dm_target *ti = t->targets + i;
if (ti->type->resume)
{
ti->type->resume(ti);
}
}
return 0;
}
void dm_table_add_target_callbacks(struct dm_table *t, struct dm_target_callbacks *cb)
{
list_add(&cb->list, &t->target_callbacks);
}
EXPORT_SYMBOL_GPL(dm_table_add_target_callbacks);
int dm_table_any_congested(struct dm_table *t, int bdi_bits)
{
struct dm_dev_internal *dd;
struct list_head *devices = dm_table_get_devices(t);
struct dm_target_callbacks *cb;
int r = 0;
list_for_each_entry(dd, devices, list)
{
struct request_queue *q = bdev_get_queue(dd->dm_dev->bdev);
char b[BDEVNAME_SIZE];
if (likely(q))
{
r |= bdi_congested(&q->backing_dev_info, bdi_bits);
}
else
DMWARN_LIMIT("%s: any_congested: nonexistent device %s",
dm_device_name(t->md),
bdevname(dd->dm_dev->bdev, b));
}
list_for_each_entry(cb, &t->target_callbacks, list)
if (cb->congested_fn)
{
r |= cb->congested_fn(cb, bdi_bits);
}
return r;
}
struct mapped_device *dm_table_get_md(struct dm_table *t)
{
return t->md;
}
EXPORT_SYMBOL(dm_table_get_md);
void dm_table_run_md_queue_async(struct dm_table *t)
{
struct mapped_device *md;
struct request_queue *queue;
unsigned long flags;
if (!dm_table_request_based(t))
{
return;
}
md = dm_table_get_md(t);
queue = dm_get_md_queue(md);
if (queue)
{
if (queue->mq_ops)
{
blk_mq_run_hw_queues(queue, true);
}
else
{
spin_lock_irqsave(queue->queue_lock, flags);
blk_run_queue_async(queue);
spin_unlock_irqrestore(queue->queue_lock, flags);
}
}
}
EXPORT_SYMBOL(dm_table_run_md_queue_async);
|
williamfdevine/PrettyLinux
|
drivers/md/dm-table.c
|
C
|
gpl-3.0
| 42,470
|
#ifndef DISPLAYGLWIDGET_H
#define DISPLAYGLWIDGET_H
#include <QGLWidget>
#include <QtOpenGL>
#include <GL/glu.h>
class DisplayGLWidget : public QGLWidget
{
Q_OBJECT
public:
explicit DisplayGLWidget(QWidget *parent = 0);
void setPitchAngle(float angle);
void setRollAngle(float angle);
void setYawAngle(float angle);
private:
float pitchAngle;
float rollAngle;
float yawAngle;
QColor qtRed;
QColor qtGray;
signals:
public slots:
protected:
void initializeGL();
void paintGL();
void resizeGL(int width, int height);
};
#endif // DISPLAYGLWIDGET_H
|
victorcrimea/Q1_Control_Panel
|
displayglwidget.h
|
C
|
gpl-3.0
| 573
|
<?php
/**
* @package HikaShop for Joomla!
* @version 2.5.0
* @author hikashop.com
* @copyright (C) 2010-2015 HIKARI SOFTWARE. All rights reserved.
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
defined('_JEXEC') or die('Restricted access');
?><fieldset>
<div class="toolbar" id="toolbar" style="float: right;">
<button class="btn" type="button" onclick="submitbutton('savechild');"><img src="<?php echo HIKASHOP_IMAGES; ?>save.png"/><?php echo JText::_('HIKA_SAVE'); ?></button>
<button class="btn" type="button" onclick="submitbutton('selectchildlisting');"><img src="<?php echo HIKASHOP_IMAGES; ?>cancel.png"/><?php echo JText::_('HIKA_CANCEL'); ?></button>
</div>
</fieldset>
<div class="iframedoc" id="iframedoc"></div>
<form action="index.php?option=<?php echo HIKASHOP_COMPONENT ?>&ctrl=zone&tmpl=component" method="post" name="adminForm" id="adminForm" enctype="multipart/form-data">
<?php
$this->setLayout('information');
echo $this->loadTemplate();
?>
<div class="clr"></div>
<input type="hidden" name="cid[]" value="0" />
<input type="hidden" name="option" value="<?php echo HIKASHOP_COMPONENT; ?>" />
<input type="hidden" name="main_namekey" value="<?php echo JRequest::getCmd('main_namekey'); ?>" />
<input type="hidden" name="main_id" value="<?php echo JRequest::getInt('main_id'); ?>" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="ctrl" value="zone" />
<?php echo JHTML::_( 'form.token' ); ?>
</form>
|
vaibhav1607/com_hikashop_starter_v2.5.0_2015-08-06_18-17-26
|
back/views/zone/tmpl/newchildform.php
|
PHP
|
gpl-3.0
| 1,495
|
require 'package'
class Wdiff < Package
description 'The GNU wdiff program is a front end to diff for comparing files on a word per word basis.'
homepage 'https://www.gnu.org/software/wdiff/'
version '1.2.2'
license 'GPL-3'
compatibility 'all'
source_url 'https://ftpmirror.gnu.org/wdiff/wdiff-1.2.2.tar.gz'
source_sha256 '34ff698c870c87e6e47a838eeaaae729fa73349139fc8db12211d2a22b78af6b'
binary_url ({
aarch64: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/wdiff/1.2.2_armv7l/wdiff-1.2.2-chromeos-armv7l.tar.xz',
armv7l: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/wdiff/1.2.2_armv7l/wdiff-1.2.2-chromeos-armv7l.tar.xz',
i686: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/wdiff/1.2.2_i686/wdiff-1.2.2-chromeos-i686.tar.xz',
x86_64: 'https://gitlab.com/api/v4/projects/26210301/packages/generic/wdiff/1.2.2_x86_64/wdiff-1.2.2-chromeos-x86_64.tar.xz',
})
binary_sha256 ({
aarch64: 'e27cdc3a13508098ddb9e330758896596af712fb33ac4f6c5c17c1b41624ffa1',
armv7l: 'e27cdc3a13508098ddb9e330758896596af712fb33ac4f6c5c17c1b41624ffa1',
i686: '0e6c8306a0fe4ddff4b03ee541f1ffbaa92af829dac9d9681af9e6e6e381952a',
x86_64: '091e34045534f4f777172e1f4a3c9e966377efa9158304f1bb15f31a3edc2dac',
})
def self.build
system "./configure --prefix=#{CREW_PREFIX}"
system 'make'
end
def self.install
system 'make', "DESTDIR=#{CREW_DEST_DIR}", 'install'
end
def self.check
system "make", "check"
end
end
|
skycocker/chromebrew
|
packages/wdiff.rb
|
Ruby
|
gpl-3.0
| 1,523
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Purchasing module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL3-COMM$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPLv3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qwinrtinapppurchasebackend_p.h"
#include "qwinrtinappproduct_p.h"
#include "qwinrtinapptransaction_p.h"
#include "qinappstore.h"
#include <QLoggingCategory>
#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QFile>
#include <QtCore/QStandardPaths>
#include <QtCore/QXmlStreamReader>
#include <private/qeventdispatcher_winrt_p.h>
#include <qfunctions_winrt.h>
#include <functional>
#include <Windows.ApplicationModel.store.h>
#include <Windows.Applicationmodel.Activation.h>
#include <wrl.h>
using namespace ABI::Windows::ApplicationModel::Store;
using namespace ABI::Windows::Foundation;
using namespace ABI::Windows::Foundation::Collections;
using namespace ABI::Windows::Storage;
using namespace Microsoft::WRL;
using namespace Microsoft::WRL::Wrappers;
typedef IAsyncOperationCompletedHandler<ListingInformation *> ListingInformationHandler;
QT_BEGIN_NAMESPACE
Q_LOGGING_CATEGORY(lcPurchasingBackend, "qt.purchasing.backend")
const QString qt_win_app_identifier = QLatin1String("app");
inline QString hStringToQString(const HString &h)
{
unsigned int length;
const wchar_t* raw = h.GetRawBuffer(&length);
return QString::fromWCharArray(raw, length);
}
class QWinRTAppBridge {
public:
HRESULT activate();
HRESULT LoadListingInformationAsync(ComPtr<IAsyncOperation<ListingInformation *>> &op);
HRESULT GetAppReceiptAsync(ComPtr<IAsyncOperation<HSTRING>> &op);
HRESULT GetProductReceiptAsync(HSTRING product, ComPtr<IAsyncOperation<HSTRING>> &op);
HRESULT RequestAppPurchaseAsync(bool receipt, ComPtr<IAsyncOperation<HSTRING>> &op);
HRESULT RequestProductPurchaseAsync(HSTRING productId, bool receipt, ComPtr<IAsyncOperation<HSTRING>> &op);
HRESULT RequestProductPurchaseWithResultsAsync(HSTRING productId, ComPtr<IAsyncOperation<PurchaseResults *>> &purchaseOp);
HRESULT ReportConsumableFulfillmentAsync(HSTRING productId, GUID transactionId, ComPtr<IAsyncOperation<FulfillmentResult>> &op);
HRESULT get_LicenseInformation(ComPtr<ILicenseInformation> &licenseInfo);
private:
HRESULT qt_winrt_load_simulator_config(const QString &fileName, ComPtr<ICurrentAppSimulator> &simulator);
ComPtr<ICurrentAppSimulator> m_simulator;
ComPtr<ICurrentApp> m_app;
bool m_simulate{false};
};
HRESULT QWinRTAppBridge::activate()
{
HRESULT hr;
const QString storeFilename = QLatin1String("QtStoreSimulation.xml");
const QString dataPath = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + QLatin1Char('/');
const QString storeSourceName = QLatin1String(":/") + storeFilename;
const QString storeTargetName = dataPath + storeFilename;
if (QFileInfo::exists(storeSourceName)) {
qWarning("Found purchasing simulation file, disabling store connectivity.\n"
"Please note you will not be able to publish this package.");
bool success = true;
if (QFileInfo(storeTargetName).exists())
success = QFile(storeTargetName).remove();
if (!success)
qWarning("Could not remove previous purchasing simulation file.");
success = QFile(storeSourceName).copy(storeTargetName);
if (!success)
qWarning("Could not copy purchasing simulation file.");
success = QFile::setPermissions(storeTargetName,
QFile::WriteOwner | QFile::ReadOwner | QFile::WriteUser | QFile::ReadUser);
if (!success)
qWarning("Could not set readwrite flags for purchasing simulation file");
m_simulate = true;
}
if (m_simulate) {
hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Store_CurrentAppSimulator).Get(),
IID_PPV_ARGS(&m_simulator));
qt_winrt_load_simulator_config(storeTargetName, m_simulator);
} else {
hr = RoGetActivationFactory(HString::MakeReference(RuntimeClass_Windows_ApplicationModel_Store_CurrentApp).Get(),
IID_PPV_ARGS(&m_app));
}
return hr;
}
HRESULT QWinRTAppBridge::LoadListingInformationAsync(ComPtr<IAsyncOperation<ListingInformation *> > &op)
{
HRESULT hr;
if (m_simulate)
hr = m_simulator->LoadListingInformationAsync(&op);
else
hr = m_app->LoadListingInformationAsync(&op);
return hr;
}
HRESULT QWinRTAppBridge::GetAppReceiptAsync(ComPtr<IAsyncOperation<HSTRING> > &op)
{
HRESULT hr;
if (m_simulate)
hr = m_simulator->GetAppReceiptAsync(&op);
else
hr = m_app->GetAppReceiptAsync(&op);
return hr;
}
HRESULT QWinRTAppBridge::GetProductReceiptAsync(HSTRING product, ComPtr<IAsyncOperation<HSTRING> > &op)
{
HRESULT hr;
if (m_simulate)
hr = m_simulator->GetProductReceiptAsync(product, &op);
else
hr = m_app->GetProductReceiptAsync(product, &op);
return hr;
}
HRESULT QWinRTAppBridge::RequestAppPurchaseAsync(bool receipt, ComPtr<IAsyncOperation<HSTRING> > &op)
{
HRESULT hr;
if (m_simulate)
hr = m_simulator->RequestAppPurchaseAsync(receipt, op.GetAddressOf());
else
hr = m_app->RequestAppPurchaseAsync(receipt, op.GetAddressOf());
return hr;
}
HRESULT QWinRTAppBridge::RequestProductPurchaseAsync(HSTRING productId, bool receipt, ComPtr<IAsyncOperation<HSTRING> > &op)
{
HRESULT hr;
if (m_simulate)
hr = m_simulator->RequestProductPurchaseAsync(productId, receipt, op.GetAddressOf());
else
hr = m_app->RequestProductPurchaseAsync(productId, receipt, op.GetAddressOf());
return hr;
}
HRESULT QWinRTAppBridge::RequestProductPurchaseWithResultsAsync(HSTRING productId, ComPtr<IAsyncOperation<PurchaseResults *> > &purchaseOp)
{
HRESULT hr;
if (m_simulate) {
ComPtr<ICurrentAppSimulatorWithConsumables> consumApp;
hr = m_simulator.As(&consumApp);
Q_ASSERT_SUCCEEDED(hr);
hr = consumApp->RequestProductPurchaseWithResultsAsync(productId, purchaseOp.GetAddressOf());
} else {
ComPtr<ICurrentAppWithConsumables> consumApp;
hr = m_app.As(&consumApp);
Q_ASSERT_SUCCEEDED(hr);
hr = consumApp->RequestProductPurchaseWithResultsAsync(productId, purchaseOp.GetAddressOf());
}
return hr;
}
HRESULT QWinRTAppBridge::ReportConsumableFulfillmentAsync(HSTRING productId, GUID transactionId, ComPtr<IAsyncOperation<FulfillmentResult> > &op)
{
HRESULT hr;
if (m_simulate) {
ComPtr<ICurrentAppSimulatorWithConsumables> consumApp;
hr = m_simulator.As(&consumApp);
Q_ASSERT_SUCCEEDED(hr);
hr = consumApp->ReportConsumableFulfillmentAsync(productId, transactionId, op.GetAddressOf());
} else {
ComPtr<ICurrentAppWithConsumables> consumApp;
hr = m_app.As(&consumApp);
Q_ASSERT_SUCCEEDED(hr);
hr = consumApp->ReportConsumableFulfillmentAsync(productId, transactionId, op.GetAddressOf());
}
return hr;
}
HRESULT QWinRTAppBridge::get_LicenseInformation(ComPtr<ILicenseInformation> &licenseInfo)
{
HRESULT hr;
if (m_simulate) {
hr = m_simulator->get_LicenseInformation(&licenseInfo);
} else {
hr = m_app->get_LicenseInformation(&licenseInfo);
}
return hr;
}
HRESULT QWinRTAppBridge::qt_winrt_load_simulator_config(const QString &fileName, ComPtr<ICurrentAppSimulator> &simulator)
{
qCDebug(lcPurchasingBackend) << __FUNCTION__ << fileName;
HRESULT hr;
const QString nativeFilename = QDir::toNativeSeparators(fileName);
HString nativeName;
hr = nativeName.Set(reinterpret_cast<PCWSTR>(nativeFilename.utf16()), nativeFilename.size());
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IStorageFileStatics> fileStatics;
hr = GetActivationFactory(HString::MakeReference(RuntimeClass_Windows_Storage_StorageFile).Get(), &fileStatics);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncOperation<StorageFile*>> op;
hr = fileStatics->GetFileFromPathAsync(nativeName.Get(), &op);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IStorageFile> storeFile;
hr = QWinRTFunctions::await(op, storeFile.GetAddressOf());
RETURN_HR_IF_FAILED("Could not find purchasing simulator xml description.");
ComPtr<ABI::Windows::Foundation::IAsyncAction> reloadAction;
hr = simulator->ReloadSimulatorAsync(storeFile.Get(), &reloadAction);
Q_ASSERT_SUCCEEDED(hr);
hr = QWinRTFunctions::await(reloadAction, QWinRTFunctions::YieldThread);
RETURN_HR_IF_FAILED("Failed to load purchasing description.");
return hr;
}
struct NativeProductInfo
{
NativeProductInfo() { }
HString productID;
HString formatPrice;
HString productName;
ProductType type;
};
inline bool compareProductTypes(QInAppProduct::ProductType qtType, ProductType nativeType) {
if (qtType == QInAppProduct::Consumable && nativeType == ProductType_Consumable)
return true;
else if (qtType == QInAppProduct::Unlockable && nativeType == ProductType_Durable)
return true;
else
return false;
}
void QWinRTInAppPurchaseBackend::createTransactionDelayed(qt_WinRTTransactionData data)
{
QInAppTransaction::TransactionStatus qStatus = (data.status == AsyncStatus::Completed) ?
QInAppTransaction::PurchaseApproved : QInAppTransaction::PurchaseFailed;
QInAppTransaction::FailureReason reason;
switch (data.status) {
case AsyncStatus::Completed: {
reason = QInAppTransaction::NoFailure;
ProductPurchaseStatus purchaseStatus;
HRESULT hr = data.purchaseResults->get_Status(&purchaseStatus);
if (FAILED(hr)) {
qWarning("Could not query purchase status for transaction.");
break;
}
switch (purchaseStatus) {
case ProductPurchaseStatus_Succeeded:
reason = QInAppTransaction::NoFailure;
break;
case ProductPurchaseStatus_NotFulfilled:
case ProductPurchaseStatus_NotPurchased:
reason = QInAppTransaction::CanceledByUser;
qStatus = QInAppTransaction::PurchaseFailed;
break;
case ProductPurchaseStatus_AlreadyPurchased:
default:
reason = QInAppTransaction::ErrorOccurred;
qStatus = QInAppTransaction::PurchaseFailed;
break;
}
break;
}
case AsyncStatus::Canceled:
reason = QInAppTransaction::CanceledByUser;
break;
case AsyncStatus::Error:
default:
reason = QInAppTransaction::ErrorOccurred;
break;
}
auto transaction = new QWinRTInAppTransaction(qStatus, data.product, reason, data.receipt, this);
transaction->m_purchaseResults = data.purchaseResults;
qCDebug(lcPurchasingBackend) << "Emitting Transaction:" << qStatus << "/"
<< reason << " Receipt:" << data.receipt;
emit transactionReady(transaction);
return;
}
class QWinRTInAppPurchaseBackendPrivate
{
public:
explicit QWinRTInAppPurchaseBackendPrivate(QWinRTInAppPurchaseBackend *p)
: q_ptr(p)
{ }
HRESULT onListingInformation(IAsyncOperation<ListingInformation*> *args,
AsyncStatus status);
ComPtr<IProductLicense> findProductLicense(const QString &identifier);
QWinRTAppBridge m_bridge;
bool m_waitingForList = false;
QMap<QString, NativeProductInfo*> nativeProducts;
QWinRTInAppPurchaseBackend *q_ptr;
Q_DECLARE_PUBLIC(QWinRTInAppPurchaseBackend)
};
QWinRTInAppPurchaseBackend::QWinRTInAppPurchaseBackend(QObject *parent)
: QInAppPurchaseBackend(parent)
{
d_ptr.reset(new QWinRTInAppPurchaseBackendPrivate(this));
qRegisterMetaType<qt_WinRTTransactionData>("qt_WinRTTransactionData");
qCDebug(lcPurchasingBackend) << __FUNCTION__;
}
void QWinRTInAppPurchaseBackend::initialize()
{
Q_D(QWinRTInAppPurchaseBackend);
qCDebug(lcPurchasingBackend) << __FUNCTION__;
HRESULT hr;
hr = QEventDispatcherWinRT::runOnXamlThread([d]() {
HRESULT hr;
hr = d->m_bridge.activate();
Q_ASSERT_SUCCEEDED(hr);
// ### Keep for later usage.
// ComPtr<ILicenseInformation> licenseInfo;
// hr = d->m_bridge.get_LicenseInformation(licenseInfo);
// RETURN_HR_IF_FAILED("Could not acquire license information.");
ComPtr<IAsyncOperation<ListingInformation*>> op;
hr = d->m_bridge.LoadListingInformationAsync(op);
RETURN_HR_IF_FAILED("Purchasing: Could not load listing information.");
hr = op->put_Completed(Callback<ListingInformationHandler>(d, &QWinRTInAppPurchaseBackendPrivate::onListingInformation).Get());
Q_ASSERT_SUCCEEDED(hr);
d->m_waitingForList = true;
return S_OK;
});
RETURN_VOID_IF_FAILED("Could not initialize purchase backend");
}
bool QWinRTInAppPurchaseBackend::isReady() const
{
Q_D(const QWinRTInAppPurchaseBackend);
qCDebug(lcPurchasingBackend) << __FUNCTION__;
return !d->m_waitingForList && !d->nativeProducts.isEmpty();
}
inline QString createStringForSubReceipt(const QXmlStreamReader &reader)
{
QString result;
QXmlStreamWriter writer(&result);
writer.writeStartDocument();
writer.writeCurrentToken(reader);
writer.writeEndDocument();
return result;
}
void QWinRTInAppPurchaseBackend::restorePurchases()
{
qCDebug(lcPurchasingBackend) << __FUNCTION__;
Q_D(QWinRTInAppPurchaseBackend);
HRESULT hr;
ComPtr<IAsyncOperation<HSTRING>> op;
hr = d->m_bridge.GetAppReceiptAsync(op);
if (FAILED(hr)) {
qCDebug(lcPurchasingBackend) << "Failed to query receipts";
return;
}
HString receipt;
hr = QWinRTFunctions::await(op, receipt.GetAddressOf());
if (FAILED(hr)) {
qCDebug(lcPurchasingBackend) << "Could not wait for app receipt query";
return;
}
const QString parse = hStringToQString(receipt);
qCDebug(lcPurchasingBackend) << "Receipt:" << parse;
QXmlStreamReader reader(parse);
while (reader.readNextStartElement()) {
if (reader.name() == QLatin1String("Receipt"))
break;
}
if (reader.name() != QLatin1String("Receipt")) {
qCDebug(lcPurchasingBackend) << "Could not parse app receipt xml";
return;
}
reader.readNextStartElement();
if (reader.name() != QLatin1String("AppReceipt")) {
qCDebug(lcPurchasingBackend) << "Expected AppReceipt in receipt, got:" << reader.name();
return;
}
const QString appReceipt = createStringForSubReceipt(reader);
while (!reader.atEnd()) {
reader.readNext();
if (reader.attributes().hasAttribute(QLatin1String("ProductId"))) {
const QString id = reader.attributes().value(QLatin1String("ProductId")).toString();
qCDebug(lcPurchasingBackend) << " Found Product " << id << "to restore";
if (d->nativeProducts.contains(id)) {
qCDebug(lcPurchasingBackend) << "Restoring:" << id;
QUuid uuid(reader.attributes().value(QLatin1String("Id")).toString());
if (uuid.isNull()) {
qCDebug(lcPurchasingBackend) << "Product " << id << " restoration failed due to "
<< "no transaction id";
continue;
}
QInAppProduct *product = store()->registeredProduct(id);
if (!product) {
qCDebug(lcPurchasingBackend) << "Product " << id << "has been bought, but is unknown";
continue;
}
const QString receipt = createStringForSubReceipt(reader);
auto transaction = new QWinRTInAppTransaction(QInAppTransaction::PurchaseRestored,
product,
QInAppTransaction::NoFailure,
receipt,
this);
transaction->m_uuid = uuid;
emit transactionReady(transaction);
}
}
}
ComPtr<ILicenseInformation> appLicense;
hr = d->m_bridge.get_LicenseInformation(appLicense);
Q_ASSERT_SUCCEEDED(hr);
boolean active;
hr = appLicense->get_IsActive(&active);
Q_ASSERT_SUCCEEDED(hr);
boolean trial;
hr = appLicense->get_IsTrial(&trial);
Q_ASSERT_SUCCEEDED(hr);
if (active && !trial) {
qCDebug(lcPurchasingBackend) << "Restoring app product";
QInAppProduct *product = store()->registeredProduct(qt_win_app_identifier);
// App is special and needs explicit registration
if (!product) {
queryProduct(QInAppProduct::Unlockable, qt_win_app_identifier);
product = store()->registeredProduct(qt_win_app_identifier);
}
auto transaction = new QWinRTInAppTransaction(QInAppTransaction::PurchaseRestored,
product,
QInAppTransaction::NoFailure,
appReceipt,
this);
emit transactionReady(transaction);
}
// Using GetProductReceiptAsync is the better solution as one can
// query for specific products instead of parsing through a xml.
// However, this returns E_NOTIMPL when using the ICurrentAppSimulator,
// so it could not be used during development phase.
#if 0
qCDebug(lcPurchasingBackend) << "Experimenting with Product Receipts";
const QStringList keys = d->nativeProducts.keys();
for (auto item : keys) {
HRESULT hr;
HString productId;
hr = productId.Set(reinterpret_cast<LPCWSTR>(item.utf16()), item.size());
ComPtr<IAsyncOperation<HSTRING>> op;
hr = d->m_bridge.GetProductReceiptAsync(productId.Get(), op);
if (FAILED(hr)) {
qCDebug(lcPurchasingBackend) << "No receipt available for:" << item;
continue;
}
HString receiptString;
hr = QWinRTFunctions::await(op, receiptString.GetAddressOf());
if (FAILED(hr)) {
qCDebug(lcPurchasingBackend) << "Failed to wait for receipt:" << item;
continue;
}
const QString receipt = hStringToQString(receiptString);
qDebug() << "Received receipt for " << item << ":" << receipt;
// Create new transaction with status == Restored and emit
//emit transactionReady();
}
#endif
}
void QWinRTInAppPurchaseBackend::setPlatformProperty(const QString &propertyName, const QString &value)
{
qCDebug(lcPurchasingBackend) << __FUNCTION__ << ":" << propertyName << ":" << value;
}
void QWinRTInAppPurchaseBackend::queryProducts(const QList<Product> &products)
{
qCDebug(lcPurchasingBackend) << __FUNCTION__ << " Size:" << products.size();
for (auto p : products)
queryProduct(p.productType, p.identifier);
}
void QWinRTInAppPurchaseBackend::queryProduct(QInAppProduct::ProductType productType,
const QString &identifier)
{
Q_D(QWinRTInAppPurchaseBackend);
qCDebug(lcPurchasingBackend) << __FUNCTION__ << ":" << productType << ":" << identifier;
if (!d->nativeProducts.contains(identifier) || !compareProductTypes(productType, d->nativeProducts.value(identifier)->type)) {
qCDebug(lcPurchasingBackend) << "No native product called:" << identifier;
emit productQueryFailed(productType, identifier);
return;
}
// With the latest Windows Store Updates, product licenses seem to be not working
// anymore. Hence, we have to rely on the listing being correct.
// ComPtr<IProductLicense> productLicense = d->findProductLicense(identifier);
// if (!productLicense && identifier != qt_win_app_identifier) {
// qCDebug(lcPurchasingBackend) << "Could not find product license even though available in listing:" << identifier;
// emit productQueryFailed(productType, identifier);
// return;
// }
NativeProductInfo *cachedInfo = d->nativeProducts.value(identifier);
const QString price = hStringToQString(cachedInfo->formatPrice);
const QString name = hStringToQString(cachedInfo->productName);
QWinRTInAppProduct *appProduct = new QWinRTInAppProduct(this,
price,
name,
QString(),
productType,
identifier,
this);
emit productQueryDone(appProduct);
}
void QWinRTInAppPurchaseBackend::purchaseProduct(QWinRTInAppProduct *product)
{
qCDebug(lcPurchasingBackend) << __FUNCTION__ << product;
Q_D(QWinRTInAppPurchaseBackend);
HRESULT hr;
HString productId;
hr = productId.Set(reinterpret_cast<LPCWSTR>(product->identifier().utf16()),
product->identifier().size());
Q_ASSERT_SUCCEEDED(hr);
if (product->identifier() == qt_win_app_identifier) {
// Buy the app itself
hr = QEventDispatcherWinRT::runOnXamlThread([d, product, this]() {
HRESULT hr;
ComPtr<IAsyncOperation<HSTRING>> appOp;
hr = d->m_bridge.RequestAppPurchaseAsync(true, appOp);
Q_ASSERT_SUCCEEDED(hr);
auto purchaseCallback = Callback<IAsyncOperationCompletedHandler<HSTRING>>([d, product, this](IAsyncOperation<HSTRING> *op, AsyncStatus status)
{
HString receiptH;
QString receiptQ;
HRESULT hr;
hr = op->GetResults(receiptH.GetAddressOf());
if (SUCCEEDED(hr))
receiptQ = hStringToQString(receiptH);
else
qWarning("Could not receive transaction receipt.");
qt_WinRTTransactionData tData(status, product, receiptQ);
QMetaObject::invokeMethod(this, "createTransactionDelayed", Qt::QueuedConnection,
Q_ARG(qt_WinRTTransactionData, tData));
return S_OK;
});
hr = appOp->put_Completed(purchaseCallback.Get());
Q_ASSERT_SUCCEEDED(hr);
return S_OK;
});
} else if (product->productType() == QInAppProduct::Unlockable) {
hr = QEventDispatcherWinRT::runOnXamlThread([d, product, &productId, this]() {
ComPtr<IAsyncOperation<HSTRING>> purchaseOp;
HRESULT hr;
hr = d->m_bridge.RequestProductPurchaseAsync(productId.Get(), true, purchaseOp);
Q_ASSERT_SUCCEEDED(hr);
auto purchaseCallback = Callback<IAsyncOperationCompletedHandler<HSTRING>>([d, product, this](IAsyncOperation<HSTRING> *op, AsyncStatus status)
{
HString receiptH;
QString receiptQ;
HRESULT hr;
hr = op->GetResults(receiptH.GetAddressOf());
if (SUCCEEDED(hr))
receiptQ = hStringToQString(receiptH);
else
qWarning("Could not receive transaction receipt.");
qt_WinRTTransactionData tData(status, product, receiptQ);
QMetaObject::invokeMethod(this, "createTransactionDelayed", Qt::QueuedConnection,
Q_ARG(qt_WinRTTransactionData, tData));
return S_OK;
});
hr = purchaseOp->put_Completed(purchaseCallback.Get());
Q_ASSERT_SUCCEEDED(hr);
return S_OK;
});
} else {
hr = QEventDispatcherWinRT::runOnXamlThread([d, product, &productId, this]() {
HRESULT hr;
ComPtr<IAsyncOperation<PurchaseResults*>> purchaseOp;
hr = d->m_bridge.RequestProductPurchaseWithResultsAsync(productId.Get(), purchaseOp);
Q_ASSERT_SUCCEEDED(hr);
auto purchaseCallback = Callback<IAsyncOperationCompletedHandler<PurchaseResults*>>([d, product, this](IAsyncOperation<PurchaseResults*> *op, AsyncStatus status)
{
ComPtr<IPurchaseResults> purchaseResults;
QString receiptQ;
if (status == AsyncStatus::Completed) {
HRESULT hr;
hr = op->GetResults(&purchaseResults);
Q_ASSERT_SUCCEEDED(hr);
HString receiptH;
hr = purchaseResults->get_ReceiptXml(receiptH.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
receiptQ = hStringToQString(receiptH);
}
qt_WinRTTransactionData tData(status, product, receiptQ, purchaseResults);
QMetaObject::invokeMethod(this, "createTransactionDelayed", Qt::QueuedConnection,
Q_ARG(qt_WinRTTransactionData, tData));
return S_OK;
});
hr = purchaseOp->put_Completed(purchaseCallback.Get());
Q_ASSERT_SUCCEEDED(hr);
return S_OK;
});
}
}
void QWinRTInAppPurchaseBackend::fulfillConsumable(QWinRTInAppTransaction *transaction)
{
Q_D(QWinRTInAppPurchaseBackend);
qCDebug(lcPurchasingBackend) << __FUNCTION__ << transaction;
HRESULT hr;
GUID transactionId;
if (transaction->m_uuid.isNull()) {
hr = transaction->m_purchaseResults->get_TransactionId(&transactionId);
Q_ASSERT_SUCCEEDED(hr);
} else
transactionId = transaction->m_uuid;
HString productId;
const QString identifier = transaction->product()->identifier();
hr = productId.Set(reinterpret_cast<LPCWSTR>(identifier.utf16()), identifier.size());
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IAsyncOperation<FulfillmentResult>> op;
hr = d->m_bridge.ReportConsumableFulfillmentAsync(productId.Get(), transactionId, op);
RETURN_VOID_IF_FAILED("Could not report consumable to be fulfilled.");
FulfillmentResult res;
hr = QWinRTFunctions::await(op, &res);
RETURN_VOID_IF_FAILED("Operation to fulfill consumable failed.");
qCDebug(lcPurchasingBackend) << "Fulfilled:" << (res == FulfillmentResult_Succeeded);
}
HRESULT QWinRTInAppPurchaseBackendPrivate::onListingInformation(IAsyncOperation<ListingInformation *> *args,
AsyncStatus status)
{
Q_UNUSED(status);
Q_Q(QWinRTInAppPurchaseBackend);
qCDebug(lcPurchasingBackend) << __FUNCTION__;
ComPtr<IListingInformation> info;
HRESULT hr = args->GetResults(&info);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IMapView<HSTRING, ABI::Windows::ApplicationModel::Store::ProductListing *>> productListings;
hr = info->get_ProductListings(&productListings);
if (FAILED(hr)) {
qCDebug(lcPurchasingBackend) << "Could not get IMapView";
return S_OK;
}
unsigned int amount = 0;
productListings->get_Size(&amount);
qCDebug(lcPurchasingBackend) << " Found " << amount << " products registered in the store.";
typedef Collections::IKeyValuePair<HSTRING, ProductListing *> ValueItem;
typedef Collections::IIterable<ValueItem *> ValueIterable;
typedef Collections::IIterator<ValueItem *> ValueIterator;
ComPtr<ValueIterable> iterable;
ComPtr<ValueIterator> iterator;
hr = productListings.As(&iterable);
if (FAILED(hr))
return S_OK;
boolean current = false;
hr = iterable->First(&iterator);
if (FAILED(hr))
return S_OK;
hr = iterator->get_HasCurrent(¤t);
if (FAILED(hr))
return S_OK;
while (SUCCEEDED(hr) && current){
ComPtr<ValueItem> currentItem;
hr = iterator->get_Current(¤tItem);
if (FAILED(hr)) {
qCDebug(lcPurchasingBackend) << "Could not get currentItem:" << hr;
continue;
}
HString nativeKey;
QString productKey;
ComPtr<IProductListing> value;
hr = currentItem->get_Key(nativeKey.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
productKey = hStringToQString(nativeKey);
qCDebug(lcPurchasingBackend) << "ProductKey:" << productKey;
hr = currentItem->get_Value(&value);
Q_ASSERT_SUCCEEDED(hr);
auto nativeInfo = new NativeProductInfo;
hr = value->get_ProductId(nativeInfo->productID.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
hr = value->get_FormattedPrice(nativeInfo->formatPrice.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
hr = value->get_Name(nativeInfo->productName.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IProductListingWithConsumables> converted;
hr = value.As(&converted);
if (SUCCEEDED(hr)) {
hr = converted->get_ProductType(&nativeInfo->type);
Q_ASSERT_SUCCEEDED(hr);
} else {
qWarning("Could not acquire product type. Assuming Unlockable");
nativeInfo->type = ProductType_Durable;
}
qCDebug(lcPurchasingBackend) << "Detailed info:"
<< " ID:" << QString::fromWCharArray(nativeInfo->productID.GetRawBuffer(nullptr))
<< " Price:" << QString::fromWCharArray(nativeInfo->formatPrice.GetRawBuffer(nullptr))
<< " Name:" << QString::fromWCharArray(nativeInfo->productName.GetRawBuffer(nullptr))
<< " Type:" << (nativeInfo->type == ProductType_Consumable ? QLatin1String("Consumable") : QLatin1String("Unlockable"));
nativeProducts.insert(QString::fromWCharArray(nativeInfo->productID.GetRawBuffer(nullptr)), nativeInfo);
hr = iterator->MoveNext(¤t);
Q_ASSERT_SUCCEEDED(hr);
}
ComPtr<ILicenseInformation> appLicense;
hr = m_bridge.get_LicenseInformation(appLicense);
Q_ASSERT_SUCCEEDED(hr);
boolean active;
hr = appLicense->get_IsActive(&active);
Q_ASSERT_SUCCEEDED(hr);
boolean trial;
hr = appLicense->get_IsTrial(&trial);
Q_ASSERT_SUCCEEDED(hr);
qCDebug(lcPurchasingBackend) << "App registration: Is Active: " << active << " Is Trial: " << trial;
if (active) {
auto appInfo = new NativeProductInfo;
hr = appInfo->productID.Set(reinterpret_cast<LPCWSTR>(qt_win_app_identifier.utf16()), qt_win_app_identifier.size());
Q_ASSERT_SUCCEEDED(hr);
// We store trial information inside the Name itself, as a kind of
// app State, as the public API does not support trial mode
const QString licenseType = trial ? QLatin1String("Trial period") : QLatin1String("Fully licensed");
appInfo->productName.Set(reinterpret_cast<LPCWSTR>(licenseType.utf16()), licenseType.size());
appInfo->type = ProductType_Durable;
nativeProducts.insert(qt_win_app_identifier, appInfo);
qCDebug(lcPurchasingBackend) << "App license valid, adding to iap items";
}
m_waitingForList = false;
emit q->ready();
return S_OK;
}
ComPtr<IProductLicense> QWinRTInAppPurchaseBackendPrivate::findProductLicense(const QString &identifier)
{
ComPtr<ILicenseInformation> licenseInfo;
HRESULT hr;
hr = m_bridge.get_LicenseInformation(licenseInfo);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IMapView<HSTRING,ABI::Windows::ApplicationModel::Store::ProductLicense*>> licenses;
hr = licenseInfo->get_ProductLicenses(&licenses);
Q_ASSERT_SUCCEEDED(hr);
typedef Collections::IKeyValuePair<HSTRING, ProductLicense *> ValueItem;
typedef Collections::IIterable<ValueItem *> ValueIterable;
typedef Collections::IIterator<ValueItem *> ValueIterator;
ComPtr<ValueIterable> iterable;
ComPtr<ValueIterator> iterator;
hr = licenses.As(&iterable);
Q_ASSERT_SUCCEEDED(hr);
boolean current = false;
hr = iterable->First(&iterator);
Q_ASSERT_SUCCEEDED(hr);
hr = iterator->get_HasCurrent(¤t);
Q_ASSERT_SUCCEEDED(hr);
while (SUCCEEDED(hr) && current) {
ComPtr<ValueItem> currentItem;
hr = iterator->get_Current(¤tItem);
Q_ASSERT_SUCCEEDED(hr);
ComPtr<IProductLicense> productLicense;
hr = currentItem->get_Value(&productLicense);
Q_ASSERT_SUCCEEDED(hr);
HString productId;
hr = productLicense->get_ProductId(productId.GetAddressOf());
Q_ASSERT_SUCCEEDED(hr);
quint32 length;
QString qProductId = QString::fromWCharArray(productId.GetRawBuffer(&length));
if (qProductId == identifier) {
return productLicense;
}
hr = iterator->MoveNext(¤t);
Q_ASSERT_SUCCEEDED(hr);
}
return ComPtr<IProductLicense>();
}
QT_END_NAMESPACE
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtpurchasing/src/purchasing/inapppurchase/winrt/qwinrtinapppurchasebackend.cpp
|
C++
|
gpl-3.0
| 34,425
|
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Unity - Scripting API: WebCamTexture.WebCamTexture</title>
<meta name="description" content="Develop once, publish everywhere! Unity is the ultimate tool for video game development, architectural visualizations, and interactive media installations - publish to the web, Windows, OS X, Wii, Xbox 360, and iPhone with many more platforms to come." />
<meta name="author" content="Unity Technologies" />
<link rel="shortcut icon" href="../StaticFiles/images/favicons/favicon.ico" />
<link rel="icon" type="image/png" href="../StaticFiles/images/favicons/favicon.png" />
<link rel="apple-touch-icon-precomposed" sizes="152x152" href="../StaticFiles/images/favicons/apple-touch-icon-152x152.png" />
<link rel="apple-touch-icon-precomposed" sizes="144x144" href="../StaticFiles/images/favicons/apple-touch-icon-144x144.png" />
<link rel="apple-touch-icon-precomposed" sizes="120x120" href="../StaticFiles/images/favicons/apple-touch-icon-120x120.png" />
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="../StaticFiles/images/favicons/apple-touch-icon-114x114.png" />
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="../StaticFiles/images/favicons/apple-touch-icon-72x72.png" />
<link rel="apple-touch-icon-precomposed" href="../StaticFiles/images/favicons/apple-touch-icon.png" />
<meta name="msapplication-TileColor" content="#222c37" />
<meta name="msapplication-TileImage" content="../StaticFiles/images/favicons/tileicon-144x144.png" />
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2854981-1']);
_gaq.push(['_setDomainName', 'unity3d.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
<script type="text/javascript" src="../StaticFiles/js/jquery.js">
</script>
<script type="text/javascript" src="docdata/toc.js">//toc</script>
<!--local TOC-->
<script type="text/javascript" src="docdata/global_toc.js">//toc</script>
<!--global TOC, including other platforms-->
<script type="text/javascript" src="../StaticFiles/js/core.js">
</script>
<link href="http://fonts.googleapis.com/css?family=Open+Sans:400,700,400italic" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="../StaticFiles/css/core.css" />
</head>
<body>
<div class="header-wrapper">
<div id="header" class="header">
<div class="content">
<div class="spacer">
<div class="menu">
<div class="logo">
<a href="http://docs.unity3d.com">
</a>
</div>
<div class="search-form">
<form action="30_search.html" method="get" class="apisearch">
<input type="text" name="q" placeholder="Search scripting..." autosave="Unity Reference" results="5" class="sbox field" id="q">
</input>
<input type="submit" class="submit">
</input>
</form>
</div>
<ul>
<li>
<a href="http://docs.unity3d.com">Overview</a>
</li>
<li>
<a href="../Manual/index.html">Manual</a>
</li>
<li>
<a href="../ScriptReference/index.html" class="selected">Scripting API</a>
</li>
</ul>
</div>
</div>
<div class="more">
<div class="filler">
</div>
<ul>
<li>
<a href="http://unity3d.com/">unity3d.com</a>
</li>
</ul>
</div>
</div>
</div>
<div class="toolbar">
<div class="content clear">
<div class="lang-switcher hide">
<div class="current toggle" data-target=".lang-list">
<div class="lbl">Language: <span class="b">English</span></div>
<div class="arrow">
</div>
</div>
<div class="lang-list" style="display:none;">
<ul>
<li>
<a href="">English</a>
</li>
</ul>
</div>
</div>
<div class="script-lang">
<ul>
<li class="selected" data-lang="CS">C#</li>
<li data-lang="JS">JS</li>
</ul>
<div id="script-lang-dialog" class="dialog hide">
<div class="dialog-content clear">
<h2>Script language</h2>
<div class="close">
</div>
<p class="clear">Select your preferred scripting language. All code snippets will be displayed in this language.</p>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="master-wrapper" class="master-wrapper clear">
<div id="sidebar" class="sidebar">
<div class="sidebar-wrap">
<div class="content">
<div class="sidebar-menu">
<div class="toc">
<h2>Scripting API</h2>
</div>
</div>
<p>
<a href="40_history.html" class="cw">History</a>
</p>
</div>
</div>
</div>
<div id="content-wrap" class="content-wrap">
<div class="content-block">
<div class="content">
<div class="section">
<div class="mb20 clear">
<h1 class="heading inherit">
<a href="WebCamTexture.html">WebCamTexture</a>.WebCamTexture</h1>
<div class="clear">
</div>
<div class="clear">
</div>
<div class="suggest">
<a class="blue-btn sbtn">Suggest a change</a>
<div class="suggest-wrap rel hide">
<div class="loading hide">
<div>
</div>
<div>
</div>
<div>
</div>
</div>
<div class="suggest-success hide">
<h2>Success!</h2>
<p>Thank you for helping us improve the quality of Unity Documentation. Although we cannot accept all submissions, we do read each suggested change from our users and will make updates where applicable.</p>
<a class="gray-btn sbtn close">Close</a>
</div>
<div class="suggest-failed hide">
<h2>Sumbission failed</h2>
<p>For some reason your suggested change could not be submitted. Please <a>try again</a> in a few minutes. And thank you for taking the time to help us improve the quality of Unity Documentation.</p>
<a class="gray-btn sbtn close">Close</a>
</div>
<div class="suggest-form clear">
<label for="suggest_name">Your name</label>
<input id="suggest_name" type="text">
</input>
<label for="suggest_email">Your email</label>
<input id="suggest_email" type="email">
</input>
<label for="suggest_body" class="clear">Suggestion <span class="r">*</span></label>
<textarea id="suggest_body" class="req">
</textarea>
<button id="suggest_submit" class="blue-btn mr10">Submit suggestion</button>
<p class="mb0">
<a class="cancel left lh42 cn">Cancel</a>
</p>
</div>
</div>
</div>
<a href="" class="switch-link gray-btn sbtn left hide">Switch to Manual</a>
<div class="clear">
</div>
</div>
<div class="subsection">
<div class="signature">
<div class="signature-JS sig-block">public <span class="sig-kw">WebCamTexture</span>()</div>
<div class="signature-CS sig-block">public <span class="sig-kw">WebCamTexture</span>();
</div>
<div class="signature-JS sig-block">public <span class="sig-kw">WebCamTexture</span>(<span class="sig-kw">requestedWidth</span>:
int,
<span class="sig-kw">requestedHeight</span>: int,
<span class="sig-kw">requestedFPS</span>: int)</div>
<div class="signature-CS sig-block">public <span class="sig-kw">WebCamTexture</span>(int <span class="sig-kw">requestedWidth</span>,
int <span class="sig-kw">requestedHeight</span>,
int <span class="sig-kw">requestedFPS</span>);
</div>
<div class="signature-JS sig-block">public <span class="sig-kw">WebCamTexture</span>(<span class="sig-kw">requestedWidth</span>:
int,
<span class="sig-kw">requestedHeight</span>: int)</div>
<div class="signature-CS sig-block">public <span class="sig-kw">WebCamTexture</span>(int <span class="sig-kw">requestedWidth</span>,
int <span class="sig-kw">requestedHeight</span>);
</div>
<div class="signature-JS sig-block">public <span class="sig-kw">WebCamTexture</span>(<span class="sig-kw">deviceName</span>:
string)</div>
<div class="signature-CS sig-block">public <span class="sig-kw">WebCamTexture</span>(string <span class="sig-kw">deviceName</span>);
</div>
<div class="signature-JS sig-block">public <span class="sig-kw">WebCamTexture</span>(<span class="sig-kw">deviceName</span>:
string,
<span class="sig-kw">requestedWidth</span>: int,
<span class="sig-kw">requestedHeight</span>: int)</div>
<div class="signature-CS sig-block">public <span class="sig-kw">WebCamTexture</span>(string <span class="sig-kw">deviceName</span>,
int <span class="sig-kw">requestedWidth</span>,
int <span class="sig-kw">requestedHeight</span>);
</div>
<div class="signature-JS sig-block">public <span class="sig-kw">WebCamTexture</span>(<span class="sig-kw">deviceName</span>:
string,
<span class="sig-kw">requestedWidth</span>: int,
<span class="sig-kw">requestedHeight</span>: int,
<span class="sig-kw">requestedFPS</span>: int)</div>
<div class="signature-CS sig-block">public <span class="sig-kw">WebCamTexture</span>(string <span class="sig-kw">deviceName</span>,
int <span class="sig-kw">requestedWidth</span>,
int <span class="sig-kw">requestedHeight</span>,
int <span class="sig-kw">requestedFPS</span>);
</div>
</div>
</div>
<div class="subsection">
<h2>Parameters</h2>
<table class="list">
<tr>
<td class="name lbl">deviceName</td>
<td class="desc">The name of the video input device to be used.</td>
</tr>
<tr>
<td class="name lbl">requestedWidth</td>
<td class="desc">The requested width of the texture.</td>
</tr>
<tr>
<td class="name lbl">requestedHeight</td>
<td class="desc">The requested height of the texture.</td>
</tr>
<tr>
<td class="name lbl">requestedFPS</td>
<td class="desc">The requested frame rate of the texture.</td>
</tr>
</table>
</div>
<div class="subsection">
<h2>Description</h2>
<p>Create a WebCamTexture.</p>
</div>
<div class="subsection">
<p>Use <a href="WebCamTexture-devices.html">WebCamTexture.devices</a> to get a list of the names of available camera devices. If no device name is supplied to the constructor or is passed as a null string, the first device found will be used.<br /><br />The requested width, height and framerate specified by the parameters may not be supported by the chosen camera. In such cases, the closest available values will be used.<br /><br />Note: if you want to use WebCamTextures in the web player, you need to get the user's
permission to do so. Call <a href="Application.RequestUserAuthorization.html">Application.RequestUserAuthorization</a> before creating a
WebCamTexture.<br /><br />Note: if you want to use WebCamTexture to play the camera stream from device connected through Unity Remote, then you must initalize it through the constructor. Later it's not possible to change device using <a href="WebCamTexture-deviceName.html">WebCamTexture.deviceName</a> from regular devices to remote devices and vice versa.</p>
</div>
</div>
<div class="footer-wrapper">
<div class="footer clear">
<div class="copy">Copyright © 2014 Unity Technologies</div>
<div class="menu">
<a href="http://unity3d.com/learn">Learn</a>
<a href="http://unity3d.com/community">Community</a>
<a href="http://unity3d.com/asset-store">Asset Store</a>
<a href="https://store.unity3d.com">Buy</a>
<a href="http://unity3d.com/unity/download">Download</a>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
|
rakuten/Uinty3D-Docs-zhcn
|
ScriptReference/WebCamTexture-ctor.html
|
HTML
|
gpl-3.0
| 14,454
|
#include "cellinfo.h"
CellInfo::CellInfo(Position pos, bool filled, bool canTravelXNeg, bool canTravelXPos,
bool canTravelYNeg, bool canTravelYPos, bool canTravelZNeg, bool canTravelZPos)
: itsPosition(pos) {
itsCanTravel[NO_DIRECTION] = filled;
itsCanTravel[XNEG] = canTravelXNeg;
itsCanTravel[XPOS] = canTravelXPos;
itsCanTravel[YNEG] = canTravelYNeg;
itsCanTravel[YPOS] = canTravelYPos;
itsCanTravel[ZNEG] = canTravelZNeg;
itsCanTravel[ZPOS] = canTravelZPos;
}
Position CellInfo::getPosition() {
return itsPosition;
}
bool CellInfo::canTravel(Direction dir) {
return itsCanTravel[dir];
}
bool CellInfo::canTravel() {
return itsCanTravel[NO_DIRECTION];
}
bool CellInfo::canTravelXNeg() {
return itsCanTravel[XNEG];
}
bool CellInfo::canTravelXPos() {
return itsCanTravel[XPOS];
}
bool CellInfo::canTravelYNeg() {
return itsCanTravel[YNEG];
}
bool CellInfo::canTravelYPos() {
return itsCanTravel[YPOS];
}
bool CellInfo::canTravelZNeg() {
return itsCanTravel[ZNEG];
}
bool CellInfo::canTravelZPos() {
return itsCanTravel[ZPOS];
}
|
Mortonium/QtHelloTriangle
|
cellinfo.cpp
|
C++
|
gpl-3.0
| 1,082
|
/**
* Copyright (C) 2016 Michael Johnson
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>
*/
package pso.async.implementation.plants;
import java.util.Arrays;
import log.ApplicationLogger;
import org.apache.commons.math3.linear.Array2DRowRealMatrix;
import org.apache.commons.math3.linear.RealMatrix;
import pso.MisconfiguredBlockException;
import pso.async.interfaces.Plant;
/**
* This class is a {@link StateSpace} representation of a Linear, time invariant
* (LTI) dynamic system.
*
* @author Mike Johnson
*
*/
public class StateSpace implements Plant
{
/**
* The A Matrix
*/
protected RealMatrix A = null;
/**
* The B Matrix
*/
protected RealMatrix B = null;
/**
* The C Matrix
*/
protected RealMatrix C = null;
/**
* The D Matrix
*/
protected RealMatrix D = null;
/**
* The time index
*/
protected long k = 0;
/**
* The initial state vector
*/
protected int[] initialState = null;
/**
* The next state vector
*/
protected int[] nextState = null;
/**
* The current state vector
*/
protected int[] state = null;
/**
* Constructs a {@link StateSpace} system from a set of
* {@link LinearPlantParameters}
*
* @throws MisconfiguredBlockException if the parameters are not valid
*
*/
public StateSpace (LinearPlantParameters params)
throws MisconfiguredBlockException
{
// initialize our values
k = 0;
int ovs = params.getOutputVectorSize();
int ivs = params.getInputVectorSize();
int svs = params.getStateVectorSize();
state = new int[svs];
nextState = new int[svs];
A = params.getA();
B = params.getB();
C = params.getC();
D = params.getD();
// check if the model is misconfigured
if (ivs != B.getColumnDimension()) { throw new MisconfiguredBlockException(
"B Matrix must have same number of Columns as size of input vector."); }
if (svs != B.getRowDimension()) { throw new MisconfiguredBlockException(
"B Matrix must have same number of Rows as size of state vector."); }
if (svs != A.getColumnDimension()) { throw new MisconfiguredBlockException(
"A Matrix must have same number of Columns as size of state vector."); }
if (svs != A.getRowDimension()) { throw new MisconfiguredBlockException(
"A Matrix must have same number of Rows as size of state vector."); }
if (ovs != C.getRowDimension()) { throw new MisconfiguredBlockException(
"C Matrix must have same number of Rows as size of output vector."); }
if (svs != C.getColumnDimension()) { throw new MisconfiguredBlockException(
"C Matrix must have same number of Columns as size of state vector."); }
if (ivs != D.getColumnDimension()) { throw new MisconfiguredBlockException(
"D Matrix must have same number of Columns as size of input vector."); }
if (ovs != D.getRowDimension()) { throw new MisconfiguredBlockException(
"D Matrix must have same number of Rows as size of output vector."); }
}
/**
* Resets the {@link StateSpace} model back to the initial timestep and sets
* the current state to the initial state
*/
public void reset ()
{
k = 0;
state = Arrays.copyOf(initialState, initialState.length);
}
/**
* @return the a
*/
public RealMatrix getA ()
{
return A;
}
/**
* @param a the a to set
*/
public void setA (RealMatrix a)
{
A = a;
}
/**
* @return the b
*/
public RealMatrix getB ()
{
return B;
}
/**
* @param b the b to set
*/
public void setB (RealMatrix b)
{
B = b;
}
/**
* @return the c
*/
public RealMatrix getC ()
{
return C;
}
/**
* @param c the c to set
*/
public void setC (RealMatrix c)
{
C = c;
}
/**
* @return the d
*/
public RealMatrix getD ()
{
return D;
}
/**
* @param d the d to set
*/
public void setD (RealMatrix d)
{
D = d;
}
/**
* @return the k
*/
public long getK ()
{
return k;
}
/**
* @param k the k to set
*/
public void setK (long k)
{
this.k = k;
}
/**
* @return the state
*/
public int[] getState ()
{
return Arrays.copyOf(state, state.length);
}
/**
* @param state the state to set
*/
public void setState (int... state)
{
this.state = state;
}
/**
* @return the initialState
*/
public int[] getInitialState ()
{
return Arrays.copyOf(initialState, initialState.length);
}
/**
* Sets the initial state for the dynamics.
*
* @param initial
* @throws MisconfiguredBlockException
*/
public void setInitialState (int... initial)
throws MisconfiguredBlockException
{
ApplicationLogger.getInstance().logDebug("PLANT: initializing");
if (initialState == null)
{
initialState = new int[state.length];
}
if (initial.length != initialState.length) { throw new MisconfiguredBlockException(
"Initial State must have dimension of " + initialState.length); }
initialState = initial;
state = Arrays.copyOf(initialState, initialState.length);
}
/*
* (non-Javadoc)
*
* @see pso.async.interfaces.Plant#isInitialized()
*/
@Override
public boolean isInitialized ()
{
if (initialState == null) { return false; }
return true;
}
/*
* (non-Javadoc)
*
* @see pso.async.interfaces.Plant#transfer(int[])
*/
@Override
public int[] transfer (int... input) throws MisconfiguredBlockException
{
if (input.length != B.getColumnDimension()) { throw new MisconfiguredBlockException(
"Input vector must have dimension equal to B Matrix number of Columns."); }
// System.out.println("Input!: " + input.toString());
RealMatrix inputMatrix = new Array2DRowRealMatrix(input.length, 1);
for (int i = 0; i < input.length; i++ )
{
inputMatrix.setEntry(i, 0, input[i]);
}
RealMatrix stateMatrix = new Array2DRowRealMatrix(state.length, 1);
for (int i = 0; i < state.length; i++ )
{
stateMatrix.setEntry(i, 0, state[i]);
}
RealMatrix nextStateMatrix =
A.multiply(stateMatrix).add(B.multiply(inputMatrix));
RealMatrix output =
C.multiply(nextStateMatrix).add(D.multiply(inputMatrix));
for (int i = 0; i < state.length; i++ )
{
nextState[i] = (int) Math.floor(nextStateMatrix.getEntry(i, 0));
}
propagateState();
int[] outputIndicies = new int[output.getRowDimension()];
for (int i = 0; i < outputIndicies.length; i++ )
{
outputIndicies[i] = (int) Math.floor(output.getEntry(i, 0));
}
return outputIndicies;
}
/**
* Increments one timestep in the signal.
*
* Delays the next state so that it becomes the current state.
*
* This allows the solution to the finite difference equations to be
* calculated
*/
protected void propagateState ()
{
k++ ;
for (int i = 0; i < state.length; i++ )
{
state[i] = nextState[i];
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString ()
{
return String
.format("StateSpace [A=%s, B=%s, C=%s, D=%s, k=%s, initialState=%s, nextState=%s, state=%s]",
A, B, C, D, k, Arrays.toString(initialState), Arrays.toString(nextState), Arrays.toString(state));
}
}
|
mj21181/ursus-swarm
|
src/main/java/pso/async/implementation/plants/StateSpace.java
|
Java
|
gpl-3.0
| 7,735
|
//
// Copyright (c) 2010-2013 Yves Langisch. All rights reserved.
// http://cyberduck.ch/
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// Bug fixes, suggestions and comments should be sent to:
// yves@cyberduck.ch
//
using System.Drawing;
using Ch.Cyberduck.Core.I18n;
using Ch.Cyberduck.Core.Local;
using NUnit.Framework;
namespace Ch.Cyberduck.Ui.Controller
{
[TestFixture]
public class PersistentFormHandlerTest
{
[Test]
public void SetGetTest()
{
PersistentFormHandler handler = new PersistentFormHandler(GetType(), 0, Rectangle.Empty);
handler.Set("key", 189);
handler = new PersistentFormHandler(GetType(), 0, Rectangle.Empty);
Assert.AreEqual(189, handler.Get<int>("key"));
}
[Test]
public void SetGetTestDefaultValue()
{
PersistentFormHandler handler = new PersistentFormHandler(GetType(), 0, Rectangle.Empty);
handler.Set("keyDefault", 111);
handler = new PersistentFormHandler(GetType(), 0, Rectangle.Empty);
Assert.AreEqual(500, handler.Get("keyNotAvailable", 500));
}
}
}
|
iterate-ch/cyberduck
|
windows/src/test/csharp/ch/cyberduck/ui/controller/PersistentFormHandlerTest.cs
|
C#
|
gpl-3.0
| 1,631
|
<?php defined('SYSPATH') or die('No direct script access.');?>
<header class="navbar navbar-inverse navbar-fixed-top bs-docs-nav">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="<?=Route::url('default')?>"><?=core::config('general.site_name')?></a>
</div>
<?
$cats = Model_Category::get_category_count();
$loc_seoname = NULL;
if (Controller::$location!==NULL)
{
if (Controller::$location->loaded())
$loc_seoname = Controller::$location->seoname;
}
?>
<div class="collapse navbar-collapse" id="mobile-menu-panel">
<ul class="nav navbar-nav">
<?if (class_exists('Menu') AND count( $menus = Menu::get() )>0 ):?>
<?foreach ($menus as $menu => $data):?>
<li class="<?=(Request::current()->uri()==$data['url'])?'active':''?>" >
<a href="<?=$data['url']?>" target="<?=$data['target']?>">
<?if($data['icon']!=''):?><i class="<?=$data['icon']?>"></i> <?endif?>
<?=$data['title']?></a>
</li>
<?endforeach?>
<?else:?>
<?nav_link(__('Listing'),'ad', 'glyphicon glyphicon-list' ,'listing', 'list')?>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown"><?=__('Categories')?> <b class="caret"></b></a>
<ul class="dropdown-menu">
<?foreach($cats as $c ):?>
<?if($c['id_category_parent'] == 1 && $c['id_category'] != 1):?>
<li class="dropdown-submenu">
<a tabindex="-1" title="<?=$c['seoname']?>" href="<?=Route::url('list', array('category'=>$c['seoname'],'location'=>$loc_seoname))?>">
<?=$c['name']?>
</a>
<?if($c['has_siblings'] AND $c['id_category_parent'] == 1):?>
<ul class="dropdown-menu">
<?foreach($cats as $chi):?>
<?if($chi['id_category_parent'] == $c['id_category']):?>
<li>
<a title="<?=$chi['name']?>" href="<?=Route::url('list', array('category'=>$chi['seoname'],'location'=>$loc_seoname))?>">
<span class="header_cat_list"><?=$chi['name']?></span>
<span class="count_ads"><span class="badge badge-success"><?=$chi['count']?></span></span>
</a>
</li>
<?endif?>
<?endforeach?>
</ul>
<?endif?>
</li>
<?endif?>
<?endforeach?>
</ul>
</li>
<?if (core::config('general.blog')==1):?>
<?nav_link(__('Blog'),'blog','','index','blog')?>
<?endif?>
<?nav_link('','ad', 'glyphicon glyphicon-search ', 'advanced_search', 'search')?>
<?if (core::config('advertisement.map')==1):?>
<?nav_link('','map', 'glyphicon glyphicon-globe ', 'index', 'map')?>
<?endif?>
<?nav_link('','contact', 'glyphicon glyphicon-envelope ', 'index', 'contact')?>
<?nav_link('','rss', 'glyphicon glyphicon-signal ', 'index', 'rss')?>
<?endif?>
</ul>
<div class="btn-group pull-right btn-header-group">
<?=View::factory('widget_login')?>
<a class="btn btn-danger" href="<?=Route::url('post_new')?>">
<i class="glyphicon glyphicon-pencil glyphicon"></i>
<?=__('Publish new ')?>
</a>
</div>
</div><!--/.nav-collapse -->
</div>
</header>
<?if (!Auth::instance()->logged_in()):?>
<div id="login-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal" >×</a>
<h3><?=__('Login')?></h3>
</div>
<div class="modal-body">
<?=View::factory('pages/auth/login-form')?>
</div>
</div>
</div>
</div>
<div id="forgot-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal" >×</a>
<h3><?=__('Forgot password')?></h3>
</div>
<div class="modal-body">
<?=View::factory('pages/auth/forgot-form')?>
</div>
</div>
</div>
</div>
<div id="register-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<a class="close" data-dismiss="modal" >×</a>
<h3><?=__('Register')?></h3>
</div>
<div class="modal-body">
<?=View::factory('pages/auth/register-form')?>
</div>
</div>
</div>
</div>
<?endif?>
|
Wildboard/WbWebApp
|
themes/default/views/header.php
|
PHP
|
gpl-3.0
| 5,660
|
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 4; tab-width: 4 -*- */
/*
* Copyright (C) 2010 Debarshi Ray <rishi@gnu.org>
* Copyright (C) 2009 Santanu Sinha <santanu.sinha@gmail.com>
*
* Solang 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.
*
* Solang is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SOLANG_NON_COPYABLE_H
#define SOLANG_NON_COPYABLE_H
namespace Solang
{
class NonCopyable
{
protected:
NonCopyable();
~NonCopyable();
private:
// Blocked.
NonCopyable(const NonCopyable & source);
// Blocked.
NonCopyable &
operator=(const NonCopyable & source);
};
} // namespace Solang
#endif // SOLANG_NON_COPYABLE_H
|
GNOME/solang
|
src/common/non-copyable.h
|
C
|
gpl-3.0
| 1,193
|
/* $XFree86: xc/programs/Xserver/afb/afbhrzvert.c,v 3.1 2001/08/01 00:44:47 tsi Exp $ */
/* Combined Purdue/PurduePlus patches, level 2.0, 1/17/89 */
/***********************************************************
Copyright (c) 1987 X Consortium
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Except as contained in this notice, the name of the X Consortium shall not be
used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from the X Consortium.
Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
All Rights Reserved
Permission to use, copy, modify, and distribute this software and its
documentation for any purpose and without fee is hereby granted,
provided that the above copyright notice appear in all copies and that
both that copyright notice and this permission notice appear in
supporting documentation, and that the name of Digital not be
used in advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
SOFTWARE.
******************************************************************/
/* $XConsortium: afbhrzvert.c,v 1.15 94/04/17 20:28:24 dpw Exp $ */
#include "X.h"
#include "gc.h"
#include "window.h"
#include "pixmap.h"
#include "region.h"
#include "afb.h"
#include "maskbits.h"
/* horizontal solid line
abs(len) > 1
*/
void
afbHorzS(pbase, nlwidth, sizeDst, depthDst, x1, y1, len, rrops)
PixelType *pbase; /* pointer to base of bitmap */
register int nlwidth; /* width in longwords of bitmap */
int sizeDst;
int depthDst;
int x1; /* initial point */
int y1;
int len; /* length of line */
register unsigned char *rrops;
{
register PixelType *addrl;
register PixelType startmask;
register PixelType endmask;
register int nlmiddle;
register int d;
int saveNLmiddle;
/* force the line to go left to right
but don't draw the last point
*/
if (len < 0) {
x1 += len;
x1 += 1;
len = -len;
}
/* all bits inside same longword */
if ( ((x1 & PIM) + len) < PPW) {
maskpartialbits(x1, len, startmask);
for (d = 0; d < depthDst; d++) {
addrl = afbScanline(pbase, x1, y1, nlwidth);
pbase += sizeDst; /* @@@ NEXT PLANE @@@ */
switch (rrops[d]) {
case RROP_BLACK:
*addrl &= ~startmask;
break;
case RROP_WHITE:
*addrl |= startmask;
break;
case RROP_INVERT:
*addrl ^= startmask;
break;
case RROP_NOP:
break;
} /* switch */
} /* for (d = ...) */
} else {
maskbits(x1, len, startmask, endmask, nlmiddle);
saveNLmiddle = nlmiddle;
for (d = 0; d < depthDst; d++) {
addrl = afbScanline(pbase, x1, y1, nlwidth);
pbase += sizeDst; /* @@@ NEXT PLANE @@@ */
nlmiddle = saveNLmiddle;
switch (rrops[d]) {
case RROP_BLACK:
if (startmask)
*addrl++ &= ~startmask;
Duff (nlmiddle, *addrl++ = 0x0);
if (endmask)
*addrl &= ~endmask;
break;
case RROP_WHITE:
if (startmask)
*addrl++ |= startmask;
Duff (nlmiddle, *addrl++ = ~0);
if (endmask)
*addrl |= endmask;
break;
case RROP_INVERT:
if (startmask)
*addrl++ ^= startmask;
Duff (nlmiddle, *addrl++ ^= ~0);
if (endmask)
*addrl ^= endmask;
break;
case RROP_NOP:
break;
} /* switch */
} /* for (d = ... ) */
}
}
/* vertical solid line
this uses do loops because pcc (Ultrix 1.2, bsd 4.2) generates
better code. sigh. we know that len will never be 0 or 1, so
it's OK to use it.
*/
void
afbVertS(pbase, nlwidth, sizeDst, depthDst, x1, y1, len, rrops)
PixelType *pbase; /* pointer to base of bitmap */
register int nlwidth; /* width in longwords of bitmap */
int sizeDst;
int depthDst;
int x1, y1; /* initial point */
register int len; /* length of line */
unsigned char *rrops;
{
register PixelType *addrl;
register PixelType bitmask;
int saveLen;
int d;
if (len < 0) {
nlwidth = -nlwidth;
len = -len;
}
saveLen = len;
for (d = 0; d < depthDst; d++) {
addrl = afbScanline(pbase, x1, y1, nlwidth);
pbase += sizeDst; /* @@@ NEXT PLANE @@@ */
len = saveLen;
switch (rrops[d]) {
case RROP_BLACK:
bitmask = rmask[x1 & PIM];
Duff(len, *addrl &= bitmask; afbScanlineInc(addrl, nlwidth) );
break;
case RROP_WHITE:
bitmask = mask[x1 & PIM];
Duff(len, *addrl |= bitmask; afbScanlineInc(addrl, nlwidth) );
break;
case RROP_INVERT:
bitmask = mask[x1 & PIM];
Duff(len, *addrl ^= bitmask; afbScanlineInc(addrl, nlwidth) );
break;
case RROP_NOP:
break;
} /* switch */
} /* for (d = ...) */
}
|
chriskmanx/qmole
|
QMOLEDEV/vnc-4_1_3-unixsrc/unix/xc/programs/Xserver/afb/afbhrzvert.c
|
C
|
gpl-3.0
| 6,028
|
using NUnit.Framework;
using EncryptedOneDrive;
namespace EncryptedOneDrive.Tests
{
[TestFixture ()]
public class OneDriveStorageTest
{
OneDrive.FileSystem fs = null;
[TestFixtureSetUp]
public void Setup()
{
var cfg = new Config ();
var auth = AppLoader.Login (cfg);
fs = new OneDrive.FileSystem (
cfg,
new OneDrive.RestClient(auth),
TestUtility.DummyKVS.Instance);
}
[TestFixtureTearDown]
public void Teardown()
{
if (fs != null) {
fs.Dispose ();
fs = null;
}
}
[Test ()]
public void TestCase ()
{
}
}
}
|
kazuki/EncryptedOneDrive
|
EncryptedOneDrive.Tests/OneDriveStorageTest.cs
|
C#
|
gpl-3.0
| 772
|
/**
# Mantis Plugin "EasyEnter"
# Copyright (C) 2015 Frithjof Gnas - fg@prae-sensation.de
#
# Javascript functions and calls to slim down the bug-report-form on the
# configured base of include_fields, field_values etc..
#
# Disclaimer & License:
# This plugin - EasyEnter - 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 MantisBT. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* Function calls, plugin execution
*/
populate_field_values( );
hide_all_fields_show_include_fields( );
/*
* Functions
*/
/**
* Set the values defined in "easyenter_config" for the corresponding fields
* TODO: Implemet jQuery-populate-plugin
*/
function populate_field_values( ) {
if( !easyenter_config.hasOwnProperty( 'field_values' ) ) {
return;
}
for( field_name in easyenter_config.field_values ) {
var thisInputfield = jQuery( '[name="' + field_name + '"]' );
if( thisInputfield.length < 1 ) {
continue;
}
if( !easyenter_config.field_values.hasOwnProperty( field_name ) ) {
continue;
}
//radio buttons need special actions, the radio button with "field_name"
// AND the configured field_value should get the attribute "checked"
if( thisInputfield.attr( 'type' ) === 'radio' ) {
thisInputfield = jQuery(
'[name="' + field_name + '"][value="'
+ easyenter_config.field_values[ field_name ] + '"]'
);
thisInputfield.attr('checked', 'checked');
continue;
}
//Single checkboxes are checked when their field_value is "CHECKED"
if( thisInputfield.attr( 'type' ) === 'checkbox' ) {
if ( 'CHECKED' === easyenter_config.field_values[ field_name ] ) {
thisInputfield.attr('checked', 'checked');
continue;
}
}
thisInputfield.val( easyenter_config.field_values[ field_name ] );
}
}
/**
* Hides all fields in "report_bug_form"-form and shows the defined
* "include_fields" afterwards
*/
function hide_all_fields_show_include_fields( ) {
var i = 0;
if( !easyenter_config.hasOwnProperty( 'include_fields' ) ) {
return;
}
if( easyenter_config.include_fields.length < 1 ) {
return;
}
var form = jQuery( 'form#report_bug_form' );
//Hide all fields, except the hidden ones, submit/reset buttons
form.find( 'input, select, textarea')
.not( ':hidden' )
.not( '[type="button"][type="submit"][type="reset"]' )
.each(function( ) {
showhide_input_field_row( jQuery( this ).attr( 'name' ), 0 );
});
//Special fields/rows to hide...
if ( easyenter_config.hasOwnProperty( 'exclude_fields' ) ) {
for( i = 0; i < easyenter_config.exclude_fields.length; i++ ) {
if( easyenter_config.exclude_fields[i] === 'special.custom_profile' ) {
hide_custom_profile_row();
continue;
}
if( easyenter_config.exclude_fields[i] === 'special.mandatory_asterisks' ) {
hide_mandatory_asterisks();
continue;
}
}
}
//Workaround: Profile-Dropdown is not shown if no profiles exists so far
// (whether global nor user-specific profiles) but the approbiate row is
// shown though.
form.find('tr')
.find('td.category:contains("' + label_selectprofile + '")')
.parent('tr').hide();
// Show fields defined in include_fields
for( i = 0; i < easyenter_config.include_fields.length; i++ ) {
showhide_input_field_row( easyenter_config.include_fields[ i ], 1 );
}
}
/**
* Show or hide a table row holding input with given name and label as well
* @param field_name name of the input of which the parent row should be hidden
* @param showrow 1=show row | 0 = hide
*/
function showhide_input_field_row( field_name, showrow ) {
var field = jQuery( '[name="' + field_name + '"]' );
if ( field.length < 1 ) {
return;
}
if( showrow === 1) {
field.parents( 'tr' ).show( );
} else {
field.parents( 'tr' ).hide( );
}
}
/**
* Hides the row for entering a custom profile, this is not covered by
* hide_all_fields_... because in the corresponding row is no input
*/
function hide_custom_profile_row( ) {
jQuery( '#profile_closed' ).parent( 'td' ).parent( 'tr').hide();
}
/**
* Hide all elements with CSS-class "required" which means hide all asterisks
* as well as the notice "* means mandatory field"
*/
function hide_mandatory_asterisks( ) {
jQuery( 'span.required').hide();
}
|
fg-ok/EasyEnter
|
files/easyenter_page.js
|
JavaScript
|
gpl-3.0
| 4,477
|
#!/bin/bash
echo "Loop of curl request, with plugin disabled for the page $1"
for p in $(wp plugin list --fields=name --status=active)
do
echo "Plugin: $p"
for i in {1..5}
do
curl -so /dev/null -H "Pragma: no-cache" -w "%{time_total}\n" $1 | sed 's/\,/./'
done | awk '{ sum +=$1; n++; print $1 } END { if (n > 0) print "AVG: " sum / n; }'
wp plugin activate $p
done
|
Mte90/Script
|
profiling/plugin-profile.sh
|
Shell
|
gpl-3.0
| 392
|
package com.packt.webstore.interceptor;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.util.StopWatch;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class PerformanceMonitorInterceptor implements HandlerInterceptor {
ThreadLocal<StopWatch> stopWatchLocal = new ThreadLocal<StopWatch>();
Logger logger = Logger.getLogger(this.getClass());
public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) {
StopWatch stopWatch = new StopWatch(handler.toString());
stopWatch.start(handler.toString());
stopWatchLocal.set(stopWatch);
logger.info("Accessing URL path: " + getURLPath(request));
logger.info("Request processing started on: " +getCurrentTime());
return true;
}
public void postHandle(HttpServletRequest arg0,HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
logger.info("Request processing ended on " +getCurrentTime());
}
public void afterCompletion(HttpServletRequest request,HttpServletResponse response, Object handler,Exception exception) throws Exception {
StopWatch stopWatch = stopWatchLocal.get();
stopWatch.stop();
logger.info("Total time taken for processing: " +stopWatch.getTotalTimeMillis()+ " ms");
stopWatchLocal.set(null);
logger.info("=======================================================");
}
private String getURLPath(HttpServletRequest request) {
String currentPath = request.getRequestURI();
String queryString = request.getQueryString();
queryString = queryString == null ? "" : "?" + queryString;
return currentPath+queryString;
}
private String getCurrentTime() {
DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy 'at' hh:mm:ss");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
return formatter.format(calendar.getTime());
}
}
|
bopbruno/webstore
|
webstore/src/main/java/com/packt/webstore/interceptor/PerformanceMonitorInterceptor.java
|
Java
|
gpl-3.0
| 2,266
|
// This file is part of MuMax, a high-performance micromagnetic simulator.
// Copyright 2011 Arne Vansteenkiste and Ben Van de Wiele.
// Use of this source code is governed by the GNU General Public License version 3
// (as published by the Free Software Foundation) that can be found in the license.txt file.
// Note that you are welcome to modify this code under the condition that you do not remove any
// copyright notices and prominently state that you modified it, giving a relevant date.
package engine
// This file implements an adaptive Euler-Heun scheme
// Author: Arne Vansteenkiste
import (
"math"
. "hotspin-core/common"
"hotspin-core/gpu"
"fmt"
)
type RK12Solver struct {
y0buffer []*gpu.Array // initial value
dybuffer []*gpu.Array // initial derivative
err []*Quant // error estimates for each equation
peakErr []*Quant // maximum error for each equation
maxErr []*Quant // maximum error for each equation
diff []gpu.Reductor
minDt *Quant
maxDt *Quant
badSteps *Quant
}
// Load the solver into the Engine
func LoadRK12(e *Engine) {
s := new(RK12Solver)
// Minimum/maximum time step
s.minDt = e.AddNewQuant("mindt", SCALAR, VALUE, Unit("s"), "Minimum time step")
s.minDt.SetScalar(1e-38)
s.minDt.SetVerifier(Positive)
s.maxDt = e.AddNewQuant("maxdt", SCALAR, VALUE, Unit("s"), "Maximum time step")
s.maxDt.SetVerifier(Positive)
s.maxDt.SetScalar(1e38)
s.badSteps = e.AddNewQuant("badsteps", SCALAR, VALUE, Unit(""), "Number of time steps that had to be re-done")
equation := e.equation
s.dybuffer = make([]*gpu.Array, len(equation))
s.y0buffer = make([]*gpu.Array, len(equation))
s.err = make([]*Quant, len(equation))
s.peakErr = make([]*Quant, len(equation))
s.maxErr = make([]*Quant, len(equation))
s.diff = make([]gpu.Reductor, len(equation))
e.SetSolver(s)
for i := range equation {
eqn := &(equation[i])
Assert(eqn.kind == EQN_PDE1)
out := eqn.output[0]
unit := out.Unit()
s.err[i] = e.AddNewQuant(out.Name()+"_error", SCALAR, VALUE, unit, "Error/step estimate for "+out.Name())
s.peakErr[i] = e.AddNewQuant(out.Name()+"_peakerror", SCALAR, VALUE, unit, "All-time maximum error/step for "+out.Name())
s.maxErr[i] = e.AddNewQuant(out.Name()+"_maxError", SCALAR, VALUE, unit, "Maximum error/step for "+out.Name())
s.diff[i].Init(out.Array().NComp(), out.Array().Size3D())
s.maxErr[i].SetVerifier(Positive)
// TODO: recycle?
y := equation[i].output[0]
s.dybuffer[i] = Pool.Get(y.NComp(), y.Size3D())
s.y0buffer[i] = Pool.Get(y.NComp(), y.Size3D())
}
}
// Declares this solver's special dependencies
func (s *RK12Solver) Dependencies() (children, parents []string) {
children = []string{"dt", "step", "t", "badsteps"}
parents = []string{"dt", "mindt", "maxdt"}
for i := range s.err {
parents = append(parents, s.maxErr[i].Name())
children = append(children, s.peakErr[i].Name(), s.err[i].Name())
}
return
}
// Register this module
func init() {
RegisterModule("solver/rk12", "Adaptive Heun solver (Runge-Kutta 1+2)", LoadRK12)
}
// Take one time step
func (s *RK12Solver) Step() {
e := GetEngine()
equation := e.equation
// First update all inputs
for i := range equation {
Assert(equation[i].kind == EQN_PDE1)
equation[i].input[0].Update()
}
// Then step all outputs
// and invalidate them.
// stage 0
t0 := e.time.Scalar()
for i := range equation {
y := equation[i].output[0]
dy := equation[i].input[0]
dyMul := dy.multiplier
checkUniform(dyMul)
s.dybuffer[i].CopyFromDevice(dy.Array()) // save for later
s.y0buffer[i].CopyFromDevice(y.Array()) // save for later
}
const maxTry = 10 // undo at most this many bad steps
const headRoom = 0.8
try := 0
for {
// We need to update timestep if the step has failed
dt := engine.dt.Scalar()
// initial euler step
for i := range equation {
y := equation[i].output[0]
dy := equation[i].input[0]
dyMul := dy.multiplier
if try > 0 { // restore previous initial conditions
y.Array().CopyFromDevice(s.y0buffer[i])
dy.Array().CopyFromDevice(s.dybuffer[i])
}
gpu.Madd(y.Array(), y.Array(), dy.Array(), dt*dyMul[0])
y.Invalidate()
}
// Advance time
e.time.SetScalar(t0 + dt)
// update inputs again
for i := range equation {
equation[i].input[0].Update()
}
// stage 1
badStep := false
minFactor := 2.0
for i := range equation {
y := equation[i].output[0]
dy := equation[i].input[0]
dyMul := dy.multiplier
h := float64(dt * dyMul[0])
gpu.MAdd2Async(y.Array(), dy.Array(), 0.5*h, s.dybuffer[i], -0.5*h, y.Array().Stream) // corrected step
y.Array().Sync()
// error estimate
stepDiff := s.diff[i].MaxDiff(dy.Array(), s.dybuffer[i]) * h
err := float64(stepDiff)
s.err[i].SetScalar(err)
maxErr := s.maxErr[i].Scalar()
if err > maxErr {
s.badSteps.SetScalar(s.badSteps.Scalar() + 1)
badStep = true
}
if (!badStep || try == maxTry-1) && err > s.peakErr[i].Scalar() {
// peak error should be that of good step, unless last trial which will not be undone
s.peakErr[i].SetScalar(err)
}
factor := 0.0
if !badStep {
factor = math.Sqrt(maxErr / err) //maxErr / err
} else {
factor = math.Pow(maxErr/err, 1./3.)
}
factor *= headRoom
// do not increase/cut too much
// TODO: give user the control:
if factor > 1.5 {
factor = 1.5
}
if factor < 0.1 {
factor = 0.1
}
if factor < minFactor {
minFactor = factor
} // take minimum time increase factor of all eqns.
y.Invalidate()
//if badStep{break} // do not waste time on other equations
}
// Set new time step but do not go beyond min/max bounds
newDt := dt * minFactor
if newDt < s.minDt.Scalar() {
newDt = s.minDt.Scalar()
}
if newDt > s.maxDt.Scalar() {
newDt = s.maxDt.Scalar()
}
e.dt.SetScalar(newDt)
if !badStep || newDt == s.minDt.Scalar() {
break
}
if try > maxTry {
panic(Bug(fmt.Sprint("The solver cannot converge after ",maxTry," badsteps")))
}
try++
} // end try
// advance time step
e.step.SetScalar(e.step.Scalar() + 1)
}
|
godsic/hotspin
|
src/hotspin-core/engine/solve_rk12.go
|
GO
|
gpl-3.0
| 6,115
|
package ch.chrummibei.silvercoin.universe.entity_systems;
import ch.chrummibei.silvercoin.universe.components.BigSpenderComponent;
import ch.chrummibei.silvercoin.universe.components.TradeSphereComponent;
import ch.chrummibei.silvercoin.universe.components.TraderComponent;
import ch.chrummibei.silvercoin.universe.components.WalletComponent;
import ch.chrummibei.silvercoin.universe.trade.TradeOffer;
import com.badlogic.ashley.core.Entity;
import com.badlogic.ashley.core.Family;
import com.badlogic.ashley.systems.IteratingSystem;
/**
* Created by brachiel on 21/02/2017.
*/
public class BigSpenderSystem extends IteratingSystem {
private static Family family = Family.all(
BigSpenderComponent.class,
TradeSphereComponent.class,
TraderComponent.class,
WalletComponent.class).get();
public BigSpenderSystem() {
super(family);
}
public BigSpenderSystem(int priority) {
super(family, priority);
}
@Override
protected void processEntity(Entity entity, float deltaTime) {
BigSpenderComponent bigSpender = Mappers.bigSpender.get(entity);
bigSpender.timeReservoir += deltaTime;
buyItems(entity);
}
public static boolean buyItems(Entity entity) {
BigSpenderComponent bigSpender = Mappers.bigSpender.get(entity);
TradeSphereComponent tradeSphere = Mappers.tradeSphere.get(entity);
WalletComponent wallet = Mappers.wallet.get(entity);
int itemsToBuy = (int) Math.floor(bigSpender.timeReservoir / bigSpender.consumptionTime);
if (itemsToBuy == 0) {
return false;
}
TradeOffer.searchTradeOffersToTradeAmount(
tradeSphere.getAllTrades(),
bigSpender.itemToConsume,
TradeOffer.TYPE.SELLING,
itemsToBuy)
.forEach((offer, amount) -> {
// Generate money for the BigSpender out of nothing
wallet.credit.iAdd(offer.getPrice().toTotalValue(amount));
offer.accept(entity, amount);
});
return true;
}
}
|
brachiel/SilverCoin
|
core/src/ch/chrummibei/silvercoin/universe/entity_systems/BigSpenderSystem.java
|
Java
|
gpl-3.0
| 2,135
|
#include <cstdio>
struct {
int lower_limit, upper_limit;
char letter;
bool contain(int arg) {
return arg>=lower_limit && arg<=upper_limit;
}
} grade[5] = {{0,0,'E'},
{1,35,'D'},
{36,60,'C'},
{61,85,'B'},
{86,100,'A'}};
int main() {
int n;
scanf(" %d", &n);
for(int i=0; i<5; ++i)
if(grade[i].contain(n))
printf("%c\n", grade[i].letter);
return 0;
}
|
pufe/aulinhas-spoj-br
|
2016/aula9/nota09/nota09.cpp
|
C++
|
gpl-3.0
| 437
|
/**
* \file IMP/flags.h
* \brief Various general useful macros for IMP.
*
* Copyright 2007-2017 IMP Inventors. All rights reserved.
*
*/
#ifndef IMPKERNEL_FLAGS_H
#define IMPKERNEL_FLAGS_H
#include <IMP/kernel_config.h>
#include <boost/cstdint.hpp>
#include "types.h"
#include <string>
IMPKERNEL_BEGIN_NAMESPACE
/** \name Flags
These methods add support for shared command
line flags to \imp. Programs that use this have access to flags
declared in modules which allow users to do things like control
log level and turn on and off profiling to see what is going on.
These functions are Python accessible.
In C++, you can also use the AddFloatFlag, AddStringFlag,
AddBoolFlag and AddIntFlag classes to add flags statically. @{
*/
//! Return the name of the current executable.
IMPKERNELEXPORT std::string get_executable_name();
#ifndef SWIG
//! Parse the command line flags and return the positional arguments.
/**
\param[in] argc argc
\param[in] argv argv
\param[in] description A message describing what the program does.
\throws UsageException if a problem with the command line was found.
*/
IMPKERNELEXPORT void setup_from_argv(int argc, char **argv,
std::string description);
/** Parse the command line flags and return the
positional arguments returning unknown flags in a list. Use this version
if some arguments are to be parsed by a different system.
\param[in] argc argc
\param[in] argv argv
\param[in] description A message describing what the program does.
\throws UsageException if a problem with the command line was found.
*/
IMPKERNELEXPORT Strings setup_from_argv_allowing_unknown(int argc, char **argv,
std::string description);
/** Parse the command line flags and return the
positional arguments.
\param[in] argc argc
\param[in] argv argv
\param[in] description A message describing what the program does.
\param[in] positional_description A message describing the the
positional arguments
\param[in] num_positional A positive integer to require that
many positional arguments, or a negative integer to require at
least that many.
\throws UsageException if a problem with the command line was found.
*/
IMPKERNELEXPORT Strings
setup_from_argv(int argc, char **argv, std::string description,
std::string positional_description, int num_positional);
#endif
/** Parse the command line flags and return the
positional arguments. For Python.
\param[in] argv sys.argv
\param[in] description A message describing what the program does.
\throws UsageException if a problem with the command line was found.
*/
IMPKERNELEXPORT void setup_from_argv(const Strings &argv,
std::string description);
/** Parse the command line flags and return the
positional arguments. For Python.
\param[in] argv sys.argv
\param[in] description A message describing what the program does.
\param[in] positional_description A message describing the positional
arguments, eg "input.pdb output.pdb"
\param[in] num_positional A positive integer to require that
many positional arguments, or a negative integer to require at
least that many.
\throws UsageException if a problem with the command line was found.
*/
IMPKERNELEXPORT Strings
setup_from_argv(const Strings &argv, std::string description,
std::string positional_description, int num_positional);
#ifndef SWIG
/** Define one of these in C++ to add a new int flag storing
into the passed variable.
\note You should consider using Flag<std::string> instead.
*/
struct IMPKERNELEXPORT AddStringFlag {
AddStringFlag(std::string name, std::string description,
std::string *storage);
};
#endif
/** For Python use.*/
IMPKERNELEXPORT void add_string_flag(std::string name, std::string default_value,
std::string description);
/** For Python use.*/
IMPKERNELEXPORT std::string get_string_flag(std::string name);
#ifndef SWIG
/** Define one of these in C++ to add a new boost::int64_t flag storing
into the passed variable.
\note You should consider using Flag<boost::int64_t> instead.
*/
struct IMPKERNELEXPORT AddIntFlag {
AddIntFlag(std::string name, std::string description,
boost::int64_t *storage);
};
#endif
/** For Python use.*/
IMPKERNELEXPORT void add_int_flag(std::string name, size_t default_value,
std::string description);
/** For Python use.*/
IMPKERNELEXPORT size_t get_int_flag(std::string name);
#ifndef SWIG
/** Define one of these in C++ to add a new bool flag storing
into the passed variable.
\note You should consider using Flag<bool> instead.
*/
struct IMPKERNELEXPORT AddBoolFlag {
AddBoolFlag(std::string name, std::string description, bool *storage);
};
#endif
/** For Python use. Default is always false.*/
IMPKERNELEXPORT void add_bool_flag(std::string name, std::string description);
/** For Python use.*/
IMPKERNELEXPORT bool get_bool_flag(std::string name);
#ifndef SWIG
/** Define one of these in C++ to add a new float flag storing
into the passed variable.
\note You should consider using Flag<double> instead.
*/
struct IMPKERNELEXPORT AddFloatFlag {
AddFloatFlag(std::string name, std::string description, double *storage);
};
#endif
/** For Python use.*/
IMPKERNELEXPORT void add_float_flag(std::string name, double default_value,
std::string description);
/** For Python use.*/
IMPKERNELEXPORT double get_float_flag(std::string name);
/** @} */
/** Prints out the help message, useful if you have extra error checking
and the flags don't pass it.*/
IMPKERNELEXPORT void write_help(std::ostream &out = std::cerr);
#if !defined(SWIG) && !defined(IMP_DOXYGEN)
/* Exposing global variables through swig is kind of broken,
see issue #723. */
extern IMPKERNELEXPORT AdvancedFlag<bool> run_quick_test;
#endif
// defined in static.cpp
/** Executables can inspect this flag and when it is true, run a shorter,
simpler version of their code to just make sure things work.
*/
inline bool get_is_quick_test() { return run_quick_test; }
IMPKERNEL_END_NAMESPACE
#endif /* IMPKERNEL_FLAGS_H */
|
shanot/imp
|
modules/kernel/include/flags.h
|
C
|
gpl-3.0
| 6,429
|
/**
* Copyright (C) 2014 Román Ginés Martínez Ferrández <rgmf@riseup.net>
*
* This program (LibreSportGPS) 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 any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package es.rgmf.libresportgps.common;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import android.graphics.BitmapFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
/**
* Several utilities that can be used in all the application.
*
* @author Román Ginés Martínez Ferrández <rgmf@riseup.net>
*/
public class Utilities {
/**
* Uses the Haversine formula to calculate the distance between to latitude and longitude coordinates.
*
* Haversine formula:
* A = sin²(Δlat/2) + cos(lat1) . cos(lat2) . sin²(Δlong/2)
* C = 2 . atan2(√a, √(1−a))
* D = R . c
* R = radius of earth, 6371 km
*
* All angles are in radians.
*
* @param latitude1 The first point's latitude.
* @param longitude1 The first point's longitude.
* @param latitude2 The second point's latitude.
* @param longitude2 The second point's longitude.
* @return The distance between the two points in meters.
*/
public static double CalculateDistance(double latitude1, double longitude1, double latitude2, double longitude2) {
double deltaLatitude = Math.toRadians(Math.abs(latitude1 - latitude2));
double deltaLongitude = Math.toRadians(Math.abs(longitude1 - longitude2));
double latitude1Rad = Math.toRadians(latitude1);
double latitude2Rad = Math.toRadians(latitude2);
double a = Math.pow(Math.sin(deltaLatitude / 2), 2) +
(Math.cos(latitude1Rad) * Math.cos(latitude2Rad) * Math.pow(Math.sin(deltaLongitude / 2), 2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return 6371 * c * 1000;
}
/**
* @return The yyyy-MM-dd string today date.
*/
public static String todayString() {
Calendar calendar = Calendar.getInstance();
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
return formatter.format(calendar.getTime());
}
/**
* ISO 8601 format.
*
* Convert milliseconds to date in the String yyyy-MM-dd'T'hh:mm:ss.SSS'Z' format.
*
* @param milliseconds
* @return The string representation time or "0000-00-00'T'00:00:00.000'Z'" if error.
*/
public static String millisecondsToDateForGPX(long milliseconds) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliseconds);
return formatter.format(calendar.getTime());
}
/**
* ISO 8601 format.
*
* Return a time in ISO8601 format in milliseconds.
*
* Accept ISO8601 format with and without milliseconds:
* - yyyy-MM-dd'T'hh:mm:ss'Z'
* - yyyy-MM-dd'T'hh:mm:ss.SSS'Z'
*
* @param strDate The string representing a time.
* @return The milliseconds or 0 if raise and exception or strDate is not ok.
*/
public static Long getMillisecondsFromStringGPXDate(String strDate) {
DateFormat shortFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
DateFormat longFormatter = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss.SSS'Z'");
try {
if(strDate.length() == 20) {
return shortFormatter.parse(strDate).getTime();
}
else if(strDate.length() == 24) {
return longFormatter.parse(strDate).getTime();
}
else {
return 0L;
}
} catch (ParseException e) {
e.printStackTrace();
return 0L;
}
}
/**
* Return a yyyy-MM-dd date format.
*
* @param milliseconds
* @return The string representation date or "0000-00-00" if error.
*/
public static String millisecondsToDate(long milliseconds) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliseconds);
return formatter.format(calendar.getTime());
}
/**
* Convert the timeStamp in the String HH:mm:ss:SS
*
* @param timeStamp
* @return
*/
public static String timeStampFormatter(long timeStamp) {
if(timeStamp > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss.SS");
return formatter.format(timeStamp);
}
else
return "00:00:00.00";
}
/**
* Convert the timeStamp in the String HH:mm:ss
*
* @param timeStamp
* @return
*/
public static String timeStampSecondsFormatter(long timeStamp) {
if(timeStamp > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
return formatter.format(timeStamp);
}
else
return "00:00:00";
}
/**
* Convert the timeStamp to the String HH:mm:ss
*
* This method calculate the total time so this can be more than 24 hours so is not
* a time but a number of hours, minutes and seconds.
*
* @param timeStamp
* @return
*/
public static String totalTimeFormatter(long timeStamp) {
if(timeStamp > 0) {
long seconds, minutes, hours;
seconds = (timeStamp / 1000) % 60;
minutes = (timeStamp / 1000 / 60) % 60;
hours = (timeStamp / 1000 / 60 / 60);
if (hours > 0)
return String.format("%02d:%02d:%02d", hours, minutes, seconds);
else
return String.format("%02d:%02d", minutes, seconds);
}
else
return "00:00:00";
}
/**
* Convert the timeStamp in the String dd/MM/yyyy HH:mm:ss:SS
*
* @param timeStamp
* @return
*/
public static String timeStampCompleteFormatter(long timeStamp) {
if(timeStamp > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
return formatter.format(timeStamp);
}
else
return "00/00/0000 00:00:00";
}
/**
* Convert the timeStamp in the String HH_mm_ss_SS
*
* @param timeStamp
* @return
*/
public static String timeStampFormatterForFilename(long timeStamp) {
if(timeStamp > 0) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
return formatter.format(timeStamp);
}
else
return "00000000_000000";
}
/**
* Convert milliseconds to hours and returns hours.
*
* @param millis
* @return
*/
public static long millisecondsToHours(long millis) {
if(millis == 0)
return 0;
return (millis / (1000 * 60 * 60)) % 24;
}
/**
* Return a string representing a distance.
*
* @param distance
* @return
*/
public static String distance(double distance) {
if (distance < 1000)
return String.format("%d m", (int) distance);
else
return String.format("%.2f km", distance / 1000d);
}
/**
* Return a string representing a gain.
*
* @param gain
* @return
*/
public static String gain(int gain) {
return String.format("%d m", gain);
}
/**
* Return a string representing an elevation.
*
* @param elevation
* @return
*/
public static String elevation(double elevation) {
return String.format("%.2f m", elevation);
}
/**
* Return a string representing the gradient.
*
* @param elevation
* @param distance
* @return
*/
public static String gradient(double elevation, double distance) {
double gradient = (100d * elevation) / distance;
return String.format("%.2f %%", gradient);
}
/**
* Return a string representing a speed.
*
* @param speed
* @return
*/
public static String speed(double speed) {
return String.format("%.2f km/h", speed);
}
/**
* Return an average speed with activityTime in milliseconds and distance
* in meters.
*
* @param activityTime The activity time in milliseconds.
* @param distance The distance in meters.
* @return km/h.
*/
public static String avgSpeed(long activityTime, float distance) {
float km = distance / ((float)1000);
float hour = ((float)activityTime) / ((float)1000) / ((float)60) / ((float)60);
return String.format("%.2f km/h", km/hour);
}
/**
* Return the tempo per km.
*
* @param distance Distance in meters.
* @param activityTime Time in milliseconds.
* @return
*/
public static String tempoPerKm(Float distance, Long activityTime) {
float km = distance / 1000;
float tempoMillis = ((float) activityTime) / km;
long seconds = (long) ((tempoMillis / 1000) % 60);
long minutes = (long) ((tempoMillis / 1000 / 60) % 60);
return String.format("%02d:%02d min/km", minutes, seconds);
}
/**
*
* @param options
* @param reqWidth
* @param reqHeight
* @return
*/
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
/**
* Return a complete name of the month String.
*
* @param m number of the Calendar month.
* @return
*/
public static String getNameOfCalendarMonth(int m) {
Calendar cal = Calendar.getInstance();
// We need to subtract 1 because Calendar begin by 0 (January).
cal.set(Calendar.MONTH, m - 1);
return cal.getDisplayName(Calendar.MONTH, Calendar.LONG, Locale.getDefault());
}
/**
* It loads an image and return the bitmap efficiently (see {@link https://developer.android.com/training/displaying-bitmaps/load-bitmap.html}.
*
* @param selectedImagePath
* @param i
* @param j
* @return
*/
/*
public static Bitmap loadBitmapEfficiently(String imagePath, int reqWidth, int reqHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
//BitmapFactory.decodeResource(getResources(), R.id.student_photo_input, options);
BitmapFactory.decodeFile(imagePath, options);
// Calculate inSampleSize
options.inSampleSize = Utilities.calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap photoBitmap = BitmapFactory.decodeFile(imagePath, options);
return photoBitmap;
}
*/
}
|
rgmf/libresportgps
|
app/src/main/java/es/rgmf/libresportgps/common/Utilities.java
|
Java
|
gpl-3.0
| 11,851
|
/*
SPDX-FileCopyrightText: 2008-2021 Graeme Gott <graeme@gottcode.org>
SPDX-License-Identifier: GPL-3.0-or-later
*/
#ifndef KAPOW_SESSION_MODEL_H
#define KAPOW_SESSION_MODEL_H
#include "session.h"
#include <QAbstractItemModel>
#include <QXmlStreamWriter>
class SessionModel : public QAbstractItemModel
{
Q_OBJECT
public:
explicit SessionModel(QObject* parent = nullptr);
QList<int> billedRows() const
{
return m_billed;
}
bool canBill() const
{
return !m_data.isEmpty() && !isBilled(m_data.size() - 1);
}
bool isBilled(int pos) const
{
return (!m_billed.isEmpty() && pos <= m_billed.last());
}
void fixConflict(const QDateTime& current_start, QDateTime& current_stop) const;
bool hasConflict(const QDateTime& current) const;
Session session(int pos) const
{
return m_data.value(pos);
}
void beginLoad();
void endLoad();
bool add(const QDateTime& start, const QDateTime& stop, const QString& task);
bool add(const Session& session);
bool edit(int row, const Session& session);
bool remove(int row);
void setBilled(int row, bool billed);
void setDecimalTotals(bool decimals);
void setMaximumDateTime(const QDateTime& max);
void toXml(QXmlStreamWriter& xml) const;
int rowCount(const QModelIndex& parent = QModelIndex()) const override;
int columnCount(const QModelIndex& parent = QModelIndex()) const override;
QVariant data(const QModelIndex& index, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex& index) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override;
QModelIndex index(int row, int column, const QModelIndex& parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex& child) const override;
bool setData(const QModelIndex& index, const QVariant& value, int role = Qt::EditRole) override;
signals:
void billedStatusChanged(bool billed);
private:
void updateTotals();
private:
QList<Session> m_data;
QList<int> m_billed;
QDateTime m_max_datetime;
bool m_decimals;
bool m_loaded;
};
#endif // KAPOW_SESSION_MODEL_H
|
gottcode/kapow
|
src/session_model.h
|
C
|
gpl-3.0
| 2,111
|
/// Copyright (c) 2012 Ecma International. All rights reserved.
/// Ecma International makes this code available under the terms and conditions set
/// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the
/// "Use Terms"). Any redistribution of this code must retain the above
/// copyright and this notice and otherwise comply with the Use Terms.
/**
* @path ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-200.js
* @description Object.getOwnPropertyDescriptor returns data desc (all false) for properties on built-ins (Number.POSITIVE_INFINITY)
*/
function testcase() {
var desc = Object.getOwnPropertyDescriptor(Number, "POSITIVE_INFINITY");
if (desc.writable === false &&
desc.enumerable === false &&
desc.configurable === false &&
desc.hasOwnProperty('get') === false &&
desc.hasOwnProperty('set') === false) {
return true;
}
}
runTestCase(testcase);
|
geminy/aidear
|
oss/qt/qt-everywhere-opensource-src-5.9.0/qtdeclarative/tests/auto/qml/ecmascripttests/test262/test/suite/ch15/15.2/15.2.3/15.2.3.3/15.2.3.3-4-200.js
|
JavaScript
|
gpl-3.0
| 913
|
# Copyright 2019-2020 by Christopher C. Little.
# This file is part of Abydos.
#
# Abydos 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.
#
# Abydos 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 Abydos. If not, see <http://www.gnu.org/licenses/>.
"""abydos.tests.distance.test_distance__token_distance.
This module contains unit tests for abydos.distance._TokenDistance
"""
import unittest
from collections import Counter
from abydos.distance import (
AverageLinkage,
DamerauLevenshtein,
Jaccard,
JaroWinkler,
SokalMichener,
)
from abydos.stats import ConfusionTable
from abydos.tokenizer import (
CharacterTokenizer,
QSkipgrams,
WhitespaceTokenizer,
)
class TokenDistanceTestCases(unittest.TestCase):
"""Test _TokenDistance functions.
abydos.distance._TokenDistance
"""
cmp_j_crisp = Jaccard(intersection_type='crisp')
cmp_j_soft = Jaccard(intersection_type='soft')
cmp_j_fuzzy = Jaccard(
intersection_type='fuzzy', metric=DamerauLevenshtein(), threshold=0.4
)
cmp_j_linkage = Jaccard(intersection_type='linkage')
def test_crisp_jaccard_sim(self):
"""Test abydos.distance.Jaccard.sim (crisp)."""
# Base cases
self.assertEqual(self.cmp_j_crisp.sim('', ''), 1.0)
self.assertEqual(self.cmp_j_crisp.sim('a', ''), 0.0)
self.assertEqual(self.cmp_j_crisp.sim('', 'a'), 0.0)
self.assertEqual(self.cmp_j_crisp.sim('abc', ''), 0.0)
self.assertEqual(self.cmp_j_crisp.sim('', 'abc'), 0.0)
self.assertEqual(self.cmp_j_crisp.sim('abc', 'abc'), 1.0)
self.assertEqual(self.cmp_j_crisp.sim('abcd', 'efgh'), 0.0)
self.assertAlmostEqual(
self.cmp_j_crisp.sim('Nigel', 'Niall'), 0.3333333333
)
self.assertAlmostEqual(
self.cmp_j_crisp.sim('Niall', 'Nigel'), 0.3333333333
)
self.assertAlmostEqual(
self.cmp_j_crisp.sim('Colin', 'Coiln'), 0.3333333333
)
self.assertAlmostEqual(
self.cmp_j_crisp.sim('Coiln', 'Colin'), 0.3333333333
)
self.assertAlmostEqual(
self.cmp_j_crisp.sim('ATCAACGAGT', 'AACGATTAG'), 0.5
)
def test_soft_jaccard_sim(self):
"""Test abydos.distance.Jaccard.sim (soft)."""
# Base cases
self.assertEqual(self.cmp_j_soft.sim('', ''), 1.0)
self.assertEqual(self.cmp_j_soft.sim('a', ''), 0.0)
self.assertEqual(self.cmp_j_soft.sim('', 'a'), 0.0)
self.assertEqual(self.cmp_j_soft.sim('abc', ''), 0.0)
self.assertEqual(self.cmp_j_soft.sim('', 'abc'), 0.0)
self.assertEqual(self.cmp_j_soft.sim('abc', 'abc'), 1.0)
self.assertAlmostEqual(self.cmp_j_soft.sim('abcd', 'efgh'), 0.11111111)
self.assertAlmostEqual(self.cmp_j_soft.sim('Nigel', 'Niall'), 0.5)
self.assertAlmostEqual(self.cmp_j_soft.sim('Niall', 'Nigel'), 0.5)
self.assertAlmostEqual(self.cmp_j_soft.sim('Colin', 'Coiln'), 0.6)
self.assertAlmostEqual(self.cmp_j_soft.sim('Coiln', 'Colin'), 0.6)
self.assertAlmostEqual(
self.cmp_j_soft.sim('ATCAACGAGT', 'AACGATTAG'), 0.68
)
self.assertAlmostEqual(
Jaccard(
intersection_type='soft', tokenizer=WhitespaceTokenizer()
).sim('junior system analyst', 'systems analyst'),
0.6190476190476191,
)
self.assertAlmostEqual(
Jaccard(
intersection_type='soft', tokenizer=WhitespaceTokenizer()
).sim('systems analyst', 'junior system analyst'),
0.6190476190476191,
)
with self.assertRaises(TypeError):
Jaccard(
intersection_type='soft',
metric=JaroWinkler(),
tokenizer=WhitespaceTokenizer(),
).sim('junior system analyst', 'systems analyst')
def test_fuzzy_jaccard_sim(self):
"""Test abydos.distance.Jaccard.sim (fuzzy)."""
# Base cases
self.assertEqual(self.cmp_j_fuzzy.sim('', ''), 1.0)
self.assertEqual(self.cmp_j_fuzzy.sim('a', ''), 0.0)
self.assertEqual(self.cmp_j_fuzzy.sim('', 'a'), 0.0)
self.assertEqual(self.cmp_j_fuzzy.sim('abc', ''), 0.0)
self.assertEqual(self.cmp_j_fuzzy.sim('', 'abc'), 0.0)
self.assertEqual(self.cmp_j_fuzzy.sim('abc', 'abc'), 1.0)
self.assertAlmostEqual(
self.cmp_j_fuzzy.sim('abcd', 'efgh'), 0.1111111111111111
)
self.assertAlmostEqual(self.cmp_j_fuzzy.sim('Nigel', 'Niall'), 0.5)
self.assertAlmostEqual(self.cmp_j_fuzzy.sim('Niall', 'Nigel'), 0.5)
self.assertAlmostEqual(self.cmp_j_fuzzy.sim('Colin', 'Coiln'), 0.6)
self.assertAlmostEqual(self.cmp_j_fuzzy.sim('Coiln', 'Colin'), 0.6)
self.assertAlmostEqual(
self.cmp_j_fuzzy.sim('ATCAACGAGT', 'AACGATTAG'), 0.68
)
self.assertEqual(sum(self.cmp_j_fuzzy._union().values()), 11.0)
self.assertAlmostEqual(
Jaccard(intersection_type='fuzzy').sim('synonym', 'antonym'),
0.3333333333333333,
)
def test_linkage_jaccard_sim(self):
"""Test abydos.distance.Jaccard.sim (group linkage)."""
# Base cases
self.assertEqual(self.cmp_j_linkage.sim('', ''), 1.0)
self.assertEqual(self.cmp_j_linkage.sim('a', ''), 0.0)
self.assertEqual(self.cmp_j_linkage.sim('', 'a'), 0.0)
self.assertEqual(self.cmp_j_linkage.sim('abc', ''), 0.0)
self.assertEqual(self.cmp_j_linkage.sim('', 'abc'), 0.0)
self.assertEqual(self.cmp_j_linkage.sim('abc', 'abc'), 1.0)
self.assertAlmostEqual(
self.cmp_j_linkage.sim('abcd', 'efgh'), 0.1111111111111111
)
self.assertAlmostEqual(self.cmp_j_linkage.sim('Nigel', 'Niall'), 0.5)
self.assertAlmostEqual(self.cmp_j_linkage.sim('Niall', 'Nigel'), 0.5)
self.assertAlmostEqual(self.cmp_j_linkage.sim('Colin', 'Coiln'), 0.6)
self.assertAlmostEqual(self.cmp_j_linkage.sim('Coiln', 'Colin'), 0.6)
self.assertAlmostEqual(
self.cmp_j_linkage.sim('ATCAACGAGT', 'AACGATTAG'), 0.68
)
self.assertAlmostEqual(
Jaccard(
intersection_type='linkage',
metric=JaroWinkler(),
threshold=0.2,
).sim('synonym', 'antonym'),
0.6,
)
def test_token_distance(self):
"""Test abydos.distance._TokenDistance members."""
self.assertAlmostEqual(
Jaccard(intersection_type='soft', alphabet=24).sim(
'ATCAACGAGT', 'AACGATTAG'
),
0.68,
)
self.assertAlmostEqual(
Jaccard(qval=1, alphabet='CGAT').sim('ATCAACGAGT', 'AACGATTAG'),
0.9,
)
self.assertAlmostEqual(
Jaccard(tokenizer=QSkipgrams(qval=3), alphabet='CGAT').sim(
'ATCAACGAGT', 'AACGATTAG'
),
0.6372795969773299,
)
self.assertAlmostEqual(
Jaccard(alphabet=None).sim('synonym', 'antonym'),
0.3333333333333333,
)
self.assertAlmostEqual(
Jaccard(tokenizer=QSkipgrams(qval=3)).sim('synonym', 'antonym'),
0.34146341463414637,
)
src_ctr = Counter({'a': 5, 'b': 2, 'c': 10})
tar_ctr = Counter({'a': 2, 'c': 1, 'd': 3, 'e': 12})
self.assertAlmostEqual(Jaccard().sim(src_ctr, tar_ctr), 0.09375)
self.assertAlmostEqual(
SokalMichener(normalizer='proportional').sim('synonym', 'antonym'),
0.984777917351113,
)
self.assertAlmostEqual(
SokalMichener(normalizer='log').sim('synonym', 'antonym'),
1.2385752469545532,
)
self.assertAlmostEqual(
SokalMichener(normalizer='exp', alphabet=0).sim(
'synonym', 'antonym'
),
3.221246147982545e18,
)
self.assertAlmostEqual(
SokalMichener(normalizer='laplace').sim('synonym', 'antonym'),
0.98856416772554,
)
self.assertAlmostEqual(
SokalMichener(normalizer='inverse').sim('synonym', 'antonym'),
197.95790155440417,
)
self.assertAlmostEqual(
SokalMichener(normalizer='complement').sim('synonym', 'antonym'),
1.0204081632653061,
)
self.assertAlmostEqual(
SokalMichener(normalizer='base case').sim('synonym', 'antonym'),
0.9897959183673469,
)
self.assertAlmostEqual(
SokalMichener().sim('synonym', 'antonym'), 0.9897959183673469
)
sm = SokalMichener()
sm._tokenize('synonym', 'antonym') # noqa: SF01
self.assertEqual(
sm._get_tokens(), # noqa: SF01
(
Counter(
{
'$s': 1,
'sy': 1,
'yn': 1,
'no': 1,
'on': 1,
'ny': 1,
'ym': 1,
'm#': 1,
}
),
Counter(
{
'$a': 1,
'an': 1,
'nt': 1,
'to': 1,
'on': 1,
'ny': 1,
'ym': 1,
'm#': 1,
}
),
),
)
self.assertEqual(sm._src_card(), 8) # noqa: SF01
self.assertEqual(sm._tar_card(), 8) # noqa: SF01
self.assertEqual(
sm._symmetric_difference(), # noqa: SF01
Counter(
{
'$s': 1,
'sy': 1,
'yn': 1,
'no': 1,
'$a': 1,
'an': 1,
'nt': 1,
'to': 1,
}
),
)
self.assertEqual(sm._symmetric_difference_card(), 8) # noqa: SF01
self.assertEqual(sm._total_complement_card(), 772) # noqa: SF01
self.assertEqual(sm._population_card(), 788) # noqa: SF01
self.assertEqual(
sm._union(), # noqa: SF01
Counter(
{
'$s': 1,
'sy': 1,
'yn': 1,
'no': 1,
'on': 1,
'ny': 1,
'ym': 1,
'm#': 1,
'$a': 1,
'an': 1,
'nt': 1,
'to': 1,
}
),
)
self.assertEqual(sm._union_card(), 12) # noqa: SF01
self.assertEqual(
sm._difference(), # noqa: SF01
Counter(
{
'$s': 1,
'sy': 1,
'yn': 1,
'no': 1,
'on': 0,
'ny': 0,
'ym': 0,
'm#': 0,
'$a': -1,
'an': -1,
'nt': -1,
'to': -1,
}
),
)
self.assertEqual(
sm._intersection(), # noqa: SF01
Counter({'on': 1, 'ny': 1, 'ym': 1, 'm#': 1}),
)
self.assertEqual(
sm._get_confusion_table(), # noqa: SF01
ConfusionTable(tp=4, tn=772, fp=4, fn=4),
)
sm = SokalMichener(
alphabet=Counter({'C': 20, 'G': 20, 'A': 20, 'T': 20}), qval=1
)
sm._tokenize('ATCAACGAGT', 'AACGATTAG') # noqa: SF01
self.assertEqual(sm._total_complement_card(), 61) # noqa: SF01
self.assertAlmostEqual(
self.cmp_j_linkage.sim('abandonned', 'abandoned'),
0.9090909090909091,
)
self.assertAlmostEqual(
self.cmp_j_linkage.sim('abundacies', 'abundances'),
0.6923076923076923,
)
# Some additional constructors needed to complete test coverage
self.assertAlmostEqual(
Jaccard(alphabet=None, qval=range(2, 4)).sim('abc', 'abcd'),
0.42857142857142855,
)
self.assertAlmostEqual(
AverageLinkage(qval=range(2, 4)).sim('abc', 'abcd'),
0.22558922558922556,
)
self.assertAlmostEqual(
Jaccard(alphabet='abcdefghijklmnop', qval=range(2, 4)).sim(
'abc', 'abcd'
),
0.42857142857142855,
)
self.assertAlmostEqual(
Jaccard(
alphabet='abcdefghijklmnop', tokenizer=WhitespaceTokenizer()
).sim('abc', 'abcd'),
0.0,
)
self.assertAlmostEqual(
Jaccard(alphabet=list('abcdefghijklmnop')).sim('abc', 'abcd'), 0.5
)
self.assertAlmostEqual(
Jaccard(tokenizer=CharacterTokenizer()).sim('abc', 'abcd'), 0.75
)
cmp_j_soft = Jaccard(intersection_type='soft')
self.assertEqual(cmp_j_soft._src_card(), 0) # noqa: SF01
self.assertEqual(cmp_j_soft._tar_card(), 0) # noqa: SF01
self.assertEqual(cmp_j_soft._src_only(), Counter()) # noqa: SF01
self.assertEqual(cmp_j_soft._tar_only(), Counter()) # noqa: SF01
self.assertEqual(cmp_j_soft._total(), Counter()) # noqa: SF01
self.assertEqual(cmp_j_soft._union(), Counter()) # noqa: SF01
self.assertEqual(cmp_j_soft._difference(), Counter()) # noqa: SF01
cmp_j_soft.sim('abcd', 'abcde')
self.assertEqual(cmp_j_soft._src_card(), 5) # noqa: SF01
self.assertEqual(cmp_j_soft._tar_card(), 6) # noqa: SF01
self.assertEqual(
cmp_j_soft._src_only(), Counter({'#': 0.5}) # noqa: SF01
)
self.assertEqual(
cmp_j_soft._tar_only(), Counter({'e#': 1, 'e': 0.5}) # noqa: SF01
)
self.assertEqual(
cmp_j_soft._total(), # noqa: SF01
Counter(
{
'e#': 1,
'e': 0.5,
'#': 0.5,
'$a': 2,
'ab': 2,
'bc': 2,
'cd': 2,
'd': 1.0,
}
),
)
self.assertEqual(
cmp_j_soft._union(), # noqa: SF01
Counter(
{
'e#': 1,
'e': 0.5,
'#': 0.5,
'$a': 1,
'ab': 1,
'bc': 1,
'cd': 1,
'd': 0.5,
}
),
)
self.assertEqual(
cmp_j_soft._difference(), # noqa: SF01
Counter({'#': 0.5, 'e#': -1, 'e': -0.5}),
)
if __name__ == '__main__':
unittest.main()
|
chrislit/abydos
|
tests/distance/test_distance__token_distance.py
|
Python
|
gpl-3.0
| 15,537
|
/*
* Generated by class-dump 3.1.2.
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2007 by Steve Nygard.
*/
#import "_ABCreateStringWithAddressDictionary.h"
#import "NSURLConnectionDataDelegate-Protocol.h"
#import "SDWebImageOperation-Protocol.h"
@class NSMutableData, NSThread, NSURLConnection, NSURLCredential, NSURLRequest, NSURLResponse;
@interface SDWebImageDownloaderOperation : _ABCreateStringWithAddressDictionary <NSURLConnectionDataDelegate, SDWebImageOperation>
{
unsigned long width;
unsigned long height;
int orientation;
BOOL responseFromCached;
BOOL _executing;
BOOL _finished;
BOOL _shouldDecompressImages;
BOOL _shouldUseCredentialStorage;
NSURLRequest *_request;
NSURLCredential *_credential;
unsigned int _options;
int _expectedSize;
NSURLResponse *_response;
id _progressBlock;
id _completedBlock;
id _cancelBlock;
NSMutableData *_imageData;
NSURLConnection *_connection;
NSThread *_thread;
unsigned int _backgroundTaskId;
}
+ (int)orientationFromPropertyValue:(int)fp8;
- (void)setBackgroundTaskId:(unsigned int)fp8;
- (unsigned int)backgroundTaskId;
- (void)setThread:(id)fp8;
- (id)thread;
- (void)setConnection:(id)fp8;
- (id)connection;
- (void)setImageData:(id)fp8;
- (id)imageData;
- (void)setCancelBlock:(id)fp(null);
- (id)cancelBlock;
- (void)setCompletedBlock:(id)fp(null);
- (id)completedBlock;
- (void)setProgressBlock:(id)fp(null);
- (id)progressBlock;
- (void)setResponse:(id)fp8;
- (id)response;
- (void)setExpectedSize:(int)fp8;
- (int)expectedSize;
- (unsigned int)options;
- (void)setCredential:(id)fp8;
- (id)credential;
- (void)setShouldUseCredentialStorage:(BOOL)fp8;
- (BOOL)shouldUseCredentialStorage;
- (void)setShouldDecompressImages:(BOOL)fp8;
- (BOOL)shouldDecompressImages;
- (id)request;
- (BOOL)isFinished;
- (BOOL)isExecuting;
- (void).cxx_destruct;
- (void)connection:(id)fp8 willSendRequestForAuthenticationChallenge:(id)fp12;
- (BOOL)connectionShouldUseCredentialStorage:(id)fp8;
- (BOOL)shouldContinueWhenAppEntersBackground;
- (id)connection:(id)fp8 willCacheResponse:(id)fp12;
- (void)connection:(id)fp8 didFailWithError:(id)fp12;
- (void)connectionDidFinishLoading:(id)fp8;
- (id)scaledImageForKey:(id)fp8 image:(id)fp12;
- (void)connection:(id)fp8 didReceiveData:(id)fp12;
- (void)connection:(id)fp8 didReceiveResponse:(id)fp12;
- (BOOL)isConcurrent;
- (void)setExecuting:(BOOL)fp8;
- (void)setFinished:(BOOL)fp8;
- (void)reset;
- (void)done;
- (void)cancelInternal;
- (void)cancelInternalAndStop;
- (void)cancel;
- (void)start;
- (id)initWithRequest:(id)fp8 options:(unsigned int)fp12 progress:(id)fp(null) completed:(void)fp16 cancelled:(id)fp(null);
@end
|
f41c0r/TinderStats-iOS
|
theos/include/Tinder/SDWebImageDownloaderOperation.h
|
C
|
gpl-3.0
| 2,729
|
/**
* @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or http://ckeditor.com/license
*/
/**
* @fileOverview Defines the {@link CKEDITOR.lang} object, for the
* Catalan language.
*/
/**#@+
@type String
@example
*/
/**
* Contains the dictionary of language entries.
* @namespace
*/
CKEDITOR.lang[ 'ca' ] = {
// ARIA description.
editor: 'Editor de text enriquit',
// Common messages and labels.
common: {
// Screenreader titles. Please note that screenreaders are not always capable
// of reading non-English words. So be careful while translating it.
editorHelp: 'Premeu ALT 0 per ajuda',
browseServer: 'Veure servidor',
url: 'URL',
protocol: 'Protocol',
upload: 'Puja',
uploadSubmit: 'Envia-la al servidor',
image: 'Imatge',
flash: 'Flash',
form: 'Formulari',
checkbox: 'Casella de verificació',
radio: 'Botó d\'opció',
textField: 'Camp de text',
textarea: 'Àrea de text',
hiddenField: 'Camp ocult',
button: 'Botó',
select: 'Camp de selecció',
imageButton: 'Botó d\'imatge',
notSet: '<no definit>',
id: 'Id',
name: 'Nom',
langDir: 'Direcció de l\'idioma',
langDirLtr: 'D\'esquerra a dreta (LTR)',
langDirRtl: 'De dreta a esquerra (RTL)',
langCode: 'Codi d\'idioma',
longDescr: 'Descripció llarga de la URL',
cssClass: 'Classes del full d\'estil',
advisoryTitle: 'Títol consultiu',
cssStyle: 'Estil',
ok: 'D\'acord',
cancel: 'Cancel·la',
close: 'Tanca',
preview: 'Previsualitza',
resize: 'Arrossegueu per redimensionar',
generalTab: 'General',
advancedTab: 'Avançat',
validateNumberFailed: 'Aquest valor no és un número.',
confirmNewPage: 'Els canvis en aquest contingut que no es desin es perdran. Esteu segur que voleu carregar una pàgina nova?',
confirmCancel: 'Algunes opcions s\'han canviat. Esteu segur que voleu tancar el quadre de diàleg?',
options: 'Opcions',
target: 'Destí',
targetNew: 'Nova finestra (_blank)',
targetTop: 'Finestra superior (_top)',
targetSelf: 'Mateixa finestra (_self)',
targetParent: 'Finestra pare (_parent)',
langDirLTR: 'D\'esquerra a dreta (LTR)',
langDirRTL: 'De dreta a esquerra (RTL)',
styles: 'Estil',
cssClasses: 'Classes del full d\'estil',
width: 'Amplada',
height: 'Alçada',
align: 'Alineació',
alignLeft: 'Ajusta a l\'esquerra',
alignRight: 'Ajusta a la dreta',
alignCenter: 'Centre',
alignTop: 'Superior',
alignMiddle: 'Centre',
alignBottom: 'Inferior',
invalidValue : 'Valor no vàlid.',
invalidHeight: 'L\'alçada ha de ser un número.',
invalidWidth: 'L\'amplada ha de ser un número.',
invalidCssLength: 'El valor especificat per als "%1" camps ha de ser un número positiu amb o sense unitat de mesura vàlida de CSS (px, %, in, cm, mm, em, ex, pt o pc).',
invalidHtmlLength: 'El valor especificat per als "%1" camps ha de ser un número positiu amb o sense unitat de mesura vàlida d\'HTML (px o %).',
invalidInlineStyle: 'El valor especificat per l\'estil en línia ha de constar d\'una o més tuples amb el format "name: value", separats per punt i coma.',
cssLengthTooltip: 'Introduïu un número per un valor en píxels o un número amb una unitat vàlida de CSS (px, %, in, cm, mm, em, ex, pt o pc).',
// Put the voice-only part of the label in the span.
unavailable: '%1<span class="cke_accessibility">, no disponible</span>'
}
};
|
Ayahadhiie/Sistem-Konservasi-Energi
|
lang/ca.js
|
JavaScript
|
gpl-3.0
| 3,441
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Places</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body onload = "initialize();" >
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li class = "CurrentSection"><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="PlaceDetail">
<h3></h3>
<div id="summaryarea">
<table class="infolist place">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">P2954</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/f/f/d15f60b3aef7e4f03296baadeff.html">
Holman, Lionel
<span class="grampsid"> [451596308]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:40<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
RossGammon/the-gammons.net
|
RossFamilyTree/plc/e/1/d15f60b3b22685382d7eae9d41e.html
|
HTML
|
gpl-3.0
| 2,648
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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.GPLv3 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.
**
****************************************************************************/
#include "modelmerger.h"
#include "modelnode.h"
#include "abstractview.h"
#include "nodemetainfo.h"
#include "nodeproperty.h"
#include "nodelistproperty.h"
#include "bindingproperty.h"
#include "variantproperty.h"
#include "rewritertransaction.h"
#include <rewritingexception.h>
#include <QUrl>
#include <QDebug>
namespace QmlDesigner {
static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QString, QString> &idRenamingHash, AbstractView *view);
static QString fixExpression(const QString &expression, const QHash<QString, QString> &idRenamingHash)
{
QString newExpression = expression;
foreach (const QString &id, idRenamingHash.keys()) {
if (newExpression.contains(id))
newExpression = newExpression.replace(id, idRenamingHash.value(id));
}
return newExpression;
}
static void syncVariantProperties(ModelNode &outputNode, const ModelNode &inputNode)
{
foreach (const VariantProperty &variantProperty, inputNode.variantProperties()) {
outputNode.variantProperty(variantProperty.name()).setValue(variantProperty.value());
}
}
static void syncBindingProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
foreach (const BindingProperty &bindingProperty, inputNode.bindingProperties()) {
outputNode.bindingProperty(bindingProperty.name()).setExpression(fixExpression(bindingProperty.expression(), idRenamingHash));
}
}
static void syncId(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash)
{
if (!inputNode.id().isEmpty())
outputNode.setIdWithoutRefactoring(idRenamingHash.value(inputNode.id()));
}
static void splitIdInBaseNameAndNumber(const QString &id, QString *baseId, int *number)
{
int counter = 0;
while (counter < id.count()) {
bool canConvertToInteger = false;
int newNumber = id.right(counter +1).toInt(&canConvertToInteger);
if (canConvertToInteger)
*number = newNumber;
else
break;
counter++;
}
*baseId = id.left(id.count() - counter);
}
static void setupIdRenamingHash(const ModelNode &modelNode, QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const ModelNode &node, modelNode.allSubModelNodesAndThisNode()) {
if (!node.id().isEmpty()) {
QString newId = node.id();
QString baseId;
int number = 1;
splitIdInBaseNameAndNumber(newId, &baseId, &number);
while (view->hasId(newId) || idRenamingHash.values().contains(newId)) {
newId = baseId + QString::number(number);
number++;
}
idRenamingHash.insert(node.id(), newId);
}
}
}
static void syncNodeProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const NodeProperty &nodeProperty, inputNode.nodeProperties()) {
ModelNode newNode = createNodeFromNode(nodeProperty.modelNode(), idRenamingHash, view);
outputNode.nodeProperty(nodeProperty.name()).reparentHere(newNode);
}
}
static void syncNodeListProperties(ModelNode &outputNode, const ModelNode &inputNode, const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
foreach (const NodeListProperty &nodeListProperty, inputNode.nodeListProperties()) {
foreach (const ModelNode &node, nodeListProperty.toModelNodeList()) {
ModelNode newNode = createNodeFromNode(node, idRenamingHash, view);
outputNode.nodeListProperty(nodeListProperty.name()).reparentHere(newNode);
}
}
}
static ModelNode createNodeFromNode(const ModelNode &modelNode,const QHash<QString, QString> &idRenamingHash, AbstractView *view)
{
QList<QPair<PropertyName, QVariant> > propertyList;
QList<QPair<PropertyName, QVariant> > variantPropertyList;
foreach (const VariantProperty &variantProperty, modelNode.variantProperties()) {
propertyList.append(QPair<PropertyName, QVariant>(variantProperty.name(), variantProperty.value()));
}
NodeMetaInfo nodeMetaInfo = view->model()->metaInfo(modelNode.type());
ModelNode newNode(view->createModelNode(modelNode.type(), nodeMetaInfo.majorVersion(), nodeMetaInfo.minorVersion(),
propertyList, variantPropertyList, modelNode.nodeSource(), modelNode.nodeSourceType()));
syncBindingProperties(newNode, modelNode, idRenamingHash);
syncId(newNode, modelNode, idRenamingHash);
syncNodeProperties(newNode, modelNode, idRenamingHash, view);
syncNodeListProperties(newNode, modelNode, idRenamingHash, view);
return newNode;
}
ModelNode ModelMerger::insertModel(const ModelNode &modelNode)
{
RewriterTransaction transaction(view()->beginRewriterTransaction(QByteArrayLiteral("ModelMerger::insertModel")));
QList<Import> newImports;
foreach (const Import &import, modelNode.model()->imports()) {
if (!view()->model()->hasImport(import, true, true))
newImports.append(import);
}
view()->model()->changeImports(newImports, QList<Import>());
QHash<QString, QString> idRenamingHash;
setupIdRenamingHash(modelNode, idRenamingHash, view());
ModelNode newNode(createNodeFromNode(modelNode, idRenamingHash, view()));
return newNode;
}
void ModelMerger::replaceModel(const ModelNode &modelNode)
{
view()->model()->changeImports(modelNode.model()->imports(), QList<Import>());
view()->model()->setFileUrl(modelNode.model()->fileUrl());
try {
RewriterTransaction transaction(view()->beginRewriterTransaction(QByteArrayLiteral("ModelMerger::replaceModel")));
ModelNode rootNode(view()->rootModelNode());
foreach (const PropertyName &propertyName, rootNode.propertyNames())
rootNode.removeProperty(propertyName);
QHash<QString, QString> idRenamingHash;
setupIdRenamingHash(modelNode, idRenamingHash, view());
syncVariantProperties(rootNode, modelNode);
syncBindingProperties(rootNode, modelNode, idRenamingHash);
syncId(rootNode, modelNode, idRenamingHash);
syncNodeProperties(rootNode, modelNode, idRenamingHash, view());
syncNodeListProperties(rootNode, modelNode, idRenamingHash, view());
m_view->changeRootNodeType(modelNode.type(), modelNode.majorVersion(), modelNode.minorVersion());
} catch (const RewritingException &e) {
qWarning() << e.description(); //silent error
}
}
} //namespace QmlDesigner
|
frostasm/qt-creator
|
src/plugins/qmldesigner/designercore/model/modelmerger.cpp
|
C++
|
gpl-3.0
| 7,820
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>gSOAP WS-Security: Member List</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.4 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">gSOAP WS-Security <span id="projectnumber">2.8 Stable</span></div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="pages.html"><span>Related Pages</span></a></li>
<li class="current"><a href="annotated.html"><span>Classes</span></a></li>
<li><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="annotated.html"><span>Class List</span></a></li>
<li><a href="functions.html"><span>Class Members</span></a></li>
</ul>
</div>
</div>
<div class="header">
<div class="headertitle">
<div class="title">soap_wsse_session Member List</div> </div>
</div>
<div class="contents">
This is the complete list of members for <a class="el" href="structsoap__wsse__session.html">soap_wsse_session</a>, including all inherited members.<table>
<tr class="memlist"><td><a class="el" href="structsoap__wsse__session.html#a0f424c1e05edb26c5e20426b3ab34d07">expired</a></td><td><a class="el" href="structsoap__wsse__session.html">soap_wsse_session</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structsoap__wsse__session.html#a301e031f1ac51fabe097026c49449890">hash</a></td><td><a class="el" href="structsoap__wsse__session.html">soap_wsse_session</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structsoap__wsse__session.html#abb387e5a2cc5435a96493a22db6b0396">next</a></td><td><a class="el" href="structsoap__wsse__session.html">soap_wsse_session</a></td><td></td></tr>
<tr class="memlist"><td><a class="el" href="structsoap__wsse__session.html#a18dfb0e61192d68e306000db04aa4255">nonce</a></td><td><a class="el" href="structsoap__wsse__session.html">soap_wsse_session</a></td><td></td></tr>
</table></div>
<hr class="footer"/><address class="footer"><small>Generated on Sat Aug 18 2012 13:54:15 for gSOAP WS-Security by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.4 </small></address>
</body>
</html>
|
TangCheng/ionvif
|
gsoap-2.8/gsoap/doc/wsse/html/structsoap__wsse__session-members.html
|
HTML
|
gpl-3.0
| 2,805
|
package org.sapia.corus.processor;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Properties;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.sapia.corus.client.common.ArgMatchers;
import org.sapia.corus.client.common.json.JsonInput;
import org.sapia.corus.client.services.configurator.Configurator.PropertyScope;
import org.sapia.corus.client.services.configurator.Property;
import org.sapia.corus.client.services.database.DbMap;
import org.sapia.corus.client.services.database.DbModule;
import org.sapia.corus.client.services.database.RevId;
import org.sapia.corus.client.services.database.persistence.ClassDescriptor;
import org.sapia.corus.client.services.deployer.Deployer;
import org.sapia.corus.client.services.event.EventDispatcher;
import org.sapia.corus.client.services.http.HttpModule;
import org.sapia.corus.client.services.processor.ActivePort;
import org.sapia.corus.client.services.processor.DistributionInfo;
import org.sapia.corus.client.services.processor.ExecConfig;
import org.sapia.corus.client.services.processor.ExecConfigCriteria;
import org.sapia.corus.client.services.processor.ProcStatus;
import org.sapia.corus.client.services.processor.Process;
import org.sapia.corus.client.services.processor.ProcessCriteria;
import org.sapia.corus.client.services.processor.ProcessorConfiguration;
import org.sapia.corus.configurator.PropertyChangeEvent;
import org.sapia.corus.configurator.PropertyChangeEvent.EventType;
import org.sapia.corus.core.CorusConsts;
import org.sapia.corus.core.InternalServiceContext;
import org.sapia.corus.core.ServerContext;
import org.sapia.corus.database.InMemoryArchiver;
import org.sapia.corus.database.InMemoryDbMap;
import org.sapia.corus.interop.soap.message.Context;
import org.sapia.corus.interop.soap.message.Status;
import org.sapia.corus.processor.task.PublishConfigurationChangeTask;
import org.sapia.corus.taskmanager.core.TaskManager;
import org.sapia.corus.taskmanager.core.TaskParams;
import org.sapia.ubik.util.Func;
@RunWith(MockitoJUnitRunner.class)
public class ProcessorImplTest {
@Mock
private DbModule db;
@Mock
private ProcessorConfiguration conf;
@Mock
private Deployer deployer;
@Mock
private EventDispatcher events;
@Mock
private HttpModule httpModule;
@Mock
private ServerContext serverContext;
@Mock
private InternalServiceContext serviceContext;
@Mock
private TaskManager tm;
private ProcessorImpl processor;
private DbMap<String, ExecConfig> execConfigs;
private DbMap<String, Process> processes;
private Properties corusServerProperties;
@Before
public void setUp() throws Exception {
processor = new ProcessorImpl();
processor.setDb(db);
processor.setConfiguration(conf);
processor.setDeployer(deployer);
processor.setTaskManager(tm);
processor.setEvents(events);
processor.setHttpModule(httpModule);
processor.setServerContext(serverContext);
corusServerProperties = new Properties();
execConfigs = new InMemoryDbMap<String, ExecConfig>(new ClassDescriptor<ExecConfig>(ExecConfig.class), new InMemoryArchiver<String, ExecConfig>(), new Func<ExecConfig, JsonInput>() {
public ExecConfig call(JsonInput arg0) {
return ExecConfig.fromJson(arg0);
}
});
processes = new InMemoryDbMap<String, Process>(new ClassDescriptor<Process>(Process.class), new InMemoryArchiver<String, Process>(), new Func<Process, JsonInput>() {
public Process call(JsonInput arg0) {
return Process.fromJson(arg0);
}
});
when(db.getDbMap(eq(String.class), eq(ExecConfig.class), anyString())).thenReturn(execConfigs);
when(db.getDbMap(eq(String.class), eq(Process.class), anyString())).thenReturn(processes);
when(serverContext.getServices()).thenReturn(serviceContext);
when(serviceContext.getTaskManager()).thenReturn(tm);
// when(tm.executeBackground(any(), any(), any());
when(serverContext.getCorusProperties()).thenReturn(corusServerProperties);
processor.init();
}
@Test
public void testSetExecConfigEnabled_true() {
execConfigs.put("test", conf("test"));
processor.setExecConfigEnabled(ExecConfigCriteria.builder().name("test").build(), true);
assertTrue(processor.getExecConfigs(ExecConfigCriteria.builder().all().build()).get(0).isEnabled());
}
@Test
public void testSetExecConfigEnabled_false() {
execConfigs.put("test", conf("test"));
processor.setExecConfigEnabled(ExecConfigCriteria.builder().name("test").build(), false);
assertFalse(processor.getExecConfigs(ExecConfigCriteria.builder().all().build()).get(0).isEnabled());
}
@Test
public void testAddExecConfig() {
processor.addExecConfig(conf("test"));
assertEquals(1, processor.getExecConfigs(ExecConfigCriteria.builder().all().build()).size());
}
@Test
public void testRemoveExecConfig() {
processor.addExecConfig(conf("test"));
processor.removeExecConfig(ExecConfigCriteria.builder().all().build());
assertEquals(0, processor.getExecConfigs(ExecConfigCriteria.builder().all().build()).size());
}
@Test
public void testGetProcess() throws Exception {
Process proc = proc("1");
processes.put(proc.getProcessID(), proc);
assertEquals(proc, processor.getProcess(proc.getProcessID()));
}
@Test
public void testGetProcesses() {
Process proc1 = proc("1");
Process proc2 = proc("2");
processes.put(proc1.getProcessID(), proc1);
processes.put(proc2.getProcessID(), proc2);
List<Process> results = processor.getProcesses(ProcessCriteria.builder()
.distribution(ArgMatchers.parse(proc1.getDistributionInfo().getName())).build());
assertEquals(1, results.size());
assertEquals(proc1, results.get(0));
}
@Test
public void testGetProcessesWithPorts() {
Process proc1 = proc("1");
Process proc2 = proc("2");
proc1.addActivePort(new ActivePort("test", 1));
processes.put(proc1.getProcessID(), proc1);
processes.put(proc2.getProcessID(), proc2);
List<Process> results = processor.getProcessesWithPorts();
assertEquals(1, results.size());
assertEquals(proc1, results.get(0));
}
@Test
public void testGetStatus() throws Exception {
Process proc = proc("1");
processes.put(proc.getProcessID(), proc);
proc.status(new Status.StatusBuilder()
.commandId("1")
.context(
new Context.ContextBuilder().name("testConext").build()
)
.build());
processor.getStatus(ProcessCriteria.builder().all());
}
@Test
public void testGetStatusFor() throws Exception {
Process proc = proc("1");
processes.put(proc.getProcessID(), proc);
proc.status(new Status());
ProcStatus status = processor.getStatusFor(proc.getProcessID());
assertNotNull(status);
}
@Test
public void testArchiveExecConfigs() {
ExecConfig conf = conf("test");
processor.addExecConfig(conf);
processor.archiveExecConfigs(RevId.valueOf("123"));
processor.removeExecConfig(ExecConfigCriteria.builder().all().build());
processor.unarchiveExecConfigs(RevId.valueOf("123"));
assertEquals(1, processor.getExecConfigs(ExecConfigCriteria.builder().all().build()).size());
}
private ExecConfig conf(String name) {
ExecConfig cfg = new ExecConfig();
cfg.setName(name);
return cfg;
}
private Process proc(String distSuffix) {
Process proc = new Process(new DistributionInfo("test-" + distSuffix, "v1", "prof", "proc"));
return proc;
}
@Test
public void testProcessConfigurationUpdate_defaultValueDisabled() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "false");
processor.start();
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isFalse();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_defaultValueActive() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true");
processor.start();
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isTrue();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_enabling() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "false");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.ADD, CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true", PropertyScope.SERVER);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isTrue();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_disabling() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.ADD, CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "false", PropertyScope.SERVER);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isFalse();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_deleteProcessProperty() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.REMOVE, CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "false", PropertyScope.SERVER);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isTrue();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_active_otherServerProperty() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.REMOVE, "corus.server.whatever", "flagala", PropertyScope.SERVER);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isTrue();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_active_processPropertyAdded() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.ADD, "client.custom.param1", "val1", PropertyScope.PROCESS);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isTrue();
assertTaskManagerExecutedConfigurationChangeTask(new Property[] { new Property("client.custom.param1", "val1") }, new Property[0]);
}
@Test
public void testProcessConfigurationUpdate_active_processPropertyRemoved() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "true");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.REMOVE, "client.custom.param1", "val1", "cat3", PropertyScope.PROCESS);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isTrue();
assertTaskManagerExecutedConfigurationChangeTask(new Property[0], new Property[] { new Property("client.custom.param1", "val1", "cat3") });
}
@Test
public void testProcessConfigurationUpdate_inactive_processPropertyAdded() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "false");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.ADD, "client.custom.param1", "val1", PropertyScope.PROCESS);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isFalse();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@Test
public void testProcessConfigurationUpdate_inactive_processPropertyRemoved() throws Exception {
corusServerProperties.setProperty(CorusConsts.PROPERTY_CORUS_PROCESS_CONFIG_UPDATE_ENABLED, "false");
processor.start();
PropertyChangeEvent event = new PropertyChangeEvent(EventType.REMOVE, "client.custom.param1", "val1", "cat3", PropertyScope.PROCESS);
processor.doHandlePropertyChangeEvent(event);
assertThat(processor.isPublishProcessConfigurationChangeEnabled()).isFalse();
assertTaskManagerDidntExecuteConfigurationChangeTask();
}
@SuppressWarnings("unchecked")
protected void assertTaskManagerDidntExecuteConfigurationChangeTask() {
verify(tm, never()).execute(any(PublishConfigurationChangeTask.class), any(TaskParams.class));
}
@SuppressWarnings({ "rawtypes", "unchecked" })
protected void assertTaskManagerExecutedConfigurationChangeTask(Property[] eAddedProperties, Property[] eRemovedProperties) {
ArgumentCaptor<TaskParams> taskParamCaptor = ArgumentCaptor.forClass(TaskParams.class);
verify(tm).execute(any(PublishConfigurationChangeTask.class), taskParamCaptor.capture());
TaskParams actualParams = taskParamCaptor.getValue();
assertThat((List<Property>) actualParams.getParam1()).containsOnly(eAddedProperties);
assertThat((List<Property>) actualParams.getParam2()).containsOnly(eRemovedProperties);
}
}
|
sapia-oss/corus
|
modules/server/src/test/java/org/sapia/corus/processor/ProcessorImplTest.java
|
Java
|
gpl-3.0
| 14,562
|
#!/usr/bin/env python
import sys
import re
"""Rewrite the doxygen \\file lines to have the full path to the file."""
def fix(filename):
contents = open(filename, "r").read()
contents = re.sub(
"\\\\file .*\\.h",
"\\\\file " + filename[len("build/include/"):],
contents,
1)
contents = re.sub(
"\\\\file .*/.*\\.h",
"\\\\file " + filename[len("build/include/"):],
contents,
1)
f = open(filename, "wr")
f.truncate()
f.write(contents)
if __name__ == '__main__':
for f in sys.argv[1:]:
fix(f)
|
shanot/imp
|
tools/maintenance/fix_doxygen_file_lines.py
|
Python
|
gpl-3.0
| 593
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<TITLE>AFL Match Statistics : Sydney defeats Collingwood at ANZ Stadium Round 1 Saturday, 26th March 2016</TITLE>
<meta NAME="description" CONTENT="Sydney defeats Collingwood at ANZ Stadium Round 1 Saturday, 26th March 2016 AFL match statistics">
<meta NAME="keywords" CONTENT="AFL Match Statistics, AFL Game Statistics, AFL Match Stats">
<link rel="canonical" href="https://www.footywire.com/afl/footy/ft_match_statistics?mid=6176&advv=Y"/>
<style>
.tabbg { background-color: #000077; vertical-align: middle; }
.blkbg { background-color: #000000; vertical-align: middle; }
.tabbdr { background-color: #d8dfea; vertical-align: middle; }
.wspace { background-color: #ffffff; vertical-align: middle; }
.greybg { background-color: #f4f5f1; }
.greybdr { background-color: #e3e4e0; }
.blackbdr { background-color: #000000; }
.lbgrey { background-color: #d4d5d1; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; font-weight: bold; }
.caprow { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; font-weight: bold; }
.ylwbg { background-color: #eeffee; text-decoration: none; color: #000000; vertical-align: middle; }
.ylwbgmid { background-color: #eeffee; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; }
.ylwbgtop { background-color: #eeffee; text-decoration: none; color: #000000; vertical-align: top; }
.ylwbgbottom { background-color: #eeffee; text-decoration: none; color: #000000; vertical-align: bottom; text-align: center; }
.ylwbg2 { background-color: #ddeedd; }
.ylwbdr { background-color: #ccddcc; }
.mtabbg { background-color: #f2f4f7; vertical-align: top; text-align: center; }
.error { background-color: #ffffff; text-decoration: none; color: #ff0000; vertical-align: middle; text-align: left; font-weight: bold; }
.cerror { background-color: #ffffff; text-decoration: none; color: #ff0000; vertical-align: middle; text-align: center; font-weight: bold; }
.greytxt { color: #777777; }
.bluetxt { color: #003399; }
.normtxt { color: #000000; }
.norm { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; }
.drow { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; }
.lnorm { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; }
.rnorm { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: right; }
.rdrow { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: middle; text-align: right; }
.ldrow { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; }
.bnorm { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; font-weight: bold; }
.rbnorm { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: right; font-weight: bold; }
.lbnorm { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; font-weight: bold; }
.bdrow { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; font-weight: bold; }
.lbdrow { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; font-weight: bold; }
.lylw { background-color: #eeffee; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; }
.normtop { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: top; text-align: center; }
.lnormtop { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: top; text-align: left; }
.drowtop { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: top; text-align: center; }
.ldrowtop { background-color: #f2f4f7; text-decoration: none; color: #000000; vertical-align: top; text-align: left; }
a.tblink:link {
color: #ffffff;
font-weight: bold;
vertical-align: middle;
}
.dvr { color: #999999; font-weight: normal; vertical-align: middle; }
.hltitle { text-decoration: none; color: #000000; font-size: 16px; font-weight: bold; }
.whltitle { background-color: #ffffff; text-decoration: none; color: #000000; font-size: 16px; font-weight: bold; }
.idxhltitle { text-decoration: none; color: #990099; font-size: 16px; font-weight: bold; }
.tbtitle {
text-decoration:none;
color:#3B5998;
font-weight:bold;
border-top:1px solid #e4ebf6;
border-bottom:1px solid #D8DFEA;
background:#D8DFEA url(/afl/img/icon/tbback.png); bottom left repeat-x;
}
.innertbtitle {
background-color:#D8DFEA;
text-decoration:none;
color:#3B5998;
font-weight:normal;
background:#D8DFEA url(/afl/img/icon/tbback.png); bottom left repeat-x;
}
.tabopt { background-color: #5555cc; vertical-align: middle; text-align: center; }
.tabsel { background-color: #ffffff; text-decoration: underline; color: #000000; font-weight: bold; vertical-align: middle; text-align: center; }
a.tablink {
font-weight:bold;
vertical-align:middle;
}
a.tablink:link { color: #ffffff; }
a.tablink:hover { color: #eeeeee; }
.lnitxt { }
.lseltxt { }
.lselbldtxt { font-weight: bold; }
.formcls { background-color:#f2f4f7; vertical-align:middle; text-align:left }
.formclsright { background-color:#f2f4f7; vertical-align:middle; text-align:right }
li { background-color: #ffffff; color: #000000; }
p { color: #000000; }
th { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; font-weight: bold; }
a.wire { font-weight:bold }
.menubg { background-color: #000077; text-decoration: none; color: #000000; vertical-align: middle; text-align: center; }
.menubdr { background-color: #f2f4f7; vertical-align: middle; }
table#wiretab {
border-spacing:0px;
border-collapse:collapse;
background-color:#F2F4F7;
width:450px;
height:250px;
}
table#wiretab td.section {
border-bottom:1px solid #D8DFEA;
}
table#wirecell {
background-color:#F2F4F7;
border:0px;
}
table#wirecell td#wirecelltitle {
vertical-align:top;
}
table#wirecell td#wirecellblurb {
vertical-align:top;
}
.smnt { background-color: #ffffff; text-decoration: none; color: #000000; vertical-align: middle; text-align: left; }
a.peep { font-weight:bold; font-size: 12px; line-height: 14px; }
form {
padding:0px;
margin:0px;
}
table.thickouter {
border:1px solid #D8DFEA;
}
table.thickouter td.padded {
padding:2px;
}
div.notice {
border:1px solid #D8DFEA;
padding:8px;
background:#D8DFEA url(/afl/img/icon/customback.png);
text-align:center;
vertical-align:middle;
margin-bottom:10px;
font-size: 12px;
}
div.notice div.clickable {
font-weight:bold;
cursor:pointer;
display:inline;
color:#3B5998;
}
div.datadiv td.data, div.datadiv td.bdata {
padding:3px;
vertical-align:top;
}
div.datadiv td.bdata {
font-weight:bold;
}
a:focus { outline:none; }
h1.centertitle {
padding-top:10px;
font-size:20px;
font-weight:bold;
text-align:center;
}
#matchscoretable {
background-color : #eeffee;
border:1px solid #ccddcc;
}
#matchscoretable td, #matchscoretable th {
background-color : #eeffee;
text-decoration: none;
color: #000000;
vertical-align: middle;
}
#matchscoretable th, #matchscoretable th.leftbold {
border-bottom:1px solid #ccddcc;
font-weight:bold;
}
#matchscoretable td.leftbold {
font-weight:bold;
}
#matchscoretable td.leftbold, #matchscoretable th.leftbold {
text-align:left;
padding-left:10px;
}
body {
margin-top:0px;
margin-bottom:5px;
margin-left:5px;
margin-right:5px;
background-color:#ffffff;
overflow-x: auto;
overflow-y: auto;
}
body, p, td, th, textarea, input, select, h1, h2, h3, h4, h5, h6 {
font-family: "lucida grande",tahoma,verdana,arial,sans-serif;
font-size:11px;
text-decoration: none;
}
table.plain {
border-spacing:0px;
border-collapse:collapse;
padding:0px;
}
table.leftmenu {
background-color:#F7F7F7;
}
table.leftmenu td {
padding:2px 2px 2px 5px;
}
table.leftmenu td#skyscraper {
padding:2px 0px 2px 0px;
text-align:left;
margin:auto;
vertical-align:top;
background-color:#ffffff;
}
table.leftmenu td#topborder {
padding:0px 0px 0px 0px;
border-top:5px solid #b7b7b7;
font-size:5px;
}
table.leftmenu td#bottomborder {
padding:0px 0px 0px 0px;
border-bottom:1px solid #b7b7b7;
font-size:5px;
}
table.leftmenu td#bottomborderpad {
padding:0px 0px 0px 0px;
border-bottom:0px solid #b7b7b7;
font-size:3px;
}
td#headercell {
text-align:left;
vertical-align:bottom;
background:#3B5998 url(/afl/img/logo/header-logo-bg-2011.png);
}
a.leftmenu {
color:#3B5998;
display:block;
width:100%;
text-decoration:none;
}
a.leftmenu:hover {
text-decoration:none;
}
a {
color:#3B5998;
}
a:link {
text-decoration:none;
}
a:visited {
text-decoration:none;
}
a:active {
text-decoration:none;
}
a:hover {
text-decoration:underline;
}
table#footer {
border-spacing:0px;
border-collapse:collapse;
padding:0px;
color:#868686;
width:760px;
}
table#footer td#footercopy {
text-align:left;
}
table#footer td#footerlinks {
text-align:right;
}
table#footer a {
padding:0px 2px 0px 2px;
}
.textinput {
border:1px solid #BDC7D8;
padding:2px 2px 2px 2px;
}
.button {
color:#ffffff;
height:18px;
padding:0px 4px 4px 4px;
border:1px solid #3B5998;
background:#5b79b8 url(/afl/img/icon/btback.png); bottom left repeat-x;
vertical-align:middle;
cursor:pointer;
}
.button:focus { outline:none; }
.button::-moz-focus-inner { border: 0; }
a.button:link, a.button:visited, a.button:hover {
text-decoration:none;
}
td.blocklink {
padding:3px 3px 3px 3px;
}
a.blocklink {
padding:2px 2px 2px 2px;
}
a.blocklink:hover {
background-color:#3B5998;
color:#ffffff;
text-decoration:none;
}
table#teammenu, table#playermenu, table#playerrankmenu, table#teamrankmenu,
table#draftmenu, table#risingstarmenu, table#matchmenu, table#laddermenu,
table#brownlowmenu, table#attendancemenu, table#coachmenu, table#supercoachmenu,
table#dreamteammenu, table#highlightsmenu, table#selectionsmenu, table#pastplayermenu,
table#tweetmenu, table#contractsmenu {
border-spacing:0px;
border-collapse:collapse;
background-color:#F7F7F7;
z-index:1;
position:absolute;
left:0px;
top:0px;
visibility:hidden;
border:1px solid #b7b7b7;
opacity:.95;
filter:alpha(opacity=95);
width:220px;
}
a.submenuitem {
padding:3px;
color:#3B5998;
text-decoration:none;
border:0px solid #3B5998;
}
a.submenuitem:link {
text-decoration:none;
}
a.submenuitem:hover {
text-decoration:underline;
}
div.submenux, div.submenutitle {
font-size:9px;
color:#676767;
font-weight:bold;
}
div.submenux {
color:#676767;
cursor:pointer;
}
div.submenutitle {
color:#353535;
padding:4px 2px 2px 2px;
}
td#teamArrow, td#playerArrow, td#playerrankArrow, td#teamrankArrow,
td#draftArrow, td#risingstarArrow, td#matchArrow, td#ladderArrow,
td#brownlowArrow, td#attendanceArrow, td#coachArrow, td#supercoachArrow,
td#dreamteamArrow, td#highlightsArrow, td#selectionsArrow, td#pastplayerArrow,
td#tweetArrow, td#contractsArrow {
color:#676767;
font-weight:bold;
display:block;
text-decoration:none;
border-left:1px solid #F7F7F7;
cursor:pointer;
text-align:center;
width:10px;
}
table#header {
border-spacing:0px;
border-collapse:collapse;
margin:auto;
width:100%;
}
table#header td {
border:0px solid #3B5998;
}
table#header td#logo {
vertical-align:middle;
text-align:center;
}
table#header td#mainlinks {
vertical-align:bottom;
text-align:left;
padding-bottom:10px;
}
table#header td#memberStatus {
vertical-align:bottom;
text-align:right;
padding-bottom:10px;
}
a.emptylink, a.emptylink:link, a.emptylink:visited, a.emptylink:active, a.emptylink:hover {
border:0px;
margin:0px;
text-decoration:none;
}
table#header a.headerlink {
font-size:12px;
font-weight:bold;
color:#ffffff;
padding:4px;
}
table#header a.headerlink:link {
background-color:#3B5998;
text-decoration:none;
}
table#header a.headerlink:visited {
background-color:#3B5998;
text-decoration:none;
}
table#header a.headerlink:active {
background-color:#3B5998;
text-decoration:none;
}
table#header a.headerlink:hover {
background-color:#6D84B4;
text-decoration:none;
}
table#header a.userlink {
font-size:11px;
font-weight:normal;
color:#D8DFEA;
padding:5px;
}
table#header a.userlink:link {
color:#D8DFEA;
text-decoration:none;
}
table#header a.userlink:visited {
color:#D8DFEA;
text-decoration:none;
}
table#header a.userlink:active {
color:#D8DFEA;
text-decoration:none;
}
table#header a.userlink:hover {
color:#ffffff;
text-decoration:underline;
}
table#header div#welcome {
display:inline;
font-size:11px;
font-weight:bold;
color:#D8DFEA;
padding:5px;
}
td.hdbar {
text-decoration:none;
border-top:1px solid #92201e;
border-bottom:1px solid #760402;
background:#D8DFEA url(/afl/img/icon/hdback.png); bottom left repeat-x;
padding:0px 5px 0px 5px;
}
td.hdbar div {
color:#ffffff;
display:inline;
padding:0px 5px 0px 5px;
}
td.hdbar div a {
font-size:11px;
font-weight:normal;
color:#ffffff;
font-weight:bold;
}
td.hdbar div a:link { text-decoration:none; }
td.hdbar div a:hover { text-decoration:underline; }
div#membersbgdiv {
background:#888888;
opacity:.50;
filter:alpha(opacity=50);
z-index:1;
position:absolute;
left:0px;
top:0px;
width:100%;
height:100%;
text-align:center;
vertical-align:middle;
display:none;
}
div#memberswhitediv {
width:610px;
height:380px;
border:3px solid #222222;
background:#ffffff;
opacity:1;
filter:alpha(opacity=100);
z-index:2;
position:absolute;
left:0;
top:0;
border-radius:20px;
-moz-border-radius:20px; /* Old Firefox */
padding:15px;
display:none;
}
#membersx {
color:#222222;
font-weight:bold;
font-size:16px;
cursor:pointer;
}
</style>
<script type="text/javascript">
function flipSubMenu(cellid, tableid) {
var table = document.getElementById(tableid);
if (table.style.visibility == 'visible') {
hideSubMenu(tableid);
}
else {
showSubMenu(cellid, tableid);
}
}
function showSubMenu(cellid, tableid) {
hideAllSubMenus();
var cell = document.getElementById(cellid);
var coors = findPos(cell);
var table = document.getElementById(tableid);
table.style.visibility = 'visible';
table.style.top = (coors[1]) + 'px';
table.style.left = (coors[0] + 175) + 'px';
}
function hideSubMenu(tableid) {
var table = document.getElementById(tableid);
if (table != null) {
table.style.visibility = 'hidden';
}
}
function findPos(obj) {
var curleft = curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
curtop = obj.offsetTop
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
curtop += obj.offsetTop
}
}
return [curleft,curtop];
}
function highlightCell(tag) {
var cell = document.getElementById(tag + 'linkcell');
cell.style.backgroundColor = "#E7E7E7";
highlightArrow(tag + 'Arrow');
}
function dehighlightCell(tag) {
var cell = document.getElementById(tag + 'linkcell');
cell.style.backgroundColor = "transparent";
dehighlightArrow(tag + 'Arrow');
}
function highlightArrow(arrowId) {
var arrow = document.getElementById(arrowId);
arrow.style.backgroundColor = "#E7E7E7";
}
function dehighlightArrow(arrowId) {
var arrow = document.getElementById(arrowId);
arrow.style.backgroundColor = "transparent";
}
function hideAllSubMenus() {
hideSubMenu('teammenu');
hideSubMenu('playermenu');
hideSubMenu('teamrankmenu');
hideSubMenu('playerrankmenu');
hideSubMenu('draftmenu');
hideSubMenu('risingstarmenu');
hideSubMenu('matchmenu');
hideSubMenu('brownlowmenu');
hideSubMenu('laddermenu');
hideSubMenu('attendancemenu');
hideSubMenu('supercoachmenu');
hideSubMenu('dreamteammenu');
hideSubMenu('coachmenu');
hideSubMenu('highlightsmenu');
hideSubMenu('selectionsmenu');
hideSubMenu('pastplayermenu');
hideSubMenu('contractsmenu');
hideSubMenu('tweetmenu');
}
function GetMemberStatusXmlHttpObject() {
var xmlMemberStatusHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlMemberStatusHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlMemberStatusHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlMemberStatusHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlMemberStatusHttp;
}
function rememberMember() {
xmlMemberStatusHttp=GetMemberStatusXmlHttpObject();
url="/club/sports/member-remember.html?sid=" + Math.random();
xmlMemberStatusHttp.onreadystatechange=showAlert;
xmlMemberStatusHttp.open("GET",url,true);
xmlMemberStatusHttp.send(null);
}
function quickLogout() {
xmlMemberStatusHttp=GetMemberStatusXmlHttpObject();
url="/afl/club/quick-logout.html?sid=" + Math.random();
xmlMemberStatusHttp.onreadystatechange=showAlert;
xmlMemberStatusHttp.open("GET",url,true);
xmlMemberStatusHttp.send(null);
}
function showMemberStatus() {
xmlMemberStatusHttp = GetMemberStatusXmlHttpObject();
url = "/afl/club/member-status.html?sid=" + Math.random();
fetchShowMemberStatus(xmlMemberStatusHttp, url);
}
function showMemberStatusWithUrl(url) {
xmlMemberStatusHttp = GetMemberStatusXmlHttpObject();
url = "/afl/club/member-status.html?url=" + url + "&sid=" + Math.random();
fetchShowMemberStatus(xmlMemberStatusHttp, url);
}
function showMemberStatusSkipAds() {
xmlMemberStatusHttp = GetMemberStatusXmlHttpObject();
url = "/afl/club/member-status.html?skipAds=Y&sid=" + Math.random();
fetchShowMemberStatus(xmlMemberStatusHttp, url);
}
function showMemberStatusWithUrlSkipAds(url) {
xmlMemberStatusHttp = GetMemberStatusXmlHttpObject();
url = "/afl/club/member-status.html?skipAds=Y&url=" + url + "&sid=" + Math.random();
fetchShowMemberStatus(xmlMemberStatusHttp, url);
}
function fetchShowMemberStatus(xmlMemberStatusHttp, url) {
xmlMemberStatusHttp.onreadystatechange = memberStatusChanged;
xmlMemberStatusHttp.open("GET", url, true);
xmlMemberStatusHttp.send(null);
}
function showAlert() {
if (xmlMemberStatusHttp.readyState==4) {
alertMessage = xmlMemberStatusHttp.responseText;
showMemberStatus();
alert(alertMessage);
}
}
function memberStatusChanged() {
if (xmlMemberStatusHttp.readyState==4) {
response = xmlMemberStatusHttp.responseText;
if (response.indexOf("<!-- MEMBER STATUS -->") < 0) {
response = " ";
}
document.getElementById("memberStatus").innerHTML = response;
}
}
function pushSignUpEvent(signUpSource) {
_gaq.push(['_trackEvent', 'Member Activity', 'Sign Up', signUpSource]);
}
function pushContent(category, page) {
_gaq.push(['_trackEvent', 'Content', category, page]);
}
function GetXmlHttpObject() {
var xmlWireHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlWireHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlWireHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlWireHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlWireHttp;
}
function showWire() {
xmlWireHttp=GetXmlHttpObject()
url="/afl/club/forum-threads-wire.html?sid=" + Math.random();
fetchWire(xmlWireHttp, url);
}
function showWireSkipAds() {
xmlWireHttp=GetXmlHttpObject()
url="/afl/club/forum-threads-wire.html?skipAds=Y&sid=" + Math.random();
fetchWire(xmlWireHttp, url);
}
function fetchWire(xmlWireHttp, url) {
xmlWireHttp.onreadystatechange = wireChanged;
xmlWireHttp.open("GET", url, true);
xmlWireHttp.send(null);
}
function wireChanged() {
if (xmlWireHttp.readyState==4) {
response = xmlWireHttp.responseText;
if (response.indexOf("<!-- WIRE -->") < 0) {
response = " ";
}
document.getElementById("threadsWire").innerHTML=response;
}
}
function positionMemberDivs() {
var bodyOffsetHeight = document.body.offsetHeight;
document.getElementById('membersbgdiv').style.width = '100%';
document.getElementById('membersbgdiv').style.height = '100%';
var leftOffset = (document.getElementById('membersbgdiv').offsetWidth - document.getElementById('memberswhitediv').offsetWidth) / 2;
var topOffset = ((document.getElementById('membersbgdiv').offsetHeight - document.getElementById('memberswhitediv').offsetHeight) / 2);
document.getElementById('memberswhitediv').style.left = leftOffset;
document.getElementById('memberswhitediv').style.top = topOffset;
document.getElementById('membersbgdiv').style.height = bodyOffsetHeight;
}
function closeMemberDivs() {
document.getElementById('membersbgdiv').style.display = 'none';
document.getElementById('memberswhitediv').style.display = 'none';
}
function displayMemberDivs() {
document.getElementById('membersbgdiv').style.display = 'block';
document.getElementById('memberswhitediv').style.display = 'block';
positionMemberDivs();
}
function openRegistrationLoginDialog() {
document.getElementById('memberscontent').innerHTML = "<iframe src='/afl/footy/custom_login' width=600 height=350 hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe>";
document.getElementById('memberswhitediv').style.width = '610px';
document.getElementById('memberswhitediv').style.height = '380px';
displayMemberDivs();
}
function openRegistrationLoginDialogWithNextPage(nextPage) {
document.getElementById('memberscontent').innerHTML = "<div><iframe src='/afl/footy/custom_login?p=" + nextPage + "' width=600 height=350 hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe></div>"
document.getElementById('memberswhitediv').style.width = '610px';
document.getElementById('memberswhitediv').style.height = '380px';
displayMemberDivs();
}
function openChangePasswordDialog() {
document.getElementById('memberscontent').innerHTML = "<div><iframe src='/afl/footy/custom_login?action=changePasswordForm' width=250 height=190 hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe></div>"
document.getElementById('memberswhitediv').style.width = '250px';
document.getElementById('memberswhitediv').style.height = '240px';
displayMemberDivs();
}
function openManageSettingsDialog() {
document.getElementById('memberscontent').innerHTML = "<div><iframe src='/afl/footy/custom_login?action=manageSettingsForm' width=380 height=210 hspace=0 vspace=0 frameborder=0 marginheight=0 marginwidth=0 scrolling=no></iframe></div>"
document.getElementById('memberswhitediv').style.width = '380px';
document.getElementById('memberswhitediv').style.height = '260px';
displayMemberDivs();
}
var xmlLoginHttp;
function GetLoginXmlHttpObject() {
var xmlLoginHttp=null;
try {
// Firefox, Opera 8.0+, Safari
xmlLoginHttp=new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlLoginHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlLoginHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlLoginHttp;
}
function postLogout() {
var params = "action=logout";
xmlLoginHttp=GetLoginXmlHttpObject();
xmlLoginHttp.onreadystatechange = validateLogoutResponse;
xmlLoginHttp.open("POST", '/afl/footy/custom_login', true);
xmlLoginHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlLoginHttp.setRequestHeader("Content-length", params.length);
xmlLoginHttp.setRequestHeader("Connection", "close");
xmlLoginHttp.send(params);
}
function getPlugContent(type) {
xmlLoginHttp=GetLoginXmlHttpObject()
xmlLoginHttp.onreadystatechange = plugCustomFantasy;
xmlLoginHttp.open("GET", '/afl/footy/custom_login?action=plug&type=' + type, true);
xmlLoginHttp.send(null);
}
function validateResponse() {
if(xmlLoginHttp.readyState == 4 && xmlLoginHttp.status == 200) {
var result = xmlLoginHttp.responseText;
if (result == 'PASS') {
self.parent.location.reload(true);
}
else if (result.indexOf('ERROR:') == 0) {
result = result.substring(6);
alert(result + ". Please try again.");
}
else {
alert("An error occurred during registration.");
}
}
}
function plugCustomFantasy() {
if (xmlLoginHttp.readyState == 4 && xmlLoginHttp.status == 200) {
var response = xmlLoginHttp.responseText;
if (response.indexOf("<!-- PLUG -->") < 0) {
response = "";
}
document.getElementById("customPlugDiv").innerHTML=response;
}
}
function validateLogoutResponse() {
if(xmlLoginHttp.readyState == 4 && xmlLoginHttp.status == 200) {
var result = xmlLoginHttp.responseText;
if (result == 'PASS') {
selfReload();
}
else if (result.indexOf('ERROR:') == 0) {
result = result.substring(6);
alert(result + ". Please try again.");
}
else {
alert("Oops! An error occurred!");
}
}
}
function selfReload() {
if (xmlLoginHttp.readyState == 4 && xmlLoginHttp.status == 200) {
self.parent.location.reload(true);
}
}
</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-3312858-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</HEAD>
<BODY onload="pushContent('Match Statistics', 'Match Statistics');showMemberStatusWithUrl('https%3A%2F%2Fwww.footywire.com%2Fafl%2Ffooty%2Fft_match_statistics');showWire();hideAllSubMenus();" onresize="positionMemberDivs();">
<DIV align="CENTER">
<table cellpadding="0" cellspacing="0" border="0" id="frametable2008" width="948">
<tr><td colspan="4" height="102" id="headercell" width="948">
<table id="header">
<tr>
<td id="logo" valign="middle" height="102" width="200">
<a class="emptylink" href="//www.footywire.com/"><div style="width:200px;height:54px;cursor:pointer;"> </div></a>
</td>
<td id="mainlinks" width="200">
</td>
<td style="padding-top:3px;padding-right:4px;">
<div style="margin-left:-3px;">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Footywire 728x90 Prime -->
<ins class="adsbygoogle"
style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-1151582373407200"
data-ad-slot="7204222137"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</td>
</tr>
</table>
</td></tr>
<tr><td colspan="4" height="21" class="hdbar" align="right" valign="middle" id="memberStatus"></td></tr>
<tr>
<td rowspan="4" width="175" valign="top">
<table width="175" cellpadding="0" cellspacing="0" border="0" class="leftmenu">
<tr><td colspan="2" id="topborder"> </td></tr>
<tr><td width="175" colspan="2" onMouseOver="this.style.backgroundColor='#e7e7e7';" onMouseOut="this.style.backgroundColor='transparent';"><a class="leftmenu" href="//www.footywire.com/">AFL Statistics Home</a></td></tr>
<tr>
<td id="matchlinkcell" width="165"><a onMouseOver="highlightCell('match')" onMouseOut="dehighlightCell('match')" class="leftmenu" href="/afl/footy/ft_match_list">AFL Fixture</a></td>
<td id="matchArrow" onMouseOver="highlightArrow('matchArrow')" onMouseOut="dehighlightArrow('matchArrow')" onClick="flipSubMenu('matchlinkcell','matchmenu')">»</td>
</tr>
<tr>
<td id="playerlinkcell" width="165"><a onMouseOver="highlightCell('player')" onMouseOut="dehighlightCell('player')" class="leftmenu" href="/afl/footy/ft_players">Players</a></td>
<td id="playerArrow" onMouseOver="highlightArrow('playerArrow')" onMouseOut="dehighlightArrow('playerArrow')" onClick="flipSubMenu('playerlinkcell','playermenu')">»</td>
</tr>
<tr>
<td id="teamlinkcell" width="165"><a onMouseOver="highlightCell('team')" onMouseOut="dehighlightCell('team')" class="leftmenu" href="/afl/footy/ft_teams">Teams</a></td>
<td id="teamArrow" onMouseOver="highlightArrow('teamArrow')" onMouseOut="dehighlightArrow('teamArrow')" onClick="flipSubMenu('teamlinkcell','teammenu')">»</td>
</tr>
<tr>
<td id="playerranklinkcell" width="165"><a onMouseOver="highlightCell('playerrank')" onMouseOut="dehighlightCell('playerrank')" class="leftmenu" href="/afl/footy/ft_player_rankings">Player Rankings</a></td>
<td id="playerrankArrow" onMouseOver="highlightArrow('playerrankArrow')" onMouseOut="dehighlightArrow('playerrankArrow')" onClick="flipSubMenu('playerranklinkcell','playerrankmenu')">»</td>
</tr>
<tr>
<td id="teamranklinkcell" width="165"><a onMouseOver="highlightCell('teamrank')" onMouseOut="dehighlightCell('teamrank')" class="leftmenu" href="/afl/footy/ft_team_rankings">Team Rankings</a></td>
<td id="teamrankArrow" onMouseOver="highlightArrow('teamrankArrow')" onMouseOut="dehighlightArrow('teamrankArrow')" onClick="flipSubMenu('teamranklinkcell','teamrankmenu')">»</td>
</tr>
<tr>
<td id="risingstarlinkcell" width="165"><a onMouseOver="highlightCell('risingstar')" onMouseOut="dehighlightCell('risingstar')" class="leftmenu" href="/afl/footy/ft_rising_stars_round_performances">Rising Stars</a></td>
<td id="risingstarArrow" onMouseOver="highlightArrow('risingstarArrow')" onMouseOut="dehighlightArrow('risingstarArrow')" onClick="flipSubMenu('risingstarlinkcell','risingstarmenu')">»</td>
</tr>
<tr>
<td id="draftlinkcell" width="165"><a onMouseOver="highlightCell('draft')" onMouseOut="dehighlightCell('draft')" class="leftmenu" href="/afl/footy/ft_drafts">AFL Draft</a></td>
<td id="draftArrow" onMouseOver="highlightArrow('draftArrow')" onMouseOut="dehighlightArrow('draftArrow')" onClick="flipSubMenu('draftlinkcell','draftmenu')">»</td>
</tr>
<tr>
<td id="brownlowlinkcell" width="165"><a onMouseOver="highlightCell('brownlow')" onMouseOut="dehighlightCell('brownlow')" class="leftmenu" href="/afl/footy/brownlow_medal">Brownlow Medal</a></td>
<td id="brownlowArrow" onMouseOver="highlightArrow('brownlowArrow')" onMouseOut="dehighlightArrow('brownlowArrow')" onClick="flipSubMenu('brownlowlinkcell','brownlowmenu')">»</td>
</tr>
<tr>
<td id="ladderlinkcell" width="165"><a onMouseOver="highlightCell('ladder')" onMouseOut="dehighlightCell('ladder')" class="leftmenu" href="/afl/footy/ft_ladder">AFL Ladder</a></td>
<td id="ladderArrow" onMouseOver="highlightArrow('ladderArrow')" onMouseOut="dehighlightArrow('ladderArrow')" onClick="flipSubMenu('ladderlinkcell','laddermenu')">»</td>
</tr>
<tr>
<td id="coachlinkcell" width="165"><a onMouseOver="highlightCell('coach')" onMouseOut="dehighlightCell('coach')" class="leftmenu" href="/afl/footy/afl_coaches">Coaches</a></td>
<td id="coachArrow" onMouseOver="highlightArrow('coachArrow')" onMouseOut="dehighlightArrow('coachArrow')" onClick="flipSubMenu('coachlinkcell','coachmenu')">»</td>
</tr>
<tr>
<td id="attendancelinkcell" width="165"><a onMouseOver="highlightCell('attendance')" onMouseOut="dehighlightCell('attendance')" class="leftmenu" href="/afl/footy/attendances">Attendances</a></td>
<td id="attendanceArrow" onMouseOver="highlightArrow('attendanceArrow')" onMouseOut="dehighlightArrow('attendanceArrow')" onClick="flipSubMenu('attendancelinkcell','attendancemenu')">»</td>
</tr>
<tr>
<td id="supercoachlinkcell" width="165"><a onMouseOver="highlightCell('supercoach')" onMouseOut="dehighlightCell('supercoach')" class="leftmenu" href="/afl/footy/supercoach_round">Supercoach</a></td>
<td id="supercoachArrow" onMouseOver="highlightArrow('supercoachArrow')" onMouseOut="dehighlightArrow('supercoachArrow')" onClick="flipSubMenu('supercoachlinkcell','supercoachmenu')">»</td>
</tr>
<tr>
<td id="dreamteamlinkcell" width="165"><a onMouseOver="highlightCell('dreamteam')" onMouseOut="dehighlightCell('dreamteam')" class="leftmenu" href="/afl/footy/dream_team_round">AFL Fantasy</a></td>
<td id="dreamteamArrow" onMouseOver="highlightArrow('dreamteamArrow')" onMouseOut="dehighlightArrow('dreamteamArrow')" onClick="flipSubMenu('dreamteamlinkcell','dreamteammenu')">»</td>
</tr>
<tr>
<td id="highlightslinkcell" width="165"><a onMouseOver="highlightCell('highlights')" onMouseOut="dehighlightCell('highlights')" class="leftmenu" href="/afl/footy/afl_highlights">AFL Highlights</a></td>
<td id="highlightsArrow" onMouseOver="highlightArrow('highlightsArrow')" onMouseOut="dehighlightArrow('highlightsArrow')" onClick="flipSubMenu('highlightslinkcell','highlightsmenu')">»</td>
</tr>
<tr>
<td id="selectionslinkcell" width="165"><a onMouseOver="highlightCell('selections')" onMouseOut="dehighlightCell('selections')" class="leftmenu" href="/afl/footy/afl_team_selections">AFL Team Selections</a></td>
<td id="selectionsArrow" onMouseOver="highlightArrow('selectionsArrow')" onMouseOut="dehighlightArrow('selectionsArrow')" onClick="flipSubMenu('selectionslinkcell','selectionsmenu')">»</td>
</tr>
<tr>
<td id="pastplayerlinkcell" width="165"><a onMouseOver="highlightCell('pastplayer')" onMouseOut="dehighlightCell('pastplayer')" class="leftmenu" href="/afl/footy/past_players">Past Players</a></td>
<td id="pastplayerArrow" onMouseOver="highlightArrow('pastplayerArrow')" onMouseOut="dehighlightArrow('pastplayerArrow')" onClick="flipSubMenu('pastplayerlinkcell','pastplayermenu')">»</td>
</tr>
<tr>
<td id="contractslinkcell" width="165"><a onMouseOver="highlightCell('contracts')" onMouseOut="dehighlightCell('contracts')" class="leftmenu" href="/afl/footy/out_of_contract_players">AFL Player Contracts</a></td>
<td id="contractsArrow" onMouseOver="highlightArrow('contractsArrow')" onMouseOut="dehighlightArrow('contractsArrow')" onClick="flipSubMenu('contractslinkcell','contractsmenu')">»</td>
</tr>
<tr><td width="175" colspan="2" onMouseOver="this.style.backgroundColor='#e7e7e7';" onMouseOut="this.style.backgroundColor='transparent';"><a class="leftmenu" href="/afl/footy/afl_betting">AFL Betting</a></td></tr>
<tr><td width="175" colspan="2" onMouseOver="this.style.backgroundColor='#e7e7e7';" onMouseOut="this.style.backgroundColor='transparent';"><a class="leftmenu" href="/afl/footy/injury_list">AFL Injury List</a></td></tr>
<tr><td width="175" colspan="2" onMouseOver="this.style.backgroundColor='#e7e7e7';" onMouseOut="this.style.backgroundColor='transparent';"><a class="leftmenu" href="/afl/footy/ft_season_records">Records</a></td></tr>
<tr><td colspan="2" id="bottomborder"> </td></tr>
<tr><td colspan="2" class="norm" style="height:10px"></td></tr>
<tr><td colspan="2" id="skyscraper">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Footywire 160x600 Prime -->
<ins class="adsbygoogle"
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-1151582373407200"
data-ad-slot="2707810136"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</td></tr>
</table>
</td>
<td rowspan="3" bgcolor="#b7b7b7" style="width:1px"></td>
<td height="900" width="761" valign="top" align="center" style="padding:5px 5px 5px 5px">
<div id="liveStatus" style="margin:0px;padding:0px;"></div>
<table border="0" cellspacing="0" cellpadding="0">
<tr><td>
<TABLE BORDER="0" CELLSPACING="0" CELLPADDING="0" WIDTH="760">
<TR>
<TD id="threadsWire" WIDTH="450" HEIGHT="250" VALIGN="TOP"> </TD>
<td rowspan="2" class="norm" style="width:10px"></td>
<TD WIDTH="300" HEIGHT="250" ROWSPAN="2">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Footywire 300x250 Prime -->
<ins class="adsbygoogle"
style="display:inline-block;width:300px;height:250px"
data-ad-client="ca-pub-1151582373407200"
data-ad-slot="4250755734"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</TD>
</TR>
</TABLE>
</td></tr>
<tr><td colspan="1" class="norm" style="height:10px"></td></tr>
<tr><td>
<div class="notice" width="760">
Advanced stats currently displayed. <a href="/afl/footy/ft_match_statistics?mid=6176"><b>View Basic Stats</b></a>.
</div>
</td></tr>
<tr><td>
<style>
td.statdata {
text-align:center;
cursor:default;
}
</style>
<script type="text/javascript">
function getStats() {
document.stat_select.submit();
}
</script>
<TABLE WIDTH="760" BORDER="0" CELLSPACING="0" CELLPADDING="0">
<TR><TD CLASS="lnormtop">
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="0" WIDTH="760">
<TR>
<TD WIDTH="375" class="lnormtop">
<table border="0" cellspacing="0" cellpadding="0" width="375">
<tr><td width="375" valign="top" height="22" align="left" class="hltitle">
Sydney defeats Collingwood
</td></tr>
<tr><td class="lnorm" height="15">Round 1, ANZ Stadium, Attendance: 33857</td></tr>
<tr><td class="lnorm" height="15">
Saturday, 26th March 2016, 7:25 PM AEDT</td></tr>
<tr><td class="lnorm" height="19" style="padding-top:4px;">
Sydney Betting Odds: Win 1.60, Line -10.5 @ 1.92
</td></tr>
<tr><td class="lnorm" height="19" style="padding-bottom:4px;">
Collingwood Betting Odds: Win 2.40, Line +10.5 @ 1.92
</td></tr>
<tr><td class="lnorm" height="15">
<b>Brownlow Votes:</b>
3: <a href="pp-sydney-swans--luke-parker">L Parker</a>, 2: <a href="pp-sydney-swans--tom-mitchell">T Mitchell</a>, 1: <a href="pp-sydney-swans--lance-franklin">L Franklin</a></td></tr>
</table>
</TD>
<td rowspan="1" class="norm" style="width:9px"></td>
<TD WIDTH="376" class="lnormtop">
<table border="0" cellspacing="0" cellpadding="0" width="376" id="matchscoretable">
<tr>
<th class="leftbold" height="23" width="100">Team</td>
<th width="49" align="center">Q1</td>
<th width="49" align="center">Q2</td>
<th width="49" align="center">Q3</td>
<th width="49" align="center">Q4</td>
<th width="49" align="center">Final</td>
</tr>
<tr>
<td class="leftbold" height="22"><a href="th-sydney-swans">Sydney</a></td>
<td align="center">3.9
<td align="center">10.12
<td align="center">14.21
<td align="center">18.25
<td align="center">133
</tr>
<tr>
<td class="leftbold" height="22"><a href="th-collingwood-magpies">Collingwood</a></td>
<td align="center">1.1
<td align="center">1.4
<td align="center">5.6
<td align="center">7.11
<td align="center">53
</tr>
</table>
</TD></TR>
<TR><TD COLSPAN="3" HEIGHT="30" CLASS="norm">
<a href="#t1">Sydney Player Stats</a> |
<a href="#t2">Collingwood Player Stats</a> |
<a href="#hd">Match Head to Head Stats</a> |
<a href="#brk">Scoring Breakdown</a>
| <a href="highlights?id=1347">Highlights</a>
</TD></TR>
</TABLE></TD></TR>
<tr><td colspan="1" class="norm" style="height:5px"></td></tr>
<TR><TD>
<table border="0" cellspacing="0" cellpadding="0" width="760">
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="585">
<tr>
<td height="21" align="center" colspan="3" class="tbtitle" width="585">
<table border="0" cellspacing="0" cellpadding="0" width="585">
<tr>
<td class="innertbtitle" align="left"> <b><a name=t1></a>Sydney Match Statistics (Sorted by Disposals)</b></td>
<td class="innertbtitle" align="right">Coach: <a href="cp-john-longmire--81">John Longmire</a> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td rowspan="1" class="tabbdr" style="width:1px"></td>
<td>
<table border="0" cellspacing="0" cellpadding="3" width="583">
<tr>
<td width="148" class="lbnorm" height="21">Player</td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=23&advv=Y#t1" title="Contested Possessions">CP</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=24&advv=Y#t1" title="Uncontested Possessions">UP</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=25&advv=Y#t1" title="Effective Disposals">ED</a></td>
<td width="34" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=34&advv=Y#t1" title="Disposal Efficiency %">DE%</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=27&advv=Y#t1" title="Contested Marks">CM</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=21&advv=Y#t1" title="Goal Assists">GA</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=28&advv=Y#t1" title="Marks Inside 50">MI5</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=31&advv=Y#t1" title="One Percenters">1%</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=32&advv=Y#t1" title="Bounces">BO</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=35&advv=Y#t1" title="Centre Clearances">CCL</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=36&advv=Y#t1" title="Stoppage Clearances">SCL</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=37&advv=Y#t1" title="Score Involvements">SI</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=38&advv=Y#t1" title="Metres Gained">MG</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=39&advv=Y#t1" title="Turnovers">TO</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=40&advv=Y#t1" title="Intercepts">ITC</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=41&advv=Y#t1" title="Tackles Inside 50">T5</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=42&advv=Y#t1" title="Time On Ground %">TOG%</a></td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--luke-parker" title="Luke Parker">L Parker</a></td>
<td class="statdata">20</td>
<td class="statdata">21</td>
<td class="statdata">32</td>
<td class="statdata">80</td>
<td class="statdata">3</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">3</td>
<td class="statdata">12</td>
<td class="statdata">231</td>
<td class="statdata">5</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">88</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--kieran-jack" title="Kieren Jack">K Jack</a></td>
<td class="statdata">16</td>
<td class="statdata">19</td>
<td class="statdata">22</td>
<td class="statdata">62.9</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">16</td>
<td class="statdata">632</td>
<td class="statdata">6</td>
<td class="statdata">8</td>
<td class="statdata">2</td>
<td class="statdata">78</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--jake-lloyd" title="Jake Lloyd">J Lloyd</a></td>
<td class="statdata">11</td>
<td class="statdata">26</td>
<td class="statdata">25</td>
<td class="statdata">71.4</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">12</td>
<td class="statdata">551</td>
<td class="statdata">6</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">82</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-hawthorn-hawks--tom-mitchell" title="Tom Mitchell">T Mitchell</a></td>
<td class="statdata">9</td>
<td class="statdata">21</td>
<td class="statdata">18</td>
<td class="statdata">60</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">8</td>
<td class="statdata">325</td>
<td class="statdata">3</td>
<td class="statdata">3</td>
<td class="statdata">3</td>
<td class="statdata">73</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--josh-p--kennedy" title="Josh Kennedy">J Kennedy</a></td>
<td class="statdata">15</td>
<td class="statdata">10</td>
<td class="statdata">17</td>
<td class="statdata">73.9</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">8</td>
<td class="statdata">1</td>
<td class="statdata">11</td>
<td class="statdata">164</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">84</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--isaac-heeney" title="Isaac Heeney">I Heeney</a></td>
<td class="statdata">9</td>
<td class="statdata">14</td>
<td class="statdata">15</td>
<td class="statdata">65.2</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">11</td>
<td class="statdata">242</td>
<td class="statdata">3</td>
<td class="statdata">4</td>
<td class="statdata">1</td>
<td class="statdata">82</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--daniel-hannebery" title="Daniel Hannebery">D Hannebery</a></td>
<td class="statdata">13</td>
<td class="statdata">7</td>
<td class="statdata">16</td>
<td class="statdata">76.2</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">3</td>
<td class="statdata">8</td>
<td class="statdata">191</td>
<td class="statdata">1</td>
<td class="statdata">5</td>
<td class="statdata">0</td>
<td class="statdata">50</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--heath-grundy" title="Heath Grundy">H Grundy</a></td>
<td class="statdata">6</td>
<td class="statdata">13</td>
<td class="statdata">15</td>
<td class="statdata">78.9</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">5</td>
<td class="statdata">251</td>
<td class="statdata">4</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">100</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--dean-towers" title="Dean Towers">D Towers</a></td>
<td class="statdata">9</td>
<td class="statdata">10</td>
<td class="statdata">15</td>
<td class="statdata">78.9</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">6</td>
<td class="statdata">296</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">1</td>
<td class="statdata">82</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--lance-franklin" title="Lance Franklin">L Franklin</a></td>
<td class="statdata">6</td>
<td class="statdata">13</td>
<td class="statdata">12</td>
<td class="statdata">66.7</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">9</td>
<td class="statdata">387</td>
<td class="statdata">7</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">87</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--callum-mills" title="Callum Mills">C Mills</a></td>
<td class="statdata">4</td>
<td class="statdata">15</td>
<td class="statdata">13</td>
<td class="statdata">72.2</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">8</td>
<td class="statdata">312</td>
<td class="statdata">3</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">78</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--jeremy-laidler" title="Jeremy Laidler">J Laidler</a></td>
<td class="statdata">5</td>
<td class="statdata">11</td>
<td class="statdata">17</td>
<td class="statdata">100</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">171</td>
<td class="statdata">2</td>
<td class="statdata">6</td>
<td class="statdata">0</td>
<td class="statdata">87</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--dane-rampe" title="Dane Rampe">D Rampe</a></td>
<td class="statdata">4</td>
<td class="statdata">13</td>
<td class="statdata">13</td>
<td class="statdata">76.5</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">8</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">6</td>
<td class="statdata">390</td>
<td class="statdata">2</td>
<td class="statdata">6</td>
<td class="statdata">0</td>
<td class="statdata">91</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--daniel-robinson" title="Daniel Robinson">D Robinson</a></td>
<td class="statdata">4</td>
<td class="statdata">12</td>
<td class="statdata">16</td>
<td class="statdata">94.1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">6</td>
<td class="statdata">339</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">78</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--zak-jones" title="Zak Jones">Z Jones</a></td>
<td class="statdata">7</td>
<td class="statdata">11</td>
<td class="statdata">13</td>
<td class="statdata">76.5</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">6</td>
<td class="statdata">364</td>
<td class="statdata">2</td>
<td class="statdata">5</td>
<td class="statdata">0</td>
<td class="statdata">77</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--george-hewett" title="George Hewett">G Hewett</a></td>
<td class="statdata">7</td>
<td class="statdata">9</td>
<td class="statdata">9</td>
<td class="statdata">60</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">9</td>
<td class="statdata">282</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">4</td>
<td class="statdata">71</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--nick-smith-1" title="Nick Smith">N Smith</a></td>
<td class="statdata">8</td>
<td class="statdata">7</td>
<td class="statdata">7</td>
<td class="statdata">58.3</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">159</td>
<td class="statdata">6</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">92</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--harry-cunningham" title="Harry Cunningham">H Cunningham</a></td>
<td class="statdata">1</td>
<td class="statdata">10</td>
<td class="statdata">8</td>
<td class="statdata">66.7</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">8</td>
<td class="statdata">313</td>
<td class="statdata">6</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">85</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--callum-sinclair" title="Callum Sinclair">C Sinclair</a></td>
<td class="statdata">6</td>
<td class="statdata">6</td>
<td class="statdata">7</td>
<td class="statdata">58.3</td>
<td class="statdata">3</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">5</td>
<td class="statdata">222</td>
<td class="statdata">3</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">85</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--tom-papley" title="Tom Papley">T Papley</a></td>
<td class="statdata">4</td>
<td class="statdata">6</td>
<td class="statdata">9</td>
<td class="statdata">81.8</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">9</td>
<td class="statdata">228</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">70</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-sydney-swans--michael-talia" title="Michael Talia">M Talia</a></td>
<td class="statdata">4</td>
<td class="statdata">7</td>
<td class="statdata">7</td>
<td class="statdata">70</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">6</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">129</td>
<td class="statdata">1</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">86</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-sydney-swans--kurt-tippett" title="Kurt Tippett">K Tippett</a></td>
<td class="statdata">4</td>
<td class="statdata">5</td>
<td class="statdata">6</td>
<td class="statdata">75</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">7</td>
<td class="statdata">113</td>
<td class="statdata">3</td>
<td class="statdata">2</td>
<td class="statdata">1</td>
<td class="statdata">94</td>
</tr>
</table>
</td>
<td rowspan="1" class="tabbdr" style="width:1px"></td>
</tr>
<tr><td colspan="3" class="tabbdr" style="height:1px"></td></tr>
</table>
</td>
<td rowspan="1" class="norm" style="width:15px"></td>
<td rowspan="4" width="160" align="center" valign="top">
<table border="0" cellspacing="0" cellpadding="5" width="160" style="border:1px solid #D8DFEA">
<tr><td height="15" valign="top"><a href="/afl/footy/custom_supercoach_latest_scores" class="peep"><a href='/afl/footy/custom_supercoach_latest_scores' class='peep'>Track your favourite Fantasy Players!</a></a></td></tr>
<tr>
<td height="100" align="center" valign="middle">
<a href="/afl/footy/custom_supercoach_latest_scores"><img src="/afl/img/peep/peep7.jpg" border="0" height="100"/></a>
</td>
</tr>
<tr><td valign="top">Create and save your own custom list of <a href='/afl/footy/custom_supercoach_latest_scores'>Supercoach</a> or <a href='/afl/footy/custom_dream_team_latest_scores'>AFL Fantasy</a> players to track their stats!</td></tr>
</table>
<div style="padding-top:10px;">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- Footywire 160x600 Right -->
<ins class="adsbygoogle"
style="display:inline-block;width:160px;height:600px"
data-ad-client="ca-pub-1151582373407200"
data-ad-slot="4900122530"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
</td>
</tr>
<tr><td colspan="2" class="norm" style="height:20px"></td></tr>
<tr><td>
<table border="0" cellspacing="0" cellpadding="0" width="585">
<tr>
<td height="21" align="center" colspan="3" class="tbtitle" width="585">
<table border="0" cellspacing="0" cellpadding="0" width="585">
<tr>
<td class="innertbtitle" align="left"> <b><a name=t1></a>Collingwood Match Statistics (Sorted by Disposals)</b></td>
<td class="innertbtitle" align="right">Coach: <a href="cp-nathan-buckley--91">Nathan Buckley</a> </td>
</tr>
</table>
</td>
</tr>
<tr>
<td rowspan="1" class="tabbdr" style="width:1px"></td>
<td>
<table border="0" cellspacing="0" cellpadding="3" width="583">
<tr>
<td width="148" class="lbnorm" height="21">Player</td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=23&advv=Y#t2" title="Contested Possessions">CP</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=24&advv=Y#t2" title="Uncontested Possessions">UP</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=25&advv=Y#t2" title="Effective Disposals">ED</a></td>
<td width="34" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=34&advv=Y#t2" title="Disposal Efficiency %">DE%</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=27&advv=Y#t2" title="Contested Marks">CM</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=21&advv=Y#t2" title="Goal Assists">GA</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=28&advv=Y#t2" title="Marks Inside 50">MI5</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=31&advv=Y#t2" title="One Percenters">1%</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=32&advv=Y#t2" title="Bounces">BO</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=35&advv=Y#t2" title="Centre Clearances">CCL</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=36&advv=Y#t2" title="Stoppage Clearances">SCL</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=37&advv=Y#t2" title="Score Involvements">SI</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=38&advv=Y#t2" title="Metres Gained">MG</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=39&advv=Y#t2" title="Turnovers">TO</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=40&advv=Y#t2" title="Intercepts">ITC</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=41&advv=Y#t2" title="Tackles Inside 50">T5</a></td>
<td width="29" class="bnorm"><a href="fts_match_statistics?mid=6176&sby=42&advv=Y#t2" title="Time On Ground %">TOG%</a></td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--adam-treloar" title="Adam Treloar">A Treloar</a></td>
<td class="statdata">14</td>
<td class="statdata">20</td>
<td class="statdata">20</td>
<td class="statdata">58.8</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">4</td>
<td class="statdata">5</td>
<td class="statdata">497</td>
<td class="statdata">5</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">81</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--scott-pendlebury" title="Scott Pendlebury">S Pendlebury</a></td>
<td class="statdata">11</td>
<td class="statdata">14</td>
<td class="statdata">19</td>
<td class="statdata">76</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">5</td>
<td class="statdata">317</td>
<td class="statdata">2</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">89</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--steele-sidebottom" title="Steele Sidebottom">S Sidebottom</a></td>
<td class="statdata">10</td>
<td class="statdata">14</td>
<td class="statdata">15</td>
<td class="statdata">62.5</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">5</td>
<td class="statdata">220</td>
<td class="statdata">3</td>
<td class="statdata">7</td>
<td class="statdata">1</td>
<td class="statdata">90</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--taylor-adams" title="Taylor Adams">T Adams</a></td>
<td class="statdata">8</td>
<td class="statdata">17</td>
<td class="statdata">17</td>
<td class="statdata">70.8</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">340</td>
<td class="statdata">4</td>
<td class="statdata">4</td>
<td class="statdata">1</td>
<td class="statdata">84</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--levi-greenwood" title="Levi Greenwood">L Greenwood</a></td>
<td class="statdata">6</td>
<td class="statdata">15</td>
<td class="statdata">12</td>
<td class="statdata">54.5</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">470</td>
<td class="statdata">7</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">88</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--jarryd-blair" title="Jarryd Blair">J Blair</a></td>
<td class="statdata">9</td>
<td class="statdata">10</td>
<td class="statdata">11</td>
<td class="statdata">57.9</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">4</td>
<td class="statdata">146</td>
<td class="statdata">4</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">92</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--ben-sinclair" title="Ben Sinclair">B Sinclair</a></td>
<td class="statdata">5</td>
<td class="statdata">12</td>
<td class="statdata">13</td>
<td class="statdata">68.4</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">317</td>
<td class="statdata">7</td>
<td class="statdata">7</td>
<td class="statdata">1</td>
<td class="statdata">82</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--jackson-ramsay" title="Jackson Ramsay">J Ramsay</a></td>
<td class="statdata">5</td>
<td class="statdata">14</td>
<td class="statdata">13</td>
<td class="statdata">68.4</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">397</td>
<td class="statdata">4</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">86</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-kangaroos--marley-williams" title="Marley Williams">M Williams</a></td>
<td class="statdata">5</td>
<td class="statdata">14</td>
<td class="statdata">16</td>
<td class="statdata">88.9</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">2</td>
<td class="statdata">305</td>
<td class="statdata">7</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">83</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--tom-langdon" title="Tom Langdon">T Langdon</a></td>
<td class="statdata">7</td>
<td class="statdata">10</td>
<td class="statdata">14</td>
<td class="statdata">82.4</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">5</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">230</td>
<td class="statdata">3</td>
<td class="statdata">6</td>
<td class="statdata">0</td>
<td class="statdata">88</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--jordan-de-goey" title="Jordan De Goey">J De Goey</a></td>
<td class="statdata">9</td>
<td class="statdata">7</td>
<td class="statdata">10</td>
<td class="statdata">62.5</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">5</td>
<td class="statdata">191</td>
<td class="statdata">4</td>
<td class="statdata">3</td>
<td class="statdata">1</td>
<td class="statdata">89</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--alex-fasolo" title="Alex Fasolo">A Fasolo</a></td>
<td class="statdata">7</td>
<td class="statdata">7</td>
<td class="statdata">10</td>
<td class="statdata">76.9</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">212</td>
<td class="statdata">6</td>
<td class="statdata">2</td>
<td class="statdata">2</td>
<td class="statdata">85</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--jack-crisp" title="Jack Crisp">J Crisp</a></td>
<td class="statdata">6</td>
<td class="statdata">7</td>
<td class="statdata">9</td>
<td class="statdata">69.2</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">204</td>
<td class="statdata">3</td>
<td class="statdata">2</td>
<td class="statdata">4</td>
<td class="statdata">82</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-brisbane-lions--jack-frost" title="Jack Frost">J Frost</a></td>
<td class="statdata">7</td>
<td class="statdata">5</td>
<td class="statdata">8</td>
<td class="statdata">66.7</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">11</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">188</td>
<td class="statdata">5</td>
<td class="statdata">6</td>
<td class="statdata">0</td>
<td class="statdata">96</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-st-kilda-saints--nathan-brown" title="Nathan Brown">N Brown</a></td>
<td class="statdata">3</td>
<td class="statdata">7</td>
<td class="statdata">8</td>
<td class="statdata">80</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">7</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">200</td>
<td class="statdata">1</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">58</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--darcy-moore" title="Darcy Moore">D Moore</a></td>
<td class="statdata">4</td>
<td class="statdata">5</td>
<td class="statdata">8</td>
<td class="statdata">80</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">170</td>
<td class="statdata">5</td>
<td class="statdata">4</td>
<td class="statdata">3</td>
<td class="statdata">93</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--brent-macaffer" title="Brent Macaffer">B Macaffer</a></td>
<td class="statdata">5</td>
<td class="statdata">2</td>
<td class="statdata">6</td>
<td class="statdata">66.7</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">3</td>
<td class="statdata">22</td>
<td class="statdata">2</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">87</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-gold-coast-suns--jarrod-witts" title="Jarrod Witts">J Witts</a></td>
<td class="statdata">7</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">25</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">5</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">57</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">80</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--brayden-maynard" title="Brayden Maynard">B Maynard</a></td>
<td class="statdata">5</td>
<td class="statdata">3</td>
<td class="statdata">5</td>
<td class="statdata">62.5</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">4</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">2</td>
<td class="statdata">179</td>
<td class="statdata">4</td>
<td class="statdata">3</td>
<td class="statdata">0</td>
<td class="statdata">76</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-western-bulldogs--travis-cloke" title="Travis Cloke">T Cloke</a></td>
<td class="statdata">4</td>
<td class="statdata">3</td>
<td class="statdata">4</td>
<td class="statdata">57.1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">3</td>
<td class="statdata">2</td>
<td class="statdata">222</td>
<td class="statdata">2</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">98</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td align="left" height="18"><a href="pp-collingwood-magpies--corey-gault" title="Corey Gault">C Gault</a></td>
<td class="statdata">4</td>
<td class="statdata">3</td>
<td class="statdata">3</td>
<td class="statdata">42.9</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
<td class="statdata">21</td>
<td class="statdata">5</td>
<td class="statdata">1</td>
<td class="statdata">0</td>
<td class="statdata">91</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td align="left" height="18"><a href="pp-collingwood-magpies--dane-swan" title="Dane Swan">D Swan</a></td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">0</td>
<td class="statdata">1</td>
</tr>
</table>
</td>
<td rowspan="1" class="tabbdr" style="width:1px"></td>
</tr>
<tr><td colspan="3" class="tabbdr" style="height:1px"></td></tr>
</table>
</td>
<td rowspan="1" class="norm" style="width:10px"></td>
</tr>
</table>
</TD></TR>
<tr><td colspan="1" class="norm" style="height:20px"></td></tr>
<TR><TD valign="top">
<table border="0" cellspacing="0" cellpadding="0" width="760">
<tr><td valign="top">
<table border="0" cellspacing="0" cellpadding="0" width="375">
<tr><td height="21" align="center" colspan="5" class="tbtitle"><a name=hd></a>Head to Head</td></tr>
<tr>
<td rowspan="24" class="tabbdr" style="width:1px"></td>
<td width="124" class="bnorm" height="21">Sydney</td>
<td width="125" class="bnorm">Statistic</td>
<td width="124" class="bnorm">Collingwood</td>
<td rowspan="24" class="tabbdr" style="width:1px"></td>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">172</td>
<td class="statdata">Contested Possessions</td>
<td class="statdata">141</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">266</td>
<td class="statdata">Uncontested Possessions</td>
<td class="statdata">190</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">312</td>
<td class="statdata">Effective Disposals</td>
<td class="statdata">223</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">72.7%</td>
<td class="statdata">Disposal Efficiency %</td>
<td class="statdata">66.8%</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">53</td>
<td class="statdata">Clangers</td>
<td class="statdata">55</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">13</td>
<td class="statdata">Contested Marks</td>
<td class="statdata">6</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">16</td>
<td class="statdata">Marks Inside 50</td>
<td class="statdata">5</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">40</td>
<td class="statdata">Clearances</td>
<td class="statdata">33</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">37</td>
<td class="statdata">Rebound 50s</td>
<td class="statdata">52</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">48</td>
<td class="statdata">One Percenters</td>
<td class="statdata">56</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">5</td>
<td class="statdata">Bounces</td>
<td class="statdata">5</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">14</td>
<td class="statdata">Goal Assists</td>
<td class="statdata">5</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">77.8%</td>
<td class="statdata">% Goals Assisted</td>
<td class="statdata">71.4%</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">17</td>
<td class="statdata">Centre Clearances</td>
<td class="statdata">10</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">23</td>
<td class="statdata">Stoppage Clearances</td>
<td class="statdata">23</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">171</td>
<td class="statdata">Score Involvements</td>
<td class="statdata">53</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">6292</td>
<td class="statdata">Metres Gained</td>
<td class="statdata">4905</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">69</td>
<td class="statdata">Turnovers</td>
<td class="statdata">86</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="25" class="statdata">86</td>
<td class="statdata">Intercepts</td>
<td class="statdata">68</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="25" class="statdata">19</td>
<td class="statdata">Tackles Inside 50</td>
<td class="statdata">18</td>
</tr>
<tr><td colspan="5" class="tabbdr" style="height:1px"></td></tr>
</tr>
</table>
</td>
<td rowspan="1" class="norm" style="width:11px"></td>
<td valign="top">
<table border="0" cellspacing="0" cellpadding="0" width="374">
<tr><td height="21" align="center" colspan="5" class="tbtitle">Average Attributes</td></tr>
<tr>
<td rowspan="5" class="tabbdr" style="width:1px"></td>
<td width="124" class="bnorm" height="20">Sydney</td>
<td width="124" class="bnorm">Attribute</td>
<td width="124" class="bnorm">Collingwood</td>
<td rowspan="5" class="tabbdr" style="width:1px"></td>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="18" class="statdata">186.5cm</td>
<td class="statdata">Height</td>
<td class="statdata">188.0cm</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="18" class="statdata">86.2kg</td>
<td class="statdata">Weight</td>
<td class="statdata">88.9kg</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="18" class="statdata">24yr 5mth</td>
<td class="statdata">Age</td>
<td class="statdata">24yr 4mth</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="18" class="statdata">77.0</td>
<td class="statdata">Games</td>
<td class="statdata">81.1</td>
</tr>
<tr><td colspan="5" class="tabbdr" style="height:1px"></td></tr>
<tr><td colspan="5" class="norm" style="height:7px"></td></tr>
<tr><td height="21" align="center" colspan="5" class="tbtitle">Total Players By Games</td></tr>
<tr>
<td rowspan="5" class="tabbdr" style="width:1px"></td>
<td width="124" class="bnorm" height="20">Sydney</td>
<td width="124" class="bnorm">Games</td>
<td width="124" class="bnorm">Collingwood</td>
<td rowspan="5" class="tabbdr" style="width:1px"></td>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="18" class="statdata">5</td>
<td class="statdata">Less than 50</td>
<td class="statdata">3</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="18" class="statdata">8</td>
<td class="statdata">50 to 99</td>
<td class="statdata">10</td>
</tr>
<tr bgcolor="#f2f4f7" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#f2f4f7';">
<td height="18" class="statdata">1</td>
<td class="statdata">100 to 149</td>
<td class="statdata">3</td>
</tr>
<tr bgcolor="#ffffff" onMouseOver="this.bgColor='#cbcdd0';" onMouseOut="this.bgColor='#ffffff';">
<td height="18" class="statdata">8</td>
<td class="statdata">150 or more</td>
<td class="statdata">6</td>
</tr>
<tr><td colspan="5" class="tabbdr" style="height:1px"></td></tr>
</tr>
<tr><td colspan="5" align="center" style="padding-top:20px;">
</td></tr>
</table>
</td></tr>
</table>
</TD></TR>
<tr><td colspan="1" class="norm" style="height:20px"></td></tr>
<TR><TD>
<table border="0" cellspacing="0" cellpadding="0" width="760">
<tr><td height="21" align="center" colspan="7" class="tbtitle"><a name=brk></a>Quarter by Quarter Scoring Breakdown</td></tr>
<tr>
<td rowspan="6" class="ylwbdr" style="width:1px"></td>
<td rowspan="5" class="ylwbg2" style="width:4px"></td>
<td colspan="1" class="ylwbg2" style="height:4px"></td>
<td rowspan="5" class="ylwbg2" style="width:4px"></td>
<td colspan="1" class="ylwbg2" style="height:4px"></td>
<td rowspan="5" class="ylwbg2" style="width:4px"></td>
<td rowspan="6" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="373">
<tr>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
<td colspan="3" class="ylwbdr" style="height:1px"></td>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td class="ylwbgmid" height="20" width="124"><b>Sydney</b></td>
<td class="ylwbgmid" width="125"><b>First Quarter</b></td>
<td class="ylwbgmid" width="124"><b>Collingwood</b></td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
<tr>
<td class="ylwbgmid">3.9 27</td>
<td class="ylwbgmid">Score</td>
<td class="ylwbgmid">1.1 7</td>
</tr>
<tr>
<td class="ylwbgmid">12</td>
<td class="ylwbgmid">Scoring Shots</td>
<td class="ylwbgmid">2</td>
</tr>
<tr>
<td class="ylwbgmid">25.0%</td>
<td class="ylwbgmid">Conversion</td>
<td class="ylwbgmid">50.0%</td>
</tr>
<tr>
<td class="ylwbgmid">Won quarter by 20</td>
<td class="ylwbgmid">Result</td>
<td class="ylwbgmid">Lost quarter by 20</td>
</tr>
<tr>
<td class="ylwbgmid">Leading by 20</td>
<td class="ylwbgmid">End of Quarter</td>
<td class="ylwbgmid">Trailing by 20</td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
</table>
</td>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="373">
<tr>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
<td colspan="3" class="ylwbdr" style="height:1px"></td>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td class="ylwbgmid" height="20" width="124"><b>Sydney</b></td>
<td class="ylwbgmid" width="125"><b>Second Quarter</b></td>
<td class="ylwbgmid" width="124"><b>Collingwood</b></td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
<tr>
<td class="ylwbgmid">7.3 45</td>
<td class="ylwbgmid">Score</td>
<td class="ylwbgmid">0.3 3</td>
</tr>
<tr>
<td class="ylwbgmid">10</td>
<td class="ylwbgmid">Scoring Shots</td>
<td class="ylwbgmid">3</td>
</tr>
<tr>
<td class="ylwbgmid">70.0%</td>
<td class="ylwbgmid">Conversion</td>
<td class="ylwbgmid">0%</td>
</tr>
<tr>
<td class="ylwbgmid">Won quarter by 42</td>
<td class="ylwbgmid">Result</td>
<td class="ylwbgmid">Lost quarter by 42</td>
</tr>
<tr>
<td class="ylwbgmid">Leading by 62</td>
<td class="ylwbgmid">Halftime</td>
<td class="ylwbgmid">Trailing by 62</td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
</table>
</td>
</tr>
<tr><td colspan="3" class="ylwbg2" style="height:4px"></td></tr>
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="373">
<tr>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
<td colspan="3" class="ylwbdr" style="height:1px"></td>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td class="ylwbgmid" height="20" width="124"><b>Sydney</b></td>
<td class="ylwbgmid" width="125"><b>Third Quarter</b></td>
<td class="ylwbgmid" width="124"><b>Collingwood</b></td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
<tr>
<td class="ylwbgmid">4.9 33</td>
<td class="ylwbgmid">Score</td>
<td class="ylwbgmid">4.2 26</td>
</tr>
<tr>
<td class="ylwbgmid">13</td>
<td class="ylwbgmid">Scoring Shots</td>
<td class="ylwbgmid">6</td>
</tr>
<tr>
<td class="ylwbgmid">30.8%</td>
<td class="ylwbgmid">Conversion</td>
<td class="ylwbgmid">66.7%</td>
</tr>
<tr>
<td class="ylwbgmid">Won quarter by 7</td>
<td class="ylwbgmid">Result</td>
<td class="ylwbgmid">Lost quarter by 7</td>
</tr>
<tr>
<td class="ylwbgmid">Leading by 69</td>
<td class="ylwbgmid">End of Quarter</td>
<td class="ylwbgmid">Trailing by 69</td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
</table>
</td>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="373">
<tr>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
<td colspan="3" class="ylwbdr" style="height:1px"></td>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td class="ylwbgmid" height="20" width="124"><b>Sydney</b></td>
<td class="ylwbgmid" width="125"><b>Final Quarter</b></td>
<td class="ylwbgmid" width="124"><b>Collingwood</b></td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
<tr>
<td class="ylwbgmid">4.4 28</td>
<td class="ylwbgmid">Score</td>
<td class="ylwbgmid">2.5 17</td>
</tr>
<tr>
<td class="ylwbgmid">8</td>
<td class="ylwbgmid">Scoring Shots</td>
<td class="ylwbgmid">7</td>
</tr>
<tr>
<td class="ylwbgmid">50.0%</td>
<td class="ylwbgmid">Conversion</td>
<td class="ylwbgmid">28.6%</td>
</tr>
<tr>
<td class="ylwbgmid">Won quarter by 11</td>
<td class="ylwbgmid">Result</td>
<td class="ylwbgmid">Lost quarter by 11</td>
</tr>
<tr>
<td class="ylwbgmid">Won game by 80</td>
<td class="ylwbgmid">End of Game</td>
<td class="ylwbgmid">Lost game by 80</td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
</table>
</td>
</tr>
<tr><td colspan="3" class="ylwbg2" style="height:4px"></td></tr>
<tr><td colspan="5" class="ylwbdr" style="height:1px"></td></tr>
</table>
</TD></TR>
<tr><td colspan="1" class="norm" style="height:20px"></td></tr>
<TR><TD>
<table border="0" cellspacing="0" cellpadding="0" width="760">
<tr><td height="21" align="center" colspan="7" class="tbtitle">Scoring Breakdown For Each Half</td></tr>
<tr>
<td rowspan="4" class="ylwbdr" style="width:1px"></td>
<td rowspan="3" class="ylwbg2" style="width:4px"></td>
<td colspan="1" class="ylwbg2" style="height:4px"></td>
<td rowspan="3" class="ylwbg2" style="width:4px"></td>
<td colspan="1" class="ylwbg2" style="height:4px"></td>
<td rowspan="3" class="ylwbg2" style="width:4px"></td>
<td rowspan="4" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="373">
<tr>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
<td colspan="3" class="ylwbdr" style="height:1px"></td>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td class="ylwbgmid" height="20" width="124"><b>Sydney</b></td>
<td class="ylwbgmid" width="125"><b>First Half</b></td>
<td class="ylwbgmid" width="124"><b>Collingwood</b></td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
<tr>
<td class="ylwbgmid">10.12 72</td>
<td class="ylwbgmid">Score</td>
<td class="ylwbgmid">1.4 10</td>
</tr>
<tr>
<td class="ylwbgmid">22</td>
<td class="ylwbgmid">Scoring Shots</td>
<td class="ylwbgmid">5</td>
</tr>
<tr>
<td class="ylwbgmid">45.5%</td>
<td class="ylwbgmid">Conversion</td>
<td class="ylwbgmid">20.0%</td>
</tr>
<tr>
<td class="ylwbgmid">Won half by 62</td>
<td class="ylwbgmid">Result</td>
<td class="ylwbgmid">Lost half by 62</td>
</tr>
<tr>
<td class="ylwbgmid">Leading by 62</td>
<td class="ylwbgmid">Halftime</td>
<td class="ylwbgmid">Trailing by 62</td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
</table>
</td>
<td>
<table border="0" cellspacing="0" cellpadding="0" width="373">
<tr>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
<td colspan="3" class="ylwbdr" style="height:1px"></td>
<td rowspan="9" class="ylwbdr" style="width:1px"></td>
</tr>
<tr>
<td class="ylwbgmid" height="20" width="124"><b>Sydney</b></td>
<td class="ylwbgmid" width="125"><b>Second Half</b></td>
<td class="ylwbgmid" width="124"><b>Collingwood</b></td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
<tr>
<td class="ylwbgmid">8.13 61</td>
<td class="ylwbgmid">Score</td>
<td class="ylwbgmid">6.7 43</td>
</tr>
<tr>
<td class="ylwbgmid">21</td>
<td class="ylwbgmid">Scoring Shots</td>
<td class="ylwbgmid">13</td>
</tr>
<tr>
<td class="ylwbgmid">38.1%</td>
<td class="ylwbgmid">Conversion</td>
<td class="ylwbgmid">46.2%</td>
</tr>
<tr>
<td class="ylwbgmid">Won half by 18</td>
<td class="ylwbgmid">Result</td>
<td class="ylwbgmid">Lost half by 18</td>
</tr>
<tr>
<td class="ylwbgmid">Won game by 80</td>
<td class="ylwbgmid">End of Game</td>
<td class="ylwbgmid">Lost game by 80</td>
</tr>
<tr><td colspan="3" class="ylwbdr" style="height:1px"></td></tr>
</table>
</td>
</tr>
<tr><td colspan="3" class="ylwbg2" style="height:4px"></td></tr>
<tr><td colspan="5" class="ylwbdr" style="height:1px"></td></tr>
</table>
</TD></TR>
</TABLE>
</td></tr>
</table></td>
<td rowspan="3" bgcolor="#b7b7b7" style="width:1px"></td>
</tr>
<tr><td align="center" valign="middle" height="40">
</td></tr>
<tr>
<td colspan="1" bgcolor="#b7b7b7" style="height:1px"></td>
</tr>
<tr><td colspan="3" align="center" valign="middle" height="25">
<table id="footer">
<tr>
<td id="footercopy">Footywire.com © 2018</td>
<td id="footerlinks">
<a href="/afl/footy/info?if=a">about</a>
<a href="/afl/footy/info?if=t">terms</a>
<a href="/afl/footy/info?if=p">privacy</a>
<a target="_smaq" href="http://www.smaqtalk.com/">discussions</a>
<a href="/afl/footy/contact_us">contact us</a>
</td>
</tr>
</table>
</td></tr>
</table>
</DIV>
<table id="teammenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" >x</div></td></tr>
<tr>
<td colspan="3"><a class="submenuitem" href="/afl/footy/ft_teams">Compare Teams</a></td>
</tr>
<tr>
<td colspan="3"><div class="submenutitle">Team Home Pages</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" class="submenuitem" href="/afl/footy/th-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('teammenu')" onMouseUp="hideSubMenu('teammenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="playermenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/ft_players">All Players</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/player_search">Player Search</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/past_players">Past Players</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/other_players">Other Players</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/ft_player_compare">Compare Players</a></td></tr>
<tr>
<td colspan="3"><div class="submenutitle">Team Playing Lists</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" class="submenuitem" href="/afl/footy/tp-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('playermenu')" onMouseUp="hideSubMenu('playermenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="playerrankmenu">
<tr><td colspan="3" align="right"><div class="submenux" onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/ft_player_rankings?rt=LA">League Averages</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/ft_player_rankings?rt=LT">League Totals</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/ft_player_rankings?rt=RA">Rising Star Averages</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/ft_player_rankings?rt=RT">Rising Star Totals</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/ft_goal_kickers">Season Goalkickers</a></td></tr>
<tr>
<td colspan="3"><div class="submenutitle">Player Rankings by Team</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" class="submenuitem" href="/afl/footy/tr-richmond-tigers">Tigers</a></td>
</tr>
<tr><td colspan="3" align="right"><div class="submenux" onClick="hideSubMenu('playerrankmenu')" onMouseUp="hideSubMenu('playerrankmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="teamrankmenu">
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" >x</div></td></tr>
<tr><td><a onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" class="submenuitem" href="/afl/footy/ft_team_rankings?type=TA">Team Averages</a></td></tr>
<tr><td><a onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" class="submenuitem" href="/afl/footy/ft_team_rankings?type=TT">Team Totals</a></td></tr>
<tr><td><a onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" class="submenuitem" href="/afl/footy/ft_team_rankings?type=OA">Opponent Averages</a></td></tr>
<tr><td><a onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" class="submenuitem" href="/afl/footy/ft_team_rankings?type=OT">Opponent Totals</a></td></tr>
<tr><td><a onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" class="submenuitem" href="/afl/footy/ft_team_rankings?type=DA">Team/Opponent Differential Averages</a></td></tr>
<tr><td><a onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" class="submenuitem" href="/afl/footy/ft_team_rankings?type=DT">Team/Opponent Differential Totals</a></td></tr>
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('teamrankmenu')" onMouseUp="hideSubMenu('teamrankmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="draftmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/ft_drafts">Full AFL Draft History</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/ft_team_draft_summaries">Draft Summary by Team</a></td></tr>
<tr>
<td colspan="3"><div class="submenutitle">AFL Draft History by Team</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" class="submenuitem" href="/afl/footy/td-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('draftmenu')" onMouseUp="hideSubMenu('draftmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="risingstarmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ft_rising_stars_round_performances">Rising Star Round by Round Performances</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/rising_star_nominations">Rising Star Nominees</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/rising_star_winners">Rising Star Winners</a></td></tr>
<tr>
<td colspan="3"><div class="submenutitle">Eligible Rising Stars by Team</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" class="submenuitem" href="/afl/footy/ty-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('risingstarmenu')" onMouseUp="hideSubMenu('risingstarmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="matchmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/ft_match_list">Full Season AFL Fixture</a></td></tr>
<tr>
<td colspan="3"><div class="submenutitle">Played and Scheduled Matches by Team</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" class="submenuitem" href="/afl/footy/tg-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('matchmenu')" onMouseUp="hideSubMenu('matchmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="laddermenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/ft_ladder">Full Season</a></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/live_ladder">Live Ladder</a></td></tr>
<tr>
<td colspan="3"><div class="submenutitle">Filter Ladder by</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/ft_ladder?pt=RD&st=01&sb=p">Round</a></td>
<td><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/ft_ladder?pt=PD&st=Q1&sb=p">Match Period</a></td>
<td><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/ft_ladder?pt=LC&st=LC&sb=p">Location</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/ft_ladder?pt=VN&st=10&sb=p">Venue</a></td>
<td><a onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" class="submenuitem" href="/afl/footy/ft_ladder?pt=ST&st=disposals&sb=p">Stats</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('laddermenu')" onMouseUp="hideSubMenu('laddermenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="brownlowmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/brownlow_medal">Full Brownlow Medal Count</a></td></tr><tr>
<tr><td colspan="3"><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/brownlow_medal_winners">Brownlow Medal Winners</a></td></tr><tr>
<tr><td colspan="3"><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/team_brownlow_medal_summaries">Summary by Team</a></td></tr><tr>
<tr>
<td colspan="3"><div class="submenutitle">Brownlow Medal Vote Getters By Club</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" class="submenuitem" href="/afl/footy/tb-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('brownlowmenu')" onMouseUp="hideSubMenu('brownlowmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="attendancemenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/attendances">AFL Crowds & Attendances</a></td></tr><tr>
<tr>
<td colspan="3"><div class="submenutitle">Historical Attendance by Team</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" class="submenuitem" href="/afl/footy/ta-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('attendancemenu')" onMouseUp="hideSubMenu('attendancemenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="coachmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/afl_coaches">AFL Coaches</a></td></tr><tr>
<tr>
<td colspan="3"><div class="submenutitle">AFL Club Coaches</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" class="submenuitem" href="/afl/footy/tc-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('coachmenu')" onMouseUp="hideSubMenu('coachmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="highlightsmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" >x</div></td></tr>
<tr><td colspan="3"><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/afl_highlights">AFL Highlights</a></td></tr><tr>
<tr>
<td colspan="3"><div class="submenutitle">AFL Club Highlights</div></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" class="submenuitem" href="/afl/footy/tv-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('highlightsmenu')" onMouseUp="hideSubMenu('highlightsmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="supercoachmenu">
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" >x</div></td></tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/supercoach_round">Round by Round Player Rankings</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/supercoach_season">Season Player Rankings</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/supercoach_breakevens">Supercoach Breakevens</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/supercoach_scores">Supercoach Scores</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/supercoach_prices">Supercoach Prices</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/custom_supercoach_latest_scores">Custom Supercoach Player List</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" class="submenuitem" href="/afl/footy/pre_season_supercoach">Pre-Season Supercoach Stats</a></td></tr><tr>
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('supercoachmenu')" onMouseUp="hideSubMenu('supercoachmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="dreamteammenu">
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" >x</div></td></tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/dream_team_round">Round by Round Player Rankings</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/dream_team_season">Season Player Rankings</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/dream_team_breakevens">AFL Fantasy Breakevens</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/dream_team_scores">AFL Fantasy Scores</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/dream_team_prices">AFL Fantasy Prices</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/custom_dream_team_latest_scores">Custom AFL Fantasy Player List</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" class="submenuitem" href="/afl/footy/pre_season_dream_team">Pre-Season AFL Fantasy Stats</a></td></tr><tr>
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('dreamteammenu')" onMouseUp="hideSubMenu('dreamteammenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="selectionsmenu">
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('selectionsmenu')" onMouseUp="hideSubMenu('selectionsmenu')" >x</div></td></tr>
<tr><td><a onClick="hideSubMenu('selectionsmenu')" onMouseUp="hideSubMenu('selectionsmenu')" class="submenuitem" href="/afl/footy/afl_team_selections">Latest Team Selections</a></td></tr><tr>
<tr><td><a onClick="hideSubMenu('selectionsmenu')" onMouseUp="hideSubMenu('selectionsmenu')" class="submenuitem" href="/afl/footy/custom_all_team_selections">Custom Team Selections List</a></td></tr><tr>
<tr><td align="right"><div class="submenux" onClick="hideSubMenu('selectionsmenu')" onMouseUp="hideSubMenu('selectionsmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="pastplayermenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" >x</div></td></tr>
<tr>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" class="submenuitem" href="/afl/footy/ti-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('pastplayermenu')" onMouseUp="hideSubMenu('pastplayermenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<table id="contractsmenu">
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" >x</div></td></tr>
<tr>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-carlton-blues">Blues</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-essendon-bombers">Bombers</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-western-bulldogs">Bulldogs</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-geelong-cats">Cats</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-adelaide-crows">Crows</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-melbourne-demons">Demons</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-fremantle-dockers">Dockers</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-west-coast-eagles">Eagles</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-greater-western-sydney-giants">Giants</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-hawthorn-hawks">Hawks</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-kangaroos">Kangaroos</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-brisbane-lions">Lions</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-collingwood-magpies">Magpies</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-port-adelaide-power">Power</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-st-kilda-saints">Saints</a></td>
</tr>
<tr>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-gold-coast-suns">Suns</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-sydney-swans">Swans</a></td>
<td><a onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" class="submenuitem" href="/afl/footy/to-richmond-tigers">Tigers</a></td>
</tr>
<tr><td align="right" colspan="3"><div class="submenux" onClick="hideSubMenu('contractsmenu')" onMouseUp="hideSubMenu('contractsmenu')" style="padding-top:6px;">hide menu</div></td></tr>
</table>
<div id="membersbgdiv" onClick="closeMemberDivs();"></div>
<div id="memberswhitediv">
<table border="0" cellspacing="0" cellpadding="0" align="center">
<tr><td height="30" align="right" valign="top"><span id="membersx" onClick="closeMemberDivs();">X</span></td></tr>
<tr><td id="memberscontent" valign="top" align="center">
</td></tr>
</table>
</div>
</BODY>
</HTML>
|
criffy/aflengine
|
matchfiles/footywire_adv/footywire_adv6176.html
|
HTML
|
gpl-3.0
| 148,094
|
#ifndef NALL_UTILITY_HPP
#define NALL_UTILITY_HPP
#include <type_traits>
#include <utility>
namespace nall {
template<bool C, typename T = bool> struct enable_if { typedef T type; };
template<typename T> struct enable_if<false, T> {};
template<typename C, typename T = bool> struct mp_enable_if :
enable_if<C::value, T> {};
template<typename T> inline void swap(T &x, T &y)
{
T temp(std::move(x));
x = std::move(y);
y = std::move(temp);
}
template<typename T> struct base_from_member {
T value;
base_from_member(T value_) : value(value_) {}
};
template<typename T> class optional {
bool valid;
T value;
public:
inline operator bool() const { return valid; }
inline const T& operator()() const { if(!valid) throw; return value; }
inline optional(bool valid, const T &value) : valid(valid), value(value) {}
};
template<typename T> inline T* allocate(unsigned size, const T &value)
{
T *array = new T[size];
for (unsigned i = 0; i < size; i++) {
array[i] = value;
}
return array;
}
}
#endif
|
grim210/defimulator
|
defimulator/nall/utility.hpp
|
C++
|
gpl-3.0
| 1,065
|
namespace Minary.DataTypes.ArpScan
{
public struct SystemFound
{
#region PROPERTIES
public string MacAddress { get; set; }
public string IpAddress { get; set; }
public string Type { get; set; }
#endregion
#region PUBLIC
public SystemFound(string macAddress, string ipAddress, string type)
{
this.MacAddress = macAddress;
this.IpAddress = ipAddress;
this.Type = type;
}
#endregion
}
}
|
Minary/Minary
|
Minary/DataTypes/ArpScan/SystemFound.cs
|
C#
|
gpl-3.0
| 462
|
# coding=utf-8
import unittest
"""69. Sqrt(x)
https://leetcode.com/problems/sqrtx/description/
Implement `int sqrt(int x)`.
Compute and return the square root of _x_ , where _x_ is guaranteed to be a
non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only
the integer part of the result is returned.
**Example 1:**
**Input:** 4
**Output:** 2
**Example 2:**
**Input:** 8
**Output:** 2
**Explanation:** The square root of 8 is 2.82842..., and since
the decimal part is truncated, 2 is returned.
Similar Questions:
Pow(x, n) (powx-n)
Valid Perfect Square (valid-perfect-square)
"""
class Solution(object):
def mySqrt(self, x):
"""
:type x: int
:rtype: int
"""
def test(self):
pass
if __name__ == "__main__":
unittest.main()
|
openqt/algorithms
|
leetcode/python/lc069-sqrtx.py
|
Python
|
gpl-3.0
| 925
|
/*
* This MainForm should only contain Event Handlers
* Everything else should be in its own file or class
* Have a function that stores all Textbox into the Character class
*/
using System;
using System.Collections.Generic;
using System.Collections;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization;
using System.Linq;
using System.Diagnostics;
using System.Net;
using System.Reflection;
namespace OPRPCharBuild
{
public partial class MainForm : Form {
public MainForm() {
// Check for updates of a New Version or Bug Messages
InitializeComponent();
//this.Visible = false;
//if (!Loading_Window()) { this.Visible = true; }
}
// --------------------------------------------------------------------------------------------
// MEMBER VARIABLES
// --------------------------------------------------------------------------------------------
#region Member Variables
public const string VERSION = "1.8.1";
public const string STD_TEMPLATE_MSG = "Standard Template";
private const string WEBSITE = "https://github.com/mrdoowan/OPRPCharBuild/releases";
public static bool template_imported = false;
private static bool saved = true; // Used to keep track if saved
// Character Class
// The following will update the Character Class at real-time:
// Professions, Traits, and Techniques
Character profile = new Character();
// Variables for Templates
public static Dictionary<int, string> CustomTags = new Dictionary<int, string>();
// Variables that need their data type here instead of in Character
int genCurr, genCap, profCurr, profCap;
private Dictionary<string, Profession> profList = new Dictionary<string, Profession>();
private List<Trait> traitList = new List<Trait>();
private Dictionary<string, Technique> techList = new Dictionary<string, Technique>();
// Sp Table dictionary that won't be stored in Character
private List<SpTrait> spTraitList = new List<SpTrait>();
// Sources
private Dictionary<string, Source> sourceList = new Dictionary<string, Source>();
#endregion
#region General Functions
// General function for Deleting an Item from ListView
// Returns the string Name of the Item, specifically for finding Key values in Dictionary
public string Delete_ListViewItem(ref ListView list) {
if (list.SelectedItems.Count == 1) {
string key = list.SelectedItems[0].SubItems[0].Text; // Typically the key value is always the name
foreach (ListViewItem eachItem in list.SelectedItems) {
list.Items.Remove(eachItem);
}
notSavedStatus();
return key;
}
return null;
}
// To move up or down the item in a ListView
private void Move_List_Item(ref ListView list, string direction) {
if (list.SelectedItems.Count == 0) { return; }
int curr_ind = list.SelectedItems[0].Index;
if (curr_ind < 0) {
return;
}
else {
ListViewItem item = list.Items[curr_ind];
if (direction == "Up") {
if (curr_ind > 0) {
list.Items.RemoveAt(curr_ind);
list.Items.Insert(curr_ind - 1, item);
// Maintain selection
list.Items[curr_ind - 1].Selected = true;
notSavedStatus();
}
}
else if (direction == "Down") {
if (curr_ind < list.Items.Count - 1) {
list.Items.RemoveAt(curr_ind);
list.Items.Insert(curr_ind + 1, item);
// Maintain selection
list.Items[curr_ind + 1].Selected = true;
notSavedStatus();
}
}
else {
MessageBox.Show("There is a bug with this button!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}
// To move up or down the selected item in a dataGridView
// Requires direction to be "Up" or "Down"
private void Move_DGV_Item(ref DataGridView dgv, string direction) {
// Up
try {
int totalRows = dgv.Rows.Count;
int rowIndex = dgv.SelectedCells[0].OwningRow.Index;
if (rowIndex == 0 && direction == "Up") { return; }
if (rowIndex == totalRows - 1 && direction == "Down") { return; }
// get index of the column for the selected cell
DataGridViewRow selectedRow = dgv.Rows[rowIndex];
dgv.Rows.Remove(selectedRow);
if (direction == "Up") {
dgv.Rows.Insert(rowIndex - 1, selectedRow);
dgv.Rows[rowIndex - 1].Selected = true;
}
else {
dgv.Rows.Insert(rowIndex + 1, selectedRow);
dgv.Rows[rowIndex + 1].Selected = true;
}
notSavedStatus();
}
catch { }
}
// Start the Loading Window for cool dots (WORK ON THIS LATER)
/*
private bool Loading_Window() {
// Implement PendingWindow for Coolness
PendingWindow pendingWin = new PendingWindow();
// Get the Timer loaded
BackgroundWorker timerWorker = new BackgroundWorker();
timerWorker.DoWork += new DoWorkEventHandler(pendingWin.start_Timer);
timerWorker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(pendingWin.finished_Timer);
timerWorker.RunWorkerAsync();
// Now check for updates
BackgroundWorker updateWorker = new BackgroundWorker();
updateWorker.DoWork += new DoWorkEventHandler(Check_Update);
return false;
}
*/
// Really don't want to use Microsoft's Click-Once application at this point, so I'll just
// implement my own version.
// Version now follows the following format:
// Major.Minor.Revision (only 3)
//private void Check_Update(object sender, DoWorkEventArgs e) {
private void Check_Update() {
// -------------------------------------
// Version Check
// -------------------------------------
WebClient WC = new WebClient();
try {
string[] current = VERSION.Split('.');
// Get latest version from site
string header_msg = "OPRPCharBuilder " + Assembly.GetExecutingAssembly().GetName().Version.ToString() + " UpdateCheck " + Environment.OSVersion;
WC.Headers.Add("Content-Type", header_msg);
string version_page = WC.DownloadString("https://raw.githubusercontent.com/mrdoowan/OPRPCharBuild/master/CurrentVer.txt");
string[] latest = version_page.Split('.');
// Since we are looping through Current length, Current should not be bigger than Latest
if (current.Length > latest.Length) {
MessageBox.Show("The current Length is greater than latest Length.", "Report Bug", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
for (int i = 0; i < current.Length; ++i) {
// We ask for update if latest > current
if (int.Parse(latest[i]) != int.Parse(current[i])) {
// Version # does not align
if (int.Parse(latest[i]) > int.Parse(current[i])) {
if (MessageBox.Show("An update to v" + version_page + " is available. Would you like to close this application and download the newest version?", "New Version",
MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) {
Process.Start(WEBSITE);
Process.Start("http://s1.zetaboards.com/One_Piece_RP/topic/6060583/1/");
saved = true;
Application.Exit();
}
return;
}
}
}
}
catch { }
}
// Returns true if Prof is in the List and it's Primary
// Returns false otherwise
private bool Is_Prof_Primary(string name) {
if (profList.ContainsKey(name)) {
if (profList[name].primary) {
return true;
}
}
return false;
}
// Makes the Devil Fruit class based on what's initialized
private DevilFruit makeDFClass() {
return new DevilFruit(textBox_DFName.Text,
comboBox_DFType.Text,
comboBox_DFTier.Text,
richTextBox_DFDesc.Text);
}
#endregion
#region Update Functions
#region Update Trait Functions
// Whenever a trait is added or deleted, we update the displayed number of Traits
private void Update_Traits_Count_Label() {
int gen = 0; // 2nd Column
int prof = 0; // 3rd Column
foreach (Trait trait in traitList) {
gen += trait.genNum;
prof += trait.profNum;
}
genCurr = gen;
profCurr = prof;
label58_TraitsCurrent.Text = "You currently have " + gen + " General Trait(s) and " +
prof + " Professional Trait(s)";
if (genCurr == genCap && profCurr == profCap) {
label58_TraitsCurrent.ForeColor = Color.Green;
}
else {
label58_TraitsCurrent.ForeColor = Color.Red;
}
}
// Whenever SD Earned is updated, we have to update the max amount of Traits.
private void Update_Traits_Cap() {
int gen = 0, prof = 0;
int SD_Earned = (int)numericUpDown_SDEarned.Value;
if (SD_Earned < 50) {
gen = 3;
prof = 1;
}
else if (SD_Earned >= 50 && SD_Earned < 100) {
gen = 4;
prof = 2;
}
else if (SD_Earned >= 100 && SD_Earned < 150) {
gen = 5;
prof = 2;
}
else if (SD_Earned >= 150 && SD_Earned < 200) {
gen = 6;
prof = 3;
}
else if (SD_Earned >= 200 && SD_Earned < 250) {
gen = 7;
prof = 3;
}
else if (SD_Earned >= 250 && SD_Earned < 275) {
gen = 7;
prof = 4;
}
else if (SD_Earned >= 275 && SD_Earned < 350) {
gen = 8;
prof = 4;
}
else if (SD_Earned >= 350 && SD_Earned < 425) {
gen = 9;
prof = 5;
}
else if (SD_Earned >= 425 && SD_Earned < 500) {
gen = 10;
prof = 5;
}
else {
gen = 11;
prof = 6;
}
// Check AP Traits
gen += (int)numericUpDown_APTrait.Value;
// Update label and global variable.
genCap = gen;
profCap = prof;
// Update Focus
int focus = 1 + gen / 2;
if (focus > 7) { focus = 7; }
textBox_Focus.Text = focus.ToString();
// Update Traits Message
label59_TraitsCalc.Text = "Your current cap is " + gen +
" General Trait(s) and " + prof + " Professional Trait(s)";
if (genCurr == genCap && profCurr == profCap) {
label58_TraitsCurrent.ForeColor = Color.Green;
}
else {
label58_TraitsCurrent.ForeColor = Color.Red;
}
}
#endregion
#region Update Stats Functions
// Used when an AP is checked.
private void Update_AP_Count() {
int AP_num = (int)(numericUpDown_APTech.Value +
2 * numericUpDown_APTrait.Value +
numericUpDown_APPrime.Value +
numericUpDown_APMulti.Value +
numericUpDown_APNPC.Value);
AP_num += (checkBox_APHaki.Checked) ? 2 : 0;
AP_num += (checkBox_APDF.Checked) ? 1 : 0;
int SD = AP_num * 50;
textBox_AP.Text = AP_num.ToString();
label_SDonAP.Text = SD + " SD spent on ";
}
// For below function
private const int CONV_CAP_1 = 200;
private const int CONV_CAP_2 = 600;
private const int CONV_CAP_3 = 1000;
// Calculating Stat Points
private void Update_Stat_Points() {
int SD_in = (int)numericUpDown_SDintoStats.Value;
string calc = "[32";
int SP = 32;
if (SD_in >= 0 && SD_in <= CONV_CAP_1) {
// 1:1
SP += SD_in;
calc += " + " + SD_in;
}
else if (SD_in > CONV_CAP_1 && SD_in <= CONV_CAP_2) {
// 2:1
int remain = SD_in - CONV_CAP_1; // this is in SD
int convert = remain / 2;
SP += 200 + convert;
calc += " + 200 + " + convert + " (" + remain + "/2)";
}
else if (SD_in > CONV_CAP_2 && SD_in <= CONV_CAP_3) {
// 4:1
int remain = SD_in - CONV_CAP_1 - CONV_CAP_2;
int convert = remain / 3;
SP += 200 + 200 + convert;
calc += " + 200 + 200 (400/2) + " + convert + " (" + remain + "/4)";
}
else {
// 5:1
int remain = SD_in - CONV_CAP_1 - CONV_CAP_2 - CONV_CAP_3;
int convert = remain / 5;
SP += 200 + 200 + 100 + convert;
calc += " + 200 + 200 (400/2) + 100 (400/4) " + convert + " (" + remain + "/5)";
}
calc += ']';
textBox_StatPoints.Text = SP.ToString();
textBox_SDtoSPCalc.Text = calc;
// Used when SD into Stats is changed
}
private void Update_TotalSD() {
textBox_TotalSD.Text = ((int)numericUpDown_SDEarned.Value + int.Parse(textBox_AP.Text) * 50).ToString();
// Used when AP is Checked
// Used when SD Earned is Changed
}
// Calculating SD Remaining after remnants of Stat Points
private void Update_SD_Remaining() {
textBox_SDRemain.Text = (numericUpDown_SDEarned.Value - numericUpDown_SDintoStats.Value).ToString();
// Used when SD Earned is changed
// Used when SD into Stats is changed
}
// Calculating Used for Stat Points
private void Update_Used_for_Stats() {
textBox_UsedForStats.Text = (int.Parse(textBox_StatPoints.Text) - numericUpDown_UsedForFort.Value).ToString();
// Used when Stat Points is changed
// Used when Used for Fortune is changed
}
private void Update_Fortune() {
string calc = "[";
// First Stat Points / 4
int fortune = int.Parse(textBox_UsedForStats.Text) / 4;
calc += textBox_UsedForStats.Text + " / 4";
// Then Fortune from Used for Fortune
int used_for = (int)numericUpDown_UsedForFort.Value / 5 * 3;
if (used_for > 0) {
fortune += used_for;
calc += " + (" + numericUpDown_UsedForFort.Value + " / 5 * 3)";
}
// Then Fortune from Fate of Emperor
if (traitList.Any(x => x.name == Database.TR_FATEEM)) {
// # Gen Traits is Column 2
int traits = traitList.Find(x => x.name == Database.TR_FATEEM).genNum;
fortune += traits;
calc += " + " + traits;
}
calc += ']';
// Total Fortune display along with calculation
label_FortuneCalc.Text = calc;
textBox_Fortune.Text = fortune.ToString();
// Used when Stat Points is changed
// Used when Used for Fortune is changed
// Used when Traits are added
// Used when Traits are edited
// Used when Traits are removed
}
private void Update_BaseStats_Check() {
int total = (int)(numericUpDown_StrengthBase.Value +
numericUpDown_SpeedBase.Value +
numericUpDown_StaminaBase.Value +
numericUpDown_AccuracyBase.Value);
if (total == int.Parse(textBox_UsedForStats.Text)) {
label_GenerateCheck.Text = "Base stats added correctly!";
label_GenerateCheck.ForeColor = Color.Green;
}
else {
label_GenerateCheck.Text = "Base Stat values do not add up!\n";
label_GenerateCheck.Text += numericUpDown_StrengthBase.Value + " + ";
label_GenerateCheck.Text += numericUpDown_SpeedBase.Value + " + ";
label_GenerateCheck.Text += numericUpDown_StaminaBase.Value + " + ";
label_GenerateCheck.Text += numericUpDown_AccuracyBase.Value + " = ";
label_GenerateCheck.Text += total;
label_GenerateCheck.ForeColor = Color.Red;
}
// Used for when any of the base Stats changes.
// Used when Used for Stats is changed
}
private void Stat_Multiplier_Trait(ref int base_stat, ref string calc, double multiplier) {
if (base_stat <= 75) {
base_stat = (int)((double)base_stat * multiplier);
calc += " * " + multiplier.ToString();
}
else {
// Maxes out at base stat 75
// I can't do arithmetic operations with two doubles or
// it screws up by like 9 decimal places >_>
if (multiplier == 1.2) {
multiplier = 0.2;
}
else if (multiplier == 1.4) {
multiplier = 0.4;
}
else if (multiplier == 1.6) {
multiplier = 0.6;
}
else {
MessageBox.Show("Stat Multipliers screwed up.", "Error");
}
int base_75 = (int)(75 * multiplier);
base_stat += base_75;
calc += " + " + base_75;
}
}
// This is only for changing stats by Fated
private void Add_Fated_Stats(ref int stat, ref string calc, string fated) {
if (traitList.Any(x => x.name == fated)) {
int Traits = traitList.Find(x => x.name == fated).genNum;
stat += 3 * Traits;
calc += " + (3 * " + Traits + ")";
}
}
// Note: Stat Traits ONLY multiplies the Base Stat. And then you apply any other bonuses.
private void Update_Strength_Final() {
int base_stat = (int)numericUpDown_StrengthBase.Value;
int final = base_stat;
string calc = "[" + base_stat;
// Do the base stats first.
if (traitList.Any(x => x.name == Database.TR_STR3RD)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.6);
}
else if (traitList.Any(x => x.name == Database.TR_STR2ND)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.4);
}
else if (traitList.Any(x => x.name == Database.TR_STR1ST) ||
traitList.Any(x => x.name == Database.TR_FISHMA) ||
traitList.Any(x => x.name == Database.TR_DWARF)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.2);
}
// And then lastly, the Fated Trait.
Add_Fated_Stats(ref final, ref calc, Database.TR_FATEST);
textBox_StrengthFinal.Text = final.ToString();
calc += ']';
label_StrengthCalc.Text = calc;
// Used when Base Strength changes.
// Used when Traits are added.
// Used when Traits are edited
// Used when Traits are removed.
}
private void Update_Speed_Final() {
// I hate copying pasting code...
int base_stat = (int)numericUpDown_SpeedBase.Value;
int final = base_stat;
string calc = "[" + base_stat;
// Do the base stats first.
if (traitList.Any(x => x.name == Database.TR_SPE3RD)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.6);
}
else if (traitList.Any(x => x.name == Database.TR_SPE2ND)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.4);
}
else if (traitList.Any(x => x.name == Database.TR_SPE1ST) ||
traitList.Any(x => x.name == Database.TR_MERFOL)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.2);
}
// And then lastly, the Fated Trait.
Add_Fated_Stats(ref final, ref calc, Database.TR_FATESW);
textBox_SpeedFinal.Text = final.ToString();
calc += ']';
label_SpeedCalc.Text = calc;
// Used when Base Strength changes.
// Used when Traits are added.
// Used when Traits are edited
// Used when Traits are removed.
}
private void Update_Stamina_Final() {
// I hate copying pasting code...
int base_stat = (int)numericUpDown_StaminaBase.Value;
int final = base_stat;
string calc = "[" + base_stat;
// Do the base stats first.
if (traitList.Any(x => x.name == Database.TR_STA3RD)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.6);
}
else if (traitList.Any(x => x.name == Database.TR_STA2ND)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.4);
}
else if (traitList.Any(x => x.name == Database.TR_STA1ST)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.2);
}
// And then lastly, the Fated Trait.
Add_Fated_Stats(ref final, ref calc, Database.TR_FATEMI);
textBox_StaminaFinal.Text = final.ToString();
calc += ']';
label_StaminaCalc.Text = calc;
// Used when Base Strength changes.
// Used when Traits are added.
// Used when Traits are edited
// Used when Traits are removed.
}
private void Update_Accuracy_Final() {
// I hate copying pasting code...
int base_stat = (int)numericUpDown_AccuracyBase.Value;
int final = base_stat;
string calc = "[" + base_stat;
// Do the base stats first.
if (traitList.Any(x => x.name == Database.TR_ACC3RD)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.6);
}
else if (traitList.Any(x => x.name == Database.TR_ACC2ND)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.4);
}
else if (traitList.Any(x => x.name == Database.TR_ACC1ST)) {
Stat_Multiplier_Trait(ref final, ref calc, 1.2);
}
// And then lastly, the Fated Trait.
Add_Fated_Stats(ref final, ref calc, Database.TR_FATECU);
textBox_AccuracyFinal.Text = final.ToString();
calc += ']';
label_AccuracyCalc.Text = calc;
// Used when Base Strength changes.
// Used when Traits are added.
// Used when Traits are edited
// Used when Traits are removed.
}
#endregion
#region Update RegTP Functions
private void Update_Used_RegTP() {
int used = 0;
foreach (Technique tech in techList.Values) {
used += tech.regTP;
}
textBox_RegTPUsed.Text = used.ToString();
// Used when Techniques are added.
// Used when Techniques are edited.
// Used when Techniques are removed.
}
private void Update_Total_RegTP() {
double multiplier = 2.0;
int fortune = int.Parse(textBox_Fortune.Text);
string calc = "[" + fortune + " * ";
// Modify multiplier if SD Earned is changed.
int SD_Earned = (int)numericUpDown_SDEarned.Value;
if (SD_Earned > 150 && SD_Earned <= 250) {
multiplier = 2.5;
}
else if (SD_Earned > 250 && SD_Earned <= 350) {
multiplier = 3.0;
}
else if (SD_Earned > 350 && SD_Earned <= 450) {
multiplier = 3.5;
}
else if (SD_Earned > 450 && SD_Earned <= 600) {
multiplier = 4.0;
}
else if (SD_Earned > 600 && SD_Earned <= 800) {
multiplier = 4.5;
}
else if (SD_Earned > 800) {
multiplier = 5.0;
}
// Check AP Tech
multiplier += 0.5 * (double)(numericUpDown_APTech.Value);
int total = (int)((double)fortune * multiplier);
calc += multiplier;
// Now check if we have any Traits that add to this.
if (traitList.Any(x => x.name == Database.TR_TECHMA)) {
// Increase by 100% of Fortune
total += fortune;
calc += " + " + fortune;
}
else if (traitList.Any(x => x.name == Database.TR_TECHAD)) {
// Increase by 40% of Fortune
total += (int)((double)fortune * 0.4);
calc += " + (" + fortune + " * 0.4)";
}
// Update properly.
textBox_RegTPTotal.Text = total.ToString();
calc += ']';
label_RegTPCalc.Text = calc;
// Used when checkbox is listed.
// Used when Fortune is updated.
// Used when SD Earned is changed
// Used when a Trait is added.
// Used when a Trait is removed.
}
#endregion
#region Update Tech Misc Functions
// Helper function for Update_CritAnatQuick_Msg()
private void Print_Applied_Msg(ref string msg, string name) {
int points = int.Parse(textBox_RegTPTotal.Text) / 4;
int num = 0;
msg += name + ": ";
// How many Traits of the there are of the same Trait
if (traitList.Any(x => x.name == name)) {
num += traitList.Find(x => x.name == name).getTotal();
}
int total = num * points;
int used = 0;
foreach (Technique tech in techList.Values) {
if (tech.stats.statsName.Contains(name)) {
used += tech.regTP;
}
}
msg += used + " / " + total + '\n';
}
// This is only for Critical Hit, Anatomical Strike, and Quickstrike
private void Update_CritAnatQuick_Msg() {
string msg = "";
if (traitList.Any(x => x.name == Database.TR_CRITHI)) {
Print_Applied_Msg(ref msg, Database.TR_CRITHI);
}
if (traitList.Any(x => x.name == Database.TR_ANASTR)) {
Print_Applied_Msg(ref msg, Database.TR_ANASTR);
}
if (traitList.Any(x => x.name == Database.TR_QUICKS)) {
Print_Applied_Msg(ref msg, Database.TR_QUICKS);
}
// Trim the newline
msg = msg.TrimEnd('\n');
if (string.IsNullOrWhiteSpace(msg)) {
label_CritAnatQuick.Visible = false;
label_CritAnatQuick.Text = msg;
}
else {
label_CritAnatQuick.Visible = true;
label_CritAnatQuick.Text = msg;
}
// Updated when Technique is Added
// Updated when Technique is Edited
// Updated when Technique is Branched
// Updated when Technique is Removed
// Updated when a Trait is added.
// Updated when a Trait is removed.
// Updated when Total Reg TP is Changed.
}
private void Update_TechNum() {
// This will also properly set the Maximum Values of numericupdown_Row
int num = dgv_Techniques.Rows.Count;
label_TechCount.Text = "Total number of Techniques: " + num;
if (num > 0) {
numericUpDown_RowBegin.Maximum = num - 1;
numericUpDown_RowEnd.Maximum = num - 1;
}
else if (num == 0) {
numericUpDown_RowBegin.Maximum = 0;
numericUpDown_RowEnd.Maximum = 0;
}
// Updated when Technique is Added
// Updated when Technique is Edited
// Updated when Technique is Branched
// Updated when Technique is Removed
}
#endregion
#region Update Category Functions
// Checks to make sure that all Techniques are in Categories
private void Update_SubCatWarning() {
bool loop_break = false;
for (int i = 0; i < listView_SubCat.Items.Count; ++i) {
ListViewItem category = listView_SubCat.Items[i];
if (i == 0 && int.Parse(category.SubItems[0].Text) != 0) {
loop_break = true;
break;
}
if (i == listView_SubCat.Items.Count - 1 &&
int.Parse(category.SubItems[1].Text) != dgv_Techniques.Rows.Count - 1) {
loop_break = true;
break;
}
if (i != listView_SubCat.Items.Count - 1) {
if (int.Parse(category.SubItems[1].Text) + 1 !=
int.Parse(listView_SubCat.Items[i + 1].SubItems[0].Text)) {
// Comparing this category's End Row with the next category's Begin Row
loop_break = true;
break;
}
}
}
if (listView_SubCat.Items.Count == 0) {
label_SubCatWarning.Text = "Note: Adding no Categories will automatically put all Techniques into one table.";
label_SubCatWarning.ForeColor = Color.OrangeRed;
}
else if (loop_break) {
// Display Warning Message
label_SubCatWarning.Text = "WARNING: Some Techniques aren't in Categories! Uncategorized Techniques will not be generated!";
label_SubCatWarning.ForeColor = Color.Red;
}
else {
// All Techniques accounted for!
label_SubCatWarning.Text = "All Techniques are in Categories.";
label_SubCatWarning.ForeColor = Color.Green;
}
// Updated when a SubCategory is Added
// Updated when a SubCategory is Removed
}
#endregion
#endregion
#region Main Form Loading
// This only occurs once before the form is displayed for the first time.
private void MainForm_Load(object sender, EventArgs e) {
Check_Update();
this.Text = "OPRP Character Builder";
label_Title.Text = "OPRP Character Builder";
label1.Text = "OPRP Character Builder v" + VERSION + " designed by Solo";
// ------ Images
listView_Images.View = View.Details;
listView_Images.FullRowSelect = true;
listView_Images.Columns.Add("URL", 300);
listView_Images.Columns.Add("Label", 200);
listView_Images.Columns.Add("FullRes", 56);
listView_Images.Columns.Add("Width", 55);
listView_Images.Columns.Add("Height", 55);
// ------ Traits
Update_Traits_Cap();
// ------ Tech Category Table
label_SubCatMsg.Text = "No Valid Category Selected";
listView_SubCat.View = View.Details;
listView_SubCat.FullRowSelect = true;
listView_SubCat.Sorting = SortOrder.Ascending;
listView_SubCat.Columns.Add("Begin", 50);
listView_SubCat.Columns.Add("End", 50);
listView_SubCat.Columns.Add("Category Name", 166);
// ------ Weaponry Table
listView_Weaponry.View = View.Details;
listView_Weaponry.FullRowSelect = true;
listView_Weaponry.Columns.Add("Name", 150);
listView_Weaponry.Columns.Add("Description", 546);
// ------ Items Table
listView_Items.View = View.Details;
listView_Items.FullRowSelect = true;
listView_Items.Columns.Add("Name", 150);
listView_Items.Columns.Add("Description", 546);
// ------ Template
richTextBox_Template.Text = Sheet.BASIC_TEMPLATE;
// ------ Adding Save Changes Controls
// --- tabPage: Basic Information
foreach (Control c in groupBox_BasicInfo.Controls) {
addAnySaveEvent(c);
}
foreach (Control c in groupBox_Features.Controls) {
addAnySaveEvent(c);
}
richTextBox_Clothing.TextChanged += notSavedEvent;
richTextBox_GeneralAppear.TextChanged += notSavedEvent;
// --- tabPage: Background
foreach (Control c in groupBox_Background.Controls) {
addAnySaveEvent(c);
}
// --- tabPage: Abilities
richTextBox_Combat.TextChanged += notSavedEvent;
foreach (Control c in groupBox_DevilFruit.Controls) {
addAnySaveEvent(c);
}
// --- tabPage: RP Elements
foreach (Control c in groupBox_Stats.Controls) {
addAnySaveEvent(c);
}
foreach (Control c in groupBox_AP.Controls) {
addAnySaveEvent(c);
}
// --- tabPage: Traits
// --- tabPage: Techniques
// --- tabPage: Sources
// --- tabPage: Template
textBox_Color.TextChanged += notSavedEvent;
textBox_MasteryMsg.TextChanged += notSavedEvent;
}
// Helper Function: for TextBox, RichTextBox, ComboBox, NumericUpDown, CheckBox
private void addAnySaveEvent(Control c) {
if (c is TextBox) {
if (((TextBox)c).ReadOnly) { return; }
c.TextChanged += notSavedEvent;
}
else if (c is RichTextBox) {
if (((RichTextBox)c).ReadOnly) { return; }
c.TextChanged += notSavedEvent;
}
else if (c is ComboBox) {
((ComboBox)c).TextChanged += notSavedEvent;
((ComboBox)c).SelectedIndexChanged += notSavedEvent;
}
else if (c is NumericUpDown) {
((NumericUpDown)c).ValueChanged += notSavedEvent;
}
else if (c is CheckBox) {
((CheckBox)c).CheckedChanged += notSavedEvent;
}
}
// The event firing for notSavedStatus()
private void notSavedEvent(object sender, EventArgs e) {
notSavedStatus();
}
// To indicate that the Form is not saved. Happens when something changes
private void notSavedStatus() {
this.Text = this.Text.TrimEnd('*');
this.Text += "*";
saved = false;
}
// To indicate that the Form is saved. Only happens when Save or Save As is pressed
private void isSavedStatus() {
this.Text = this.Text.TrimEnd('*');
saved = true;
}
#endregion
// --------------------------------------------------------------------------------------------
// "BASIC INFORMATION" Tab
// --------------------------------------------------------------------------------------------
#region Basic Character Tab
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e) {
// This is when we change the Affiliation ComboBox. Exception should only happen when we change.
string affiliation = comboBox_Affiliation.Text;
if (affiliation == "Pirate") {
textBox_Bounty.Enabled = true;
numericUpDown_Comm.Enabled = false;
numericUpDown_Comm.Value = 0;
comboBox_MarineRank.Enabled = false;
comboBox_MarineRank.SelectedIndex = -1;
textBox_Threat.Enabled = false;
textBox_Threat.Clear();
}
else if (affiliation == "Marine") {
textBox_Bounty.Enabled = false;
textBox_Bounty.Clear();
numericUpDown_Comm.Enabled = true;
comboBox_MarineRank.Enabled = true;
textBox_Threat.Enabled = false;
textBox_Threat.Clear();
}
else if (affiliation == "Bounty Hunter" || affiliation == "Other") {
textBox_Bounty.Enabled = false;
textBox_Bounty.Clear();
numericUpDown_Comm.Enabled = false;
numericUpDown_Comm.Value = 0;
comboBox_MarineRank.Enabled = false;
comboBox_MarineRank.SelectedIndex = -1;
textBox_Threat.Enabled = true;
}
else {
textBox_Bounty.Enabled = false;
textBox_Bounty.Clear();
numericUpDown_Comm.Enabled = false;
numericUpDown_Comm.Value = 0;
comboBox_MarineRank.Enabled = false;
comboBox_MarineRank.SelectedIndex = -1;
textBox_Threat.Enabled = false;
textBox_Threat.Clear();
}
}
private void numericUpDown_Comm_ValueChanged(object sender, EventArgs e) {
comboBox_MarineRank.Items.Clear();
if (numericUpDown_Comm.Value >= 300) {
string[] admiral = { "Vice Admiral", "Admiral", "Fleet Admiral" };
comboBox_MarineRank.Items.AddRange(admiral);
}
else if (numericUpDown_Comm.Value >= 200) {
comboBox_MarineRank.Items.Add("Rear Admiral");
}
else if (numericUpDown_Comm.Value >= 100) {
comboBox_MarineRank.Items.Add("Commodore");
}
else if (numericUpDown_Comm.Value >= 65) {
comboBox_MarineRank.Items.Add("Captain");
}
else if (numericUpDown_Comm.Value >= 35) {
comboBox_MarineRank.Items.Add("Commander");
}
else if (numericUpDown_Comm.Value >= 20) {
comboBox_MarineRank.Items.Add("Lieutenant Commander");
}
else if (numericUpDown_Comm.Value >= 15) {
comboBox_MarineRank.Items.Add("Lieutenant");
}
else if (numericUpDown_Comm.Value >= 10) {
comboBox_MarineRank.Items.Add("Junior Lieutenant");
}
else if (numericUpDown_Comm.Value >= 5) {
comboBox_MarineRank.Items.Add("Ensign");
}
else {
string[] begRanks = {"Chief Warrant Officer",
"Master Chief Petty Officer", "Chief Petty Officer",
"Petty Officer", "Seaman", "Seaman Apprentice",
"Seaman Recruit", "Apprentice", "Chore Boy"};
comboBox_MarineRank.Items.AddRange(begRanks);
}
// Set to 0
comboBox_MarineRank.SelectedIndex = 0;
}
private void button3_AchieveAdd_Click(object sender, EventArgs e) {
// Achievement "Add" button from the MainForm
Add_Achievement AchievementWin = new Add_Achievement();
if (AchievementWin.NewDialog(ref listBox_Achieve)) { notSavedStatus(); }
// Look above to show how to transfer data between forms. This uses references quite well.
}
private void button_AchieveEdit_Click(object sender, EventArgs e) {
// Achievement "Edit" button from the MainForm
int index = listBox_Achieve.SelectedIndex;
if (index != -1) {
Add_Achievement AchievementWin = new Add_Achievement();
if (AchievementWin.EditDialogue(ref listBox_Achieve, index)) { notSavedStatus(); }
}
}
private void button2_AchieveDelete_Click(object sender, EventArgs e) {
// Achievement "Delete" button from the MainForm
int index = listBox_Achieve.SelectedIndex;
if (index != -1) {
listBox_Achieve.Items.RemoveAt(index);
notSavedStatus();
}
}
private void MoveListBoxItem(int direction) {
// Check selected item
if (listBox_Achieve.SelectedItem == null || listBox_Achieve.SelectedIndex < 0) {
return;
}
int newIndex = listBox_Achieve.SelectedIndex + direction;
// Check bounds
if (newIndex < 0 || newIndex >= listBox_Achieve.Items.Count) {
return;
}
object selected = listBox_Achieve.SelectedItem;
listBox_Achieve.Items.Remove(selected);
listBox_Achieve.Items.Insert(newIndex, selected);
listBox_Achieve.SetSelected(newIndex, true);
notSavedStatus();
}
private void button_UpAchieve_Click(object sender, EventArgs e) {
MoveListBoxItem(-1);
}
private void button_DownAchieve_Click(object sender, EventArgs e) {
MoveListBoxItem(1);
}
private void button_ImageUp_Click(object sender, EventArgs e) {
Move_List_Item(ref listView_Images, "Up");
}
private void button_ImageDown_Click(object sender, EventArgs e) {
Move_List_Item(ref listView_Images, "Down");
}
private void button_ImageAdd_Click(object sender, EventArgs e) {
// Image "Add" button from the MainForm
if (string.IsNullOrWhiteSpace(textBox_ImageURL.Text)) {
MessageBox.Show("Image needs URL", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else {
ListViewItem image = new ListViewItem();
image.SubItems[0].Text = textBox_ImageURL.Text;
image.SubItems.Add(textBox_ImageLabel.Text);
if (checkBox_FullRes.Checked) {
image.SubItems.Add("Yes");
image.SubItems.Add("");
image.SubItems.Add("");
}
else {
image.SubItems.Add("No");
image.SubItems.Add(numericUpDown_Width.Value.ToString());
image.SubItems.Add(numericUpDown_Height.Value.ToString());
}
// Add to ListView
listView_Images.Items.Add(image);
// Clear the information
textBox_ImageLabel.Clear();
textBox_ImageURL.Clear();
checkBox_FullRes.Checked = true;
notSavedStatus();
}
}
private void button_ImageEdit_Click(object sender, EventArgs e) {
// Traits "Edit" button from the MainForm
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
if (listView_Images.SelectedItems.Count == 1) {
textBox_ImageURL.Text = listView_Images.SelectedItems[0].SubItems[0].Text;
textBox_ImageLabel.Text = listView_Images.SelectedItems[0].SubItems[1].Text;
if (listView_Images.SelectedItems[0].SubItems[2].Text == "No") {
checkBox_FullRes.Checked = false;
try { numericUpDown_Width.Value = int.Parse(listView_Images.SelectedItems[0].SubItems[3].Text); }
catch { }
try { numericUpDown_Height.Value = int.Parse(listView_Images.SelectedItems[0].SubItems[4].Text); }
catch { }
}
else {
checkBox_FullRes.Checked = true;
}
// Delete from ListView
Delete_ListViewItem(ref listView_Images);
notSavedStatus();
}
}
private void button_ImageDelete_Click(object sender, EventArgs e) {
// Image "Delete" button
Delete_ListViewItem(ref listView_Images);
}
private void checkBox_FullRes_CheckedChanged(object sender, EventArgs e) {
if (!checkBox_FullRes.Checked) {
numericUpDown_Height.Enabled = true;
numericUpDown_Width.Enabled = true;
}
else {
numericUpDown_Height.Enabled = false;
numericUpDown_Width.Enabled = false;
}
}
#endregion
// --------------------------------------------------------------------------------------------
// "BACKGROUND" Tab
// --------------------------------------------------------------------------------------------
// Nothing
// --------------------------------------------------------------------------------------------
// "COMBAT" Tab
// --------------------------------------------------------------------------------------------
#region Combat Tab
private void button6_WeaponAdd_Click(object sender, EventArgs e) {
// Weapon "Add" button from the MainForm
Add_Equipment EquipmentWin = new Add_Equipment();
if (EquipmentWin.Add_Weapon(ref listView_Weaponry)) { notSavedStatus(); }
}
private void button_WeaponEdit_Click(object sender, EventArgs e) {
// Weapon "Edit" button from the MainForm
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
if (listView_Weaponry.SelectedItems.Count == 1) {
Add_Equipment EquipmentWin = new Add_Equipment();
if (EquipmentWin.Edit_Weapon(ref listView_Weaponry)) { notSavedStatus(); }
}
}
private void button7_WeaponDelete_Click(object sender, EventArgs e) {
// Weapon "Delete" button from the MainForm
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
Delete_ListViewItem(ref listView_Weaponry);
}
private void button_UpWeapon_Click(object sender, EventArgs e) {
Move_List_Item(ref listView_Weaponry, "Up");
}
private void button_DownWeapon_Click(object sender, EventArgs e) {
Move_List_Item(ref listView_Weaponry, "Down");
}
private void button8_ItemsAdd_Click(object sender, EventArgs e) {
// Item "Add" button from the MainForm
Add_Equipment EquipmentWin = new Add_Equipment();
if (EquipmentWin.Add_Item(ref listView_Items)) { notSavedStatus(); }
}
private void button_ItemsEdit_Click(object sender, EventArgs e) {
// Item "Edit" button from the MainForm
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
if (listView_Items.SelectedItems.Count == 1) {
Add_Equipment EquipmentWin = new Add_Equipment();
if (EquipmentWin.Edit_Item(ref listView_Items)) { notSavedStatus(); }
}
}
private void button9_ItemsDelete_Click(object sender, EventArgs e) {
// Item "Delete" button from the MainForm
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
Delete_ListViewItem(ref listView_Items);
}
private void button_UpItem_Click(object sender, EventArgs e) {
Move_List_Item(ref listView_Items, "Up");
}
private void button_DownItem_Click(object sender, EventArgs e) {
Move_List_Item(ref listView_Items, "Down");
}
#endregion
// --------------------------------------------------------------------------------------------
// "RP ELEMENTS" Tab
// --------------------------------------------------------------------------------------------
#region RP Elements Tab
private void numericUpDown_SDEarned_ValueChanged(object sender, EventArgs e) {
// We have to adjust the max value of SD Earned into AP.
numericUpDown_SDintoStats.Maximum = numericUpDown_SDEarned.Value;
numericUpDown_SDintoStats.Value = numericUpDown_SDEarned.Value;
Update_Traits_Cap(); // Trait Cap is based on SD Earned
Update_SD_Remaining();
Update_Total_RegTP();
Update_TotalSD();
}
private void numericUpDown_SDintoStats_ValueChanged(object sender, EventArgs e) {
Update_Stat_Points();
Update_SD_Remaining();
}
private void textBox_StatPoints_TextChanged(object sender, EventArgs e) {
Update_Used_for_Stats();
// Also set the maximum value of Used for Fortune = Stat Points / 4
numericUpDown_UsedForFort.Maximum = int.Parse(textBox_StatPoints.Text) / 4;
Update_Fortune();
// Also set the maximum value of all Base Stats = Stat Points / 2
numericUpDown_StrengthBase.Maximum = int.Parse(textBox_StatPoints.Text) / 2;
numericUpDown_SpeedBase.Maximum = int.Parse(textBox_StatPoints.Text) / 2;
numericUpDown_StaminaBase.Maximum = int.Parse(textBox_StatPoints.Text) / 2;
numericUpDown_AccuracyBase.Maximum = int.Parse(textBox_StatPoints.Text) / 2;
}
private void numericUpDown_UsedForFort_ValueChanged(object sender, EventArgs e) {
// Turn current value into divisible by 5.
int val = (int)numericUpDown_UsedForFort.Value;
val = (val / 5) * 5;
numericUpDown_UsedForFort.Value = val;
Update_Used_for_Stats();
Update_Fortune();
}
private void numericUpDown_StrengthBase_ValueChanged(object sender, EventArgs e) {
Update_Strength_Final();
Update_BaseStats_Check();
}
private void numericUpDown_SpeedBase_ValueChanged(object sender, EventArgs e) {
Update_Speed_Final();
Update_BaseStats_Check();
}
private void numericUpDown_StaminaBase_ValueChanged(object sender, EventArgs e) {
Update_Stamina_Final();
Update_BaseStats_Check();
}
private void numericUpDown_AccuracyBase_ValueChanged(object sender, EventArgs e) {
Update_Accuracy_Final();
Update_BaseStats_Check();
}
private void textBox_Fortune_TextChanged(object sender, EventArgs e) {
Update_Total_RegTP();
Update_SpTraitDGVAndList_Total();
}
private void textBox_UsedForStats_TextChanged(object sender, EventArgs e) {
Update_BaseStats_Check();
}
// Kept track of AP
private void numericUpDown_APTech_ValueChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
Update_Total_RegTP(); // For Tech multiplier
}
private void numericUpDown_APTrait_ValueChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
Update_Traits_Cap(); // For increasing Trait cap
}
private void numericUpDown_APPrime_ValueChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
}
private void numericUpDown_APMulti_ValueChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
}
private void numericUpDown_APNPC_ValueChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
}
private void checkBox_APHaki_CheckedChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
}
private void checkBox_APDF_CheckedChanged(object sender, EventArgs e) {
Update_AP_Count();
Update_TotalSD();
}
// Helper function to event handler button_Standardize
private string Commas_To_Value(uint beli) {
string val = beli.ToString();
for (int i = val.Length - 3; i > 0; i -= 3) {
// Inserting from right to left
val = val.Insert(i, ",");
}
return val;
}
// Standardize beli button
private void button_Standardize_Click(object sender, EventArgs e) {
DialogResult result = new DialogResult();
result = DialogResult.Yes;
result = MessageBox.Show("Is your character scooping in the Grand Line?", "Beli Standardization", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result != DialogResult.Cancel) {
int SD = (int)numericUpDown_SDEarned.Value;
uint beli = 500000;
string message = "You have " + SD + " SD earned. Calculations:\n+ 500,000 (Starting Beli)";
if (SD <= 50) {
beli += (uint)(250000 * SD);
message += "\n+ " + Commas_To_Value((uint)(250000 * SD)) + " (250,000 / SD for first 50)";
}
else {
beli += 250000 * 50;
message += "\n+ " + Commas_To_Value((uint)(250000 * 50)) + " (250,000 / SD for first 50)";
}
SD -= 50;
if (result == DialogResult.Yes) {
// In the GL, it's 500,000 per SD
if (SD > 0) {
beli += (uint)(500000 * SD);
message += "\n+ " + Commas_To_Value((uint)(500000 * SD)) + " (500,000 / SD in GL)";
}
}
else {
// In the Blues, it's 500,000 per SD
if (SD > 0) {
beli += (uint)(250000 * SD);
message += "\n+ " + Commas_To_Value((uint)(250000 * SD)) + " (250,000 / SD in Blues)";
}
}
// Apply beli trait / professional boosts (do not stack)
// Look for Traits bonus of 20%
if (traitList.Any(x => x.name == "Pickpocket") || traitList.Any(x => x.name == "Tough Bargainer")) {
uint addBeli = beli / 5;
beli += addBeli;
message += "\n+ " + Commas_To_Value(addBeli) + " (20% beli Trait Bonus)";
}
// Look for Thief primary bonus of 10%
else if (Is_Prof_Primary("Thief")) {
uint addBeli = beli / 10;
beli += addBeli;
message += "\n+ " + Commas_To_Value(addBeli) + " (10% beli Thief Primary)";
}
// Show calculations
string final_beli = Commas_To_Value(beli);
message += "\n= " + final_beli + " (FINAL undeducted Value)";
MessageBox.Show(message, "Beli Standardized");
textBox_Beli.Text = final_beli;
}
}
// Move a Profession up a row
private void button_UpProf_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Professions, "Up");
}
// Move a Profession down a row
private void button_DownProf_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Professions, "Down");
}
// Profession "Add" button from the MainForm
private void button_AddProf_Click(object sender, EventArgs e) {
Add_Profession ProfessionWin = new Add_Profession();
if (ProfessionWin.NewDialog(ref dgv_Professions, ref profList)) { notSavedStatus(); }
}
// Profession "Edit" button from the MainForm
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
private void button_EditProf_Click(object sender, EventArgs e) {
try {
Add_Profession ProfessionWin = new Add_Profession();
if (ProfessionWin.EditDialog(ref dgv_Professions, ref profList)) { notSavedStatus(); }
}
catch (Exception ex) {
MessageBox.Show("Error in editing Profession.\nReason: " + ex.Message);
}
}
// Profession "Delete" button from the MainForm
private void button_DeleteProf_Click(object sender, EventArgs e) {
try {
if (dgv_Professions.SelectedCells.Count > 0) {
// Remove from Dict
string prof = dgv_Professions.SelectedRows[0].Cells[0].Value.ToString();
profList.Remove(prof);
// Remove from dgv
int remove_index = dgv_Professions.SelectedRows[0].Index;
dgv_Professions.Rows.RemoveAt(remove_index);
dgv_Professions.Refresh();
notSavedStatus();
}
}
catch (Exception ex) {
MessageBox.Show("Error in deleting Profession.\nReason: " + ex.Message, "Exception Thrown");
}
}
#endregion
// --------------------------------------------------------------------------------------------
// "TRAITS" Tab
// --------------------------------------------------------------------------------------------
#region Traits Tab
#region Update SpTP Functions
// HELPER FUNCTION
private void Helper_SpTrait_UsedOverTotal() {
// After update of those values, we will then check to see if Used > Total
foreach (DataGridViewRow SpTraitRow in dgv_SpTraits.Rows) {
if (int.Parse(SpTraitRow.Cells[1].Value.ToString()) > int.Parse(SpTraitRow.Cells[2].Value.ToString())) {
SpTraitRow.Cells[1].Style.BackColor = Color.FromArgb(255, 128, 128);
}
else {
SpTraitRow.Cells[1].Style.BackColor = SystemColors.Control;
}
}
}
private void Update_Used_SpTP_Textbox() {
// Updates the Used SpTP Textbox
int used = 0;
foreach (SpTrait spTrait in spTraitList) {
used += spTrait.usedTP;
}
textBox_SpTPUsed.Text = used.ToString();
}
private void Update_Total_SpTP_Textbox() {
// Updates the Total SpTP Textbox
int total_SP = 0;
foreach (SpTrait spTrait in spTraitList) {
total_SP += spTrait.totalTP;
}
textBox_SpTPTotal.Text = total_SP.ToString();
}
// Adds the Sp Trait into the list.
// param traitName is for all getName() purposes
private void Add_SpTrait(string traitName) {
// First check to see if the Sp. TP Trait is in the list
// If so, add the trait into the ListView Special and add correspondingly.
int fortune = int.Parse(textBox_Fortune.Text);
Trait sel_Trait = traitList.Find(x => x.getName() == traitName);
int divisor = Database.getSpTraitDiv(sel_Trait.name);
string spTraitName = "";
if (divisor > 0) {
// Add Sp. Trait to the Dict
int traitNum = sel_Trait.getTotal();
string customName = sel_Trait.getName();
int totTP = (fortune / divisor) * traitNum;
SpTrait addSpTrait = new SpTrait(traitName, customName, 0, totTP);
spTraitName = addSpTrait.getName();
spTraitList.Add(addSpTrait);
// Add Sp. Trait to the dgv
dgv_SpTraits.Rows.Add(addSpTrait.getName(), 0, totTP);
}
// Lastly update the Total SpTP
Update_SpTraitDGVAndList_Total();
Update_SpTraitDGVAndList_Used(spTraitName);
// Used when a Trait is added.
}
private void Remove_SpTrait(SpTrait removeTrait) {
if (removeTrait == null) { return; }
// Remove from Dict
spTraitList.Remove(removeTrait);
// Remove from ListView
foreach (DataGridViewRow SpTraitRow in dgv_SpTraits.Rows) {
if (SpTraitRow.Cells[0].Value.ToString() == removeTrait.getName()) {
dgv_SpTraits.Rows.Remove(SpTraitRow);
dgv_SpTraits.Refresh();
break;
}
}
Update_SpTraitDGVAndList_Total();
Update_SpTraitDGVAndList_Used(removeTrait.getName());
// Used when a Trait is removed.
}
private void Update_SpTraitDGVAndList_Total() {
// This updates all the Total Sp Traits
int fortune = int.Parse(textBox_Fortune.Text);
foreach (DataGridViewRow SpTraitRow in dgv_SpTraits.Rows) {
string spName = SpTraitRow.Cells[0].Value.ToString(); // This is getting getTraitName()
Trait traitName = traitList.Find(x => x.getName() == spName);
int traitNum = traitName.getTotal();
int divisor = Database.getSpTraitDiv(traitName.name); //#TODO: CAN'T USE SPNAME!!!
int totTP = (fortune / divisor) * traitNum;
// Edit spTraitList
spTraitList.Find(x => x.getName() == spName).totalTP = totTP;
// Edit ListView
SpTraitRow.Cells[2].Value = totTP;
}
// Update the Total textboxes
Update_Total_SpTP_Textbox();
// After update of those values, we will then check to see if Used > Total
Helper_SpTrait_UsedOverTotal();
// Used when Fortune is updated.
// Used when Trait is added/edited/removed.
}
// Update values inside the table based on Techniques or Fortune edited.
private void Update_SpTraitDGVAndList_Used(string traitName) {
// This is using traitName as from Trait.getName()
// Update SpTraitList first, then the ListView
if (string.IsNullOrWhiteSpace(traitName)) { return; }
int used = 0;
foreach (Technique tech in techList.Values) {
if (tech.specialTrait == traitName) {
used += tech.spTP;
}
}
// Edit spTraitList, if it still exists
try {
spTraitList.Find(x => x.getName() == traitName).usedTP = used;
// Edit ListView
foreach (DataGridViewRow SpTraitRow in dgv_SpTraits.Rows) {
if (SpTraitRow.Cells[0].Value.ToString() == traitName) {
SpTraitRow.Cells[1].Value = used.ToString();
break;
}
}
}
catch { }
// Update the Used textboxes
Update_Used_SpTP_Textbox();
// After update of those values, we will then check to see if Used > Total
Helper_SpTrait_UsedOverTotal();
// Used when a Technique is added/edited/branched/removed.
// Used when Trait is added/edited/removed.
}
#endregion
// Put name as None if we're deleting
private void All_Update_Functions_Traits() {
Update_Traits_Count_Label();
Update_Fortune();
Update_Strength_Final();
Update_Stamina_Final();
Update_Speed_Final();
Update_Accuracy_Final();
Update_Total_RegTP();
Update_CritAnatQuick_Msg();
notSavedStatus();
}
// Traits "Add" button from the MainForm
private void button11_TraitAdd_Click(object sender, EventArgs e) {
Add_Trait TraitWin = new Add_Trait();
string name = TraitWin.NewDialog(ref dgv_Traits, ref traitList);
// And lastly all Update functions
if (name != null) {
All_Update_Functions_Traits();
Add_SpTrait(name);
}
}
// Traits "Edit" button from the MainForm
private void button_EditTrait_Click(object sender, EventArgs e) {
if (dgv_Traits.SelectedRows.Count == 0) { return; }
Add_Trait TraitWin = new Add_Trait();
string oldName = dgv_Traits.SelectedRows[0].Cells[0].Value.ToString();
string oldCustName = dgv_Traits.SelectedRows[0].Cells[1].Value.ToString();
string newName = TraitWin.EditDialog(ref dgv_Traits, ref traitList);
if (newName != null) {
All_Update_Functions_Traits();
SpTrait oldSpTrait = spTraitList.Find(x => x.name == oldName && x.custom == oldCustName);
Remove_SpTrait(oldSpTrait);
Add_SpTrait(newName);
}
}
// Traits "Delete" button from the MainForm
private void button10_TraitsDelete_Click(object sender, EventArgs e) {
// This is completely assuming that only one row can be selected (which we set MultiSelect = false)
if (dgv_Traits.SelectedRows.Count == 0) { return; }
// Remove from List
string traitName = dgv_Traits.SelectedRows[0].Cells[0].Value.ToString();
string custName = dgv_Traits.SelectedRows[0].Cells[1].Value.ToString();
try {
Trait removeTrait = traitList.Find(x => x.name == traitName && x.custom == custName);
traitList.Remove(removeTrait);
// Remove from dgv
int remove_index = dgv_Traits.SelectedRows[0].Index;
dgv_Traits.Rows.RemoveAt(remove_index);
dgv_Traits.Refresh();
// All update Functions
All_Update_Functions_Traits();
SpTrait removeSpTrait = spTraitList.Find(x => x.name == traitName && x.custom == custName);
Remove_SpTrait(removeSpTrait);
}
catch (Exception ex) {
MessageBox.Show("Error in deleting Trait.\nReason: " + ex.Message, "Exception Thrown");
}
}
// Move Trait row up
private void button_TraitsUp_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Traits, "Up");
}
// Move Trait row down
private void button_TraitsDown_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Traits, "Down");
}
// Sort by Trait Type
private void dgv_Traits_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
if (e.Column.Index == 2) {
e.Handled = true;
e.SortResult = compareTraitTypes(e.CellValue1, e.CellValue2);
}
}
// Comparator for the above function
private int compareTraitTypes(object o1, object o2) {
int o1Worth = (o1.ToString() == "General") ? 1 :
(o1.ToString() == "General / Professional") ? 0 : -1;
int o2Worth = (o2.ToString() == "General") ? 1 :
(o2.ToString() == "General / Professional") ? 0 : -1;
return o1Worth.CompareTo(o2Worth);
}
#endregion
// --------------------------------------------------------------------------------------------
// "TECHNIQUES" Tab
// --------------------------------------------------------------------------------------------
#region Techniques Tab
private void All_Update_Functions_Techs(string traitName) {
Update_SpTraitDGVAndList_Used(traitName);
Update_Used_RegTP();
Update_CritAnatQuick_Msg();
Update_TechNum();
notSavedStatus();
}
private void listView3_SpTP_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) {
// Prevents users from changing column width
e.Cancel = true;
e.NewWidth = dgv_SpTraits.Columns[e.ColumnIndex].Width;
}
private void button14_TechAdd_Click(object sender, EventArgs e) {
// Technique "Add" button from the MainForm
int fortune = int.Parse(textBox_Fortune.Text);
int num_items = dgv_Techniques.Rows.Count;
if (num_items == 0) { num_items++; } // What if empty?
Add_Technique TechniqueWin = new Add_Technique(fortune, profList,
traitList, spTraitList, makeDFClass(), false, false, null);
string newName = TechniqueWin.NewDialog(ref dgv_Techniques, ref techList, num_items - 1);
// Update functions go below
if (!string.IsNullOrWhiteSpace(newName)) {
string spTrait = techList[newName].specialTrait;
All_Update_Functions_Techs(spTrait);
}
}
private void button_TechBranch_Click(object sender, EventArgs e) {
// Technique "Branch" button from the MainForm
if (dgv_Techniques.SelectedRows.Count == 0) { return; }
string TechName = dgv_Techniques.SelectedRows[0].Cells[0].Value.ToString();
int index = dgv_Techniques.SelectedRows[0].Index;
if (!string.IsNullOrWhiteSpace(TechName)) {
int fortune = int.Parse(textBox_Fortune.Text);
int max_rank = fortune / 2;
Technique selTech = techList[TechName];
if (selTech.rokuName != Database.ROKU_NON &&
!traitList.Any(x => x.name == Database.TR_ROKUMA)) {
// ^If the Selected Technique is Rokushiki and character does not have Rokushiki Master
MessageBox.Show("You can't edit a Rokushiki Technique without the Rokushiki Master Trait.", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else if (selTech.rank + 4 > max_rank) {
// A branched technique must have at least 4 ranks from the Technique they are branching from
MessageBox.Show("A branched Technique must be 4 ranks higher than the Technique they are branching from\n" +
"Branching this Technique would cause you to go over your Max Rank [" + max_rank + "]", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
Add_Technique TechniqueWin = new Add_Technique(fortune, profList, traitList,
spTraitList, makeDFClass(), true, false, selTech);
string newName = TechniqueWin.NewDialog(ref dgv_Techniques, ref techList, index);
// Update functions go below
if (!string.IsNullOrWhiteSpace(newName)) {
string spTrait = techList[newName].specialTrait;
All_Update_Functions_Techs(spTrait);
}
}
}
}
private void button_TechEdit_Click(object sender, EventArgs e) {
// Technique "Edit" button from the MainForm
if (dgv_Techniques.SelectedRows.Count == 0) { return; }
string TechName = dgv_Techniques.SelectedRows[0].Cells[0].Value.ToString();
if (!string.IsNullOrWhiteSpace(TechName)) {
int fortune = int.Parse(textBox_Fortune.Text);
Technique selTech = techList[TechName];
if (selTech.rokuName != Database.ROKU_NON &&
!traitList.Any(x => x.name == Database.TR_ROKUMA)) {
// ^If the Selected Technique is Rokushiki and character does not have Rokushiki Master
MessageBox.Show("You can't edit a Rokushiki Technique without the Rokushiki Master Trait!", "Error",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else {
Add_Technique TechniqueWin = new Add_Technique(fortune, profList, traitList,
spTraitList, makeDFClass(), false, true, selTech);
string newName = TechniqueWin.EditDialog(ref dgv_Techniques, ref techList);
// Update functions go below
if (!string.IsNullOrWhiteSpace(newName)) {
string spTrait = techList[newName].specialTrait;
All_Update_Functions_Techs(spTrait);
}
}
}
}
private void button13_TechDelete_Click(object sender, EventArgs e) {
// Technique "Delete" button from the MainForm
if (dgv_Techniques.SelectedRows.Count == 0) { return; }
DialogResult result = MessageBox.Show("Are you sure you want to delete \"" +
dgv_Techniques.SelectedRows[0].Cells[0].Value.ToString() + "\"?", "Remove Tech",
MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
string techName = dgv_Techniques.SelectedRows[0].Cells[0].Value.ToString();
try {
// Remove from Dict
string spTrait = "";
if (!string.IsNullOrWhiteSpace(techName)) {
spTrait = techList[techName].specialTrait;
techList.Remove(techName);
}
// Remove from dgv
int remove_index = dgv_Techniques.SelectedRows[0].Index;
dgv_Techniques.Rows.RemoveAt(remove_index);
dgv_Techniques.Refresh();
// Update functions go below
All_Update_Functions_Techs(spTrait);
}
catch (Exception ex) {
MessageBox.Show("Error in deleting Technique.\nReason: " + ex.Message, "Exception Thrown");
}
}
}
private void button_UpTech_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Techniques, "Up");
}
private void button_DownTech_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Techniques, "Down");
}
private void textBox_RegTPUsed_TextChanged(object sender, EventArgs e) {
if (int.Parse(textBox_RegTPUsed.Text) > int.Parse(textBox_RegTPTotal.Text)) {
textBox_RegTPUsed.BackColor = Color.FromArgb(255, 128, 128);
}
else {
textBox_RegTPUsed.BackColor = SystemColors.Control;
}
}
private void textBox_SpTPUsed_TextChanged(object sender, EventArgs e) {
if (int.Parse(textBox_SpTPUsed.Text) > int.Parse(textBox_SpTPTotal.Text)) {
textBox_SpTPUsed.BackColor = Color.FromArgb(255, 128, 128);
}
else {
textBox_SpTPUsed.BackColor = SystemColors.Control;
}
}
private void textBox_RegTPTotal_TextChanged(object sender, EventArgs e) {
Update_CritAnatQuick_Msg();
}
// To indicate which Row is selected for Categories
private void dgv_Techniques_SelectionChanged(object sender, EventArgs e) {
try {
int row = dgv_Techniques.SelectedRows[0].Index;
label_RowNum.Text = "Row " + row + " Selected";
}
catch {
label_RowNum.Text = "Select a Technique to see which Row it is in.";
}
}
private void button_SubCatAdd_Click(object sender, EventArgs e) {
if (numericUpDown_RowEnd.Value < numericUpDown_RowBegin.Value) {
MessageBox.Show("Row Begin must be a lower value (or equal to) than Row End.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else if (string.IsNullOrWhiteSpace(textBox_SubCat.Text)) {
MessageBox.Show("Category needs a name.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
else if (dgv_Techniques.Rows.Count < 1) {
MessageBox.Show("You have no Techniques.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var rowBeg = numericUpDown_RowBegin.Value;
var rowEnd = numericUpDown_RowEnd.Value;
ListViewItem item = new ListViewItem();
item.SubItems[0].Text = rowBeg.ToString();
item.SubItems.Add(rowEnd.ToString());
item.SubItems.Add(textBox_SubCat.Text);
// Reset options
numericUpDown_RowBegin.Value = 0;
numericUpDown_RowEnd.Value = 0;
textBox_SubCat.Clear();
// Add to ListView
item.Selected = true;
listView_SubCat.Items.Add(item);
listView_SubCat.ListViewItemSorter = new ListViewItemNumberSort(0);
listView_SubCat.Sort();
// Locate where it is, and then adjust numbers above & below row.
int newIndex = listView_SubCat.Items.IndexOf(item);
if (newIndex > 0) {
listView_SubCat.Items[newIndex - 1].SubItems[1].Text = (rowBeg - 1).ToString();
}
if (newIndex < listView_SubCat.Items.Count - 1) {
listView_SubCat.Items[newIndex + 1].SubItems[0].Text = (rowEnd + 1).ToString();
}
Update_SubCatWarning();
notSavedStatus();
}
private void button_SubCatEdit_Click(object sender, EventArgs e) {
if (listView_SubCat.SelectedItems.Count == 1) {
try {
int begin = int.Parse(listView_SubCat.SelectedItems[0].SubItems[0].Text);
int end = int.Parse(listView_SubCat.SelectedItems[0].SubItems[1].Text);
if (begin > numericUpDown_RowBegin.Maximum) { numericUpDown_RowBegin.Value = numericUpDown_RowBegin.Maximum; }
else { numericUpDown_RowBegin.Value = begin; }
if (end > numericUpDown_RowEnd.Maximum) { numericUpDown_RowEnd.Value = numericUpDown_RowEnd.Maximum; }
else { numericUpDown_RowEnd.Value = end; }
textBox_SubCat.Text = listView_SubCat.SelectedItems[0].SubItems[2].Text;
Delete_ListViewItem(ref listView_SubCat);
Update_SubCatWarning();
notSavedStatus();
}
catch {
MessageBox.Show("Error in editing Category.", "Exception Thrown", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
private void button_SubCatClear_Click(object sender, EventArgs e) {
if (MessageBox.Show("Are you sure you want to clear the Categories?", "Clear Categories",
MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) {
listView_SubCat.Items.Clear();
Update_SubCatWarning();
notSavedStatus();
}
}
private void listView_SubCat_SelectedIndexChanged(object sender, EventArgs e) {
if (listView_SubCat.SelectedItems.Count == 1) {
try {
int begin_ind = int.Parse(listView_SubCat.SelectedItems[0].SubItems[0].Text);
int end_ind = int.Parse(listView_SubCat.SelectedItems[0].SubItems[1].Text);
string begin_str = dgv_Techniques.Rows[begin_ind].Cells[0].Value.ToString();
string end_str = dgv_Techniques.Rows[end_ind].Cells[0].Value.ToString();
string name = listView_SubCat.SelectedItems[0].SubItems[2].Text;
label_SubCatMsg.Text = "Selected Category: (" + name + ")\n" +
"FROM [" + begin_str + "] TO [" + end_str + ']';
}
catch {
label_SubCatMsg.Text = "No Valid Category Selected";
}
}
}
private void listView_SubCat_ColumnWidthChanging(object sender, ColumnWidthChangingEventArgs e) {
// Prevents users from changing column width
e.Cancel = true;
e.NewWidth = listView_SubCat.Columns[e.ColumnIndex].Width;
}
#endregion
// --------------------------------------------------------------------------------------------
// "SOURCES" Tab
// --------------------------------------------------------------------------------------------
#region Sources Tab
// NOTE: IN V1.7.0 A LIST WILL BE BINDED TO A BINDINGSOURCE
// Helper function for changing the SD numericupdown
private void update_SD_Sources() {
if (checkBox_CalcSD.Checked) {
int totalSD = 0;
foreach (Source source in sourceList.Values) {
totalSD += source.SD;
}
int AP_num = int.Parse(textBox_AP.Text);
numericUpDown_SDEarned.Value = totalSD - (AP_num * 50);
}
}
// Helper function for changing Beli textbox
private void update_Beli_Sources() {
if (checkBox_CalcBeli.Checked) {
int totalBeli = 0;
foreach (Source source in sourceList.Values) {
totalBeli += source.beli;
}
textBox_Beli.Text = totalBeli.ToString("N0");
}
}
// Combining update_source functions
private void update_All_Sources() {
update_SD_Sources();
update_Beli_Sources();
notSavedStatus();
}
// Remembering the state of the dateTimeStamp check
bool timeStampBool = false;
// Adds a Source
private void button_AddSource_Click(object sender, EventArgs e) {
// Add Windows Dialog and check if confirmed
Add_Source source_Win = new Add_Source();
source_Win.new_Dialog(ref dgv_Sources, ref sourceList,
radioButton_DateNA.Checked, ref timeStampBool);
// Update current SD if checked
update_All_Sources();
}
// Edits a row
private void dataGridView_Sources_CellDoubleClick(object sender, DataGridViewCellEventArgs e) {
if (dgv_Sources.SelectedRows.Count > 0 && e.ColumnIndex != 0) {
Add_Source source_Win = new Add_Source();
source_Win.edit_Dialog(ref dgv_Sources, ref sourceList,
radioButton_DateNA.Checked, ref timeStampBool);
}
// Update current SD if checked
update_All_Sources();
}
// Deletes a row
private void dataGridView_Sources_CellContentClick(object sender, DataGridViewCellEventArgs e) {
try {
DataGridView dgv = (DataGridView)sender;
DataGridViewRow item = dgv.Rows[e.RowIndex];
if (dgv.Columns[e.ColumnIndex] is DataGridViewButtonColumn && e.RowIndex >= 0) {
// Remove from Dict
string del_title = item.Cells[2].Value.ToString();
sourceList.Remove(del_title);
// Button Clicked for that row.
dgv.Rows.RemoveAt(item.Index);
dgv.Refresh();
// Update current SD if checked
update_All_Sources();
}
}
catch { } // Any implicit clicking exception errors
}
private const string DEVH_KEY = "OPRPdevHMay2017";
// Loads the devh file, overriding the dgv and sourceList
private void button_LoadDevH_Click(object sender, EventArgs e) {
if (MessageBox.Show("Are you sure you want to overwrite the current existing Sources?", "Load DevH",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) {
return;
}
OpenFileDialog dlgFileOpen = new OpenFileDialog();
dlgFileOpen.Filter = "DEVH files (*.devh)|*.devh";
dlgFileOpen.Title = "Open Development History";
dlgFileOpen.RestoreDirectory = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK) {
string devH_data;
try {
string path = dlgFileOpen.FileName;
string encrypted = File.ReadAllText(path);
devH_data = Serialize.decryptData(encrypted, DEVH_KEY);
profile.loadCharSources(ref sourceList, ref dgv_Sources,
ref radioButton_DateNA, true, devH_data);
notSavedStatus();
}
catch (Exception ex) {
MessageBox.Show("Failed to load.\nReason: " + ex.Message,
"Failed to Open", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
// Saves the current sourceList into a devh file
private void button_SaveDevH_Click(object sender, EventArgs e) {
SaveFileDialog fileDialogSaveProject = new SaveFileDialog();
fileDialogSaveProject.Filter = "DEVH files (*.devh)|*.devh";
fileDialogSaveProject.Title = "Save New Development History";
fileDialogSaveProject.OverwritePrompt = true;
if (fileDialogSaveProject.ShowDialog() == DialogResult.OK) {
try {
string data = profile.saveCharSources(dgv_Sources, sourceList, radioButton_DateNA, true);
string path = fileDialogSaveProject.FileName;
string saveData = Serialize.encryptData(data, DEVH_KEY);
using (StreamWriter newTask = new StreamWriter(path, false)) {
newTask.Write(saveData);
}
MessageBox.Show("Development History saved successfully!", "Success",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex) {
MessageBox.Show("Failed to save.\nReason: " + ex.Message,
"Failed to Open", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
// Change SD numericupdown value when True
private void checkBox_CalcSD_CheckedChanged(object sender, EventArgs e) {
update_SD_Sources();
}
// Change Beli numericupdown value when True
private void checkBox_CalcBeli_CheckedChanged(object sender, EventArgs e) {
update_Beli_Sources();
}
// Changes date format to NA (MM/DD/YYYY) when True in dgv
private void radioButton_DateNA_CheckedChanged(object sender, EventArgs e) {
if (radioButton_DateNA.Checked) {
foreach (DataGridViewRow row in dgv_Sources.Rows) {
string[] date = row.Cells[1].Value.ToString().Split('/');
// Standard swap
string temp = date[0];
date[0] = date[1];
date[1] = temp;
row.Cells[1].Value = string.Join("/", date);
}
notSavedStatus();
}
}
// Changes date format to EU (DD/MM/YYYY) when True in dgv
private void radioButton_DateEU_CheckedChanged(object sender, EventArgs e) {
if (radioButton_DateEU.Checked) {
foreach (DataGridViewRow row in dgv_Sources.Rows) {
string[] date = row.Cells[1].Value.ToString().Split('/');
// Standard swap
string temp = date[0];
date[0] = date[1];
date[1] = temp;
row.Cells[1].Value = string.Join("/", date);
}
notSavedStatus();
}
}
// Moves Row up
private void button_UpSource_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Sources, "Up");
}
// Moves Row down
private void button_DownSource_Click(object sender, EventArgs e) {
Move_DGV_Item(ref dgv_Sources, "Down");
}
// Sorts all the rows by date
private void dataGridView_Sources_SortCompare(object sender, DataGridViewSortCompareEventArgs e) {
if (e.Column.Index == 1) {
e.Handled = true;
e.SortResult = compareDates(e.CellValue1, e.CellValue2);
}
}
// Comparator function for the sorting
private int compareDates(object o1, object o2) {
// Need to sort based on either NA or EU date
if (string.IsNullOrWhiteSpace(o1.ToString())) { return -1; }
if (string.IsNullOrWhiteSpace(o2.ToString())) { return 1; }
int[] dateFormat = (radioButton_DateNA.Checked) ? new int[3] { 2, 0, 1 } : new int[3] { 2, 1, 0 };
string[] date1 = o1.ToString().Split('/');
string[] date2 = o2.ToString().Split('/');
// 3 Dates to reresent Month, Day, Year
int result = 0;
for (int i = 0; i < 3; ++i) {
int ind = dateFormat[i];
result = int.Parse(date1[ind]).CompareTo(int.Parse(date2[ind]));
// 0 means the number is the same
if (result == 0) { continue; }
else { break; }
}
return result;
}
#endregion
// --------------------------------------------------------------------------------------------
// "TEMPLATE" Tab
// --------------------------------------------------------------------------------------------
#region Template Tab
private void button_LoadTemp_Click(object sender, EventArgs e) {
Import_Template();
}
private void button_ResetTemp_Click(object sender, EventArgs e) {
if (template_imported) { notSavedStatus(); }
template_imported = false;
label_TemplateType.Text = STD_TEMPLATE_MSG;
label_TemplateType.ForeColor = Color.Green;
richTextBox_Template.Text = Sheet.BASIC_TEMPLATE;
}
private void button_MoreTemplate_Click(object sender, EventArgs e) {
try {
if (MessageBox.Show("Would you like to open a browser to the Zetaboard page?", "Custom Templates",
MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) {
Process.Start("http://s1.zetaboards.com/One_Piece_RP/topic/6153426/1/");
}
}
catch (Exception ex) {
MessageBox.Show("Error in opening up Zetaboards site.\nReason: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void richTextBox_Template_TextChanged(object sender, EventArgs e) {
notSavedStatus();
}
#endregion
// --------------------------------------------------------------------------------------------
// Main Form Miscellaneous
// --------------------------------------------------------------------------------------------
#region Save, Open, Import, Load, Form, Generate Miscellaneous
// This completely resets the form back to its Loaded state.
private void resetForm() {
// Basic Character
textBox_CharacterName.Clear();
textBox_Nickname.Clear();
numericUpDown_Age.Value = 7;
comboBox_Gender.SelectedIndex = -1;
textBox_Race.Clear();
textBox_Position.Clear();
comboBox_Affiliation.SelectedIndex = -1;
textBox_Bounty.Clear();
numericUpDown_Comm.Value = 0;
comboBox_MarineRank.SelectedIndex = -1;
textBox_Threat.Clear();
listBox_Achieve.Items.Clear();
dgv_Professions.Rows.Clear();
dgv_Professions.Refresh();
profList.Clear();
textBox_Height.Clear();
textBox_Weight.Clear();
richTextBox_Hair.Clear();
richTextBox_Eye.Clear();
richTextBox_Clothing.Clear();
richTextBox_GeneralAppear.Clear();
listView_Images.Items.Clear();
textBox_ImageURL.Clear();
textBox_ImageLabel.Clear();
checkBox_FullRes.Checked = true;
numericUpDown_Width.Value = 640;
numericUpDown_Height.Value = 480;
// Background
textBox_Island.Clear();
comboBox_Region.SelectedIndex = -1;
richTextBox_Personality.Clear();
richTextBox_History.Clear();
// Abilities
richTextBox_Combat.Clear();
listView_Weaponry.Items.Clear();
listView_Items.Items.Clear();
textBox_Beli.Clear();
textBox_DFName.Clear();
comboBox_DFType.SelectedIndex = -1;
comboBox_DFTier.SelectedIndex = -1;
richTextBox_DFDesc.Clear();
// Stats
numericUpDown_SDEarned.Value = 0;
numericUpDown_SDintoStats.Value = 0;
numericUpDown_APTech.Value = 0;
numericUpDown_APTrait.Value = 0;
numericUpDown_APPrime.Value = 0;
numericUpDown_APMulti.Value = 0;
numericUpDown_APNPC.Value = 0;
checkBox_APHaki.Checked = false;
checkBox_APDF.Checked = false;
textBox_AP.Text = "0";
textBox_Focus.Text = "0";
numericUpDown_UsedForFort.Value = 0;
numericUpDown_StrengthBase.Value = 1;
numericUpDown_SpeedBase.Value = 1;
numericUpDown_StaminaBase.Value = 1;
numericUpDown_AccuracyBase.Value = 1;
// Traits
dgv_Traits.Rows.Clear();
dgv_Traits.Refresh();
traitList.Clear();
// Techniques
dgv_SpTraits.Rows.Clear();
dgv_SpTraits.Refresh();
spTraitList.Clear();
label_CritAnatQuick.Text = "";
dgv_Techniques.Rows.Clear();
dgv_Techniques.Refresh();
Update_TechNum();
techList.Clear();
listView_SubCat.Items.Clear();
textBox_SubCat.Clear();
// Sources
dgv_Sources.Rows.Clear();
dgv_Sources.Refresh();
sourceList.Clear();
// Templates
label_TemplateType.Text = "Standard Template";
label_TemplateType.ForeColor = Color.Green;
richTextBox_Template.Text = Sheet.BASIC_TEMPLATE;
textBox_Color.Clear();
textBox_MasteryMsg.Text = "* denotes +4 Rank Mastery";
// Update Functions (that are still needed)
Update_AP_Count();
Update_Strength_Final();
Update_Speed_Final();
Update_Stamina_Final();
Update_Accuracy_Final();
Update_Traits_Cap();
Update_Traits_Count_Label();
Update_Total_RegTP();
Update_Used_RegTP();
textBox_SpTPTotal.Text = "0";
textBox_SpTPUsed.Text = "0";
// Reset save status
isSavedStatus();
}
// Saves the form into a serialized object so that only the tool recognizes the Saved Form
private void saveFormToCharacter() {
profile.saveCharResetData();
profile.saveCharBasic(
textBox_CharacterName.Text,
textBox_Nickname.Text,
(int)numericUpDown_Age.Value,
comboBox_Gender.Text,
textBox_Race.Text,
textBox_Position.Text,
comboBox_Affiliation.Text,
textBox_Bounty.Text,
(int)numericUpDown_Comm.Value,
comboBox_MarineRank.Text,
textBox_Threat.Text,
listBox_Achieve,
dgv_Professions,
profList
);
profile.saveCharAppearance(
textBox_Height.Text,
textBox_Weight.Text,
richTextBox_Hair.Text,
richTextBox_Eye.Text,
richTextBox_Clothing.Text,
richTextBox_GeneralAppear.Text,
listView_Images
);
profile.saveCharBackground(
textBox_Island.Text,
comboBox_Region.Text,
richTextBox_Personality.Text,
richTextBox_History.Text
);
profile.saveCharCombat(
richTextBox_Combat.Text,
listView_Weaponry,
listView_Items,
textBox_Beli.Text,
makeDFClass()
);
profile.saveCharStats(
(int)numericUpDown_SDEarned.Value,
(int)numericUpDown_SDintoStats.Value,
(int)numericUpDown_UsedForFort.Value,
(int)numericUpDown_StrengthBase.Value,
(int)numericUpDown_SpeedBase.Value,
(int)numericUpDown_StaminaBase.Value,
(int)numericUpDown_AccuracyBase.Value,
(int)numericUpDown_APTech.Value,
(int)numericUpDown_APTrait.Value,
(int)numericUpDown_APPrime.Value,
(int)numericUpDown_APMulti.Value,
(int)numericUpDown_APNPC.Value,
checkBox_APHaki.Checked,
checkBox_APDF.Checked
);
profile.saveCharTraits(dgv_Traits, traitList);
profile.saveCharTechs(techList, dgv_Techniques, listView_SubCat);
profile.saveCharSources(dgv_Sources, sourceList, radioButton_DateNA, false);
profile.saveCharTemplate(
label_TemplateType.Text,
richTextBox_Template.Text,
textBox_Color.Text,
textBox_MasteryMsg.Text
);
}
// Loads from serialized object and puts it into form
private void loadCharacterToForm() {
try {
profile.loadCharBasic(
ref textBox_CharacterName,
ref textBox_Nickname,
ref numericUpDown_Age,
ref comboBox_Gender,
ref textBox_Race,
ref textBox_Position,
ref comboBox_Affiliation,
ref textBox_Bounty,
ref numericUpDown_Comm,
ref comboBox_MarineRank,
ref textBox_Threat,
ref listBox_Achieve
);
}
catch (Exception ex) { MessageBox.Show("Load Basic Character Error.\nReason: " + ex.Message); }
try {
profile.loadCharAppearance(
ref textBox_Height,
ref textBox_Weight,
ref richTextBox_Hair,
ref richTextBox_Eye,
ref richTextBox_Clothing,
ref richTextBox_GeneralAppear,
ref listView_Images
);
}
catch (Exception ex) { MessageBox.Show("Load Physical Appearance Error.\nReason: " + ex.Message); }
try {
profile.loadCharBackground(
ref textBox_Island,
ref comboBox_Region,
ref richTextBox_Personality,
ref richTextBox_History
);
}
catch (Exception ex) { MessageBox.Show("Load Character Background Error.\nReason: " + ex.Message); }
try {
profile.loadCharCombat(
ref richTextBox_Combat,
ref listView_Weaponry,
ref listView_Items,
ref textBox_DFName,
ref comboBox_DFType,
ref comboBox_DFTier,
ref richTextBox_DFDesc
);
}
catch (Exception ex) { MessageBox.Show("Load Combat and Abilities Error.\nReason: " + ex.Message); }
try {
profile.loadCharRPElements(
ref numericUpDown_SDEarned,
ref numericUpDown_SDintoStats,
ref numericUpDown_UsedForFort,
ref numericUpDown_StrengthBase,
ref numericUpDown_SpeedBase,
ref numericUpDown_StaminaBase,
ref numericUpDown_AccuracyBase,
ref numericUpDown_APTech,
ref numericUpDown_APTrait,
ref numericUpDown_APPrime,
ref numericUpDown_APMulti,
ref numericUpDown_APNPC,
ref checkBox_APHaki,
ref checkBox_APDF,
ref textBox_Beli,
ref dgv_Professions,
ref profList
);
}
catch (Exception ex) { MessageBox.Show("Load Stats Error.\nReason: " + ex.Message); }
try {
profile.loadCharTraits(
ref traitList,
ref dgv_Traits,
ref spTraitList,
int.Parse(textBox_Fortune.Text)
);
}
catch (Exception ex) { MessageBox.Show("Load Traits Error.\nReason: " + ex.Message); }
try {
profile.loadCharTechs(
ref techList,
ref dgv_Techniques,
ref spTraitList,
ref dgv_SpTraits,
ref listView_SubCat
);
}
catch (Exception ex) { MessageBox.Show("Load Techniques Error.\nReason: " + ex.Message); }
try {
profile.loadCharSources(
ref sourceList,
ref dgv_Sources,
ref radioButton_DateNA,
false
);
}
catch (Exception ex) { MessageBox.Show("Load Techniques Error.\nReason: " + ex.Message); }
profile.loadCharTemplate(
ref label_TemplateType,
ref richTextBox_Template,
ref textBox_Color,
ref textBox_MasteryMsg
);
// Some update functions in which it isn't in an Exception Handle
Update_Traits_Count_Label();
Update_AP_Count();
Update_TotalSD();
Update_Strength_Final();
Update_Speed_Final();
Update_Stamina_Final();
Update_Accuracy_Final();
Update_Fortune();
Update_Total_RegTP();
Update_Used_RegTP();
Update_TechNum();
Update_Total_SpTP_Textbox();
Update_Used_SpTP_Textbox();
Update_CritAnatQuick_Msg();
}
// This is where serialize our profile.
private void saveCharactertoData() {
try {
profile.saveFile();
}
catch (SerializationException e) {
MessageBox.Show("Failed to save.\nReason: " + e.Message);
}
finally {
MessageBox.Show(profile.filename + " successfully saved!", "Saved",
MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void newCharacter() {
DialogResult result = new DialogResult();
result = DialogResult.No;
if (!saved) {
result = MessageBox.Show("Save your current work before making a New Character?", "Make New Project",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
saveCharacter();
}
}
// Make a new Character
if (result != DialogResult.Cancel) {
this.Text = "OPRP Character Builder";
profile.filename = null;
profile.path = null;
resetForm();
}
}
private void saveCharacter() {
// If there is no filename (this means New), we save one.
if (profile.filename == null) {
SaveFileDialog fileDialogSaveProject = new SaveFileDialog();
fileDialogSaveProject.Filter = "OPRP files (*.oprp)|*.oprp";
fileDialogSaveProject.Title = "Save New Project";
fileDialogSaveProject.OverwritePrompt = true;
if (fileDialogSaveProject.ShowDialog() == DialogResult.OK) {
profile.path = fileDialogSaveProject.FileName;
profile.filename = Path.GetFileNameWithoutExtension(fileDialogSaveProject.FileName);
saveFormToCharacter();
saveCharactertoData();
this.Text = profile.filename;
}
}
else {
saveFormToCharacter();
try {
saveCharactertoData();
isSavedStatus();
}
catch (Exception e) {
MessageBox.Show("Failed to save.\nReason: " + e.Message);
}
}
}
private void openCharacter() {
DialogResult result = new DialogResult();
result = DialogResult.No;
// Check if it's saved
if (!saved) {
result = MessageBox.Show("Save your current work before opening a Character?", "Open Project",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
saveCharacter();
}
}
// Open the Character
if (result != DialogResult.Cancel) {
OpenFileDialog dlgFileOpen = new OpenFileDialog();
dlgFileOpen.Filter = "OPRP files (*.oprp)|*.oprp";
dlgFileOpen.Title = "Open Project";
dlgFileOpen.RestoreDirectory = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK) {
try {
profile.path = dlgFileOpen.FileName;
profile.filename = Path.GetFileNameWithoutExtension(dlgFileOpen.FileName);
profile.openFile();
resetForm();
loadCharacterToForm();
this.Text = profile.filename;
isSavedStatus();
}
catch (Exception e) {
MessageBox.Show("Failed to deserialize.\nReason: " + e.Message,
"Failed to Open", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
}
private void Load_CustomTags_Dict() {
// This will add every single entry into the Dictionary
CustomTags.Add(1, textBox_CharacterName.Text);
CustomTags.Add(2, textBox_Nickname.Text);
CustomTags.Add(3, numericUpDown_Age.Value.ToString());
CustomTags.Add(4, comboBox_Gender.Text);
CustomTags.Add(5, textBox_Race.Text);
CustomTags.Add(6, comboBox_Affiliation.Text);
CustomTags.Add(7, textBox_Bounty.Text);
CustomTags.Add(8, comboBox_MarineRank.Text);
CustomTags.Add(9, numericUpDown_Comm.Text);
CustomTags.Add(10, textBox_Threat.Text);
CustomTags.Add(11, textBox_Position.Text);
// 12 is Achievements
// 13 is Profession Name
CustomTags.Add(14, textBox_Height.Text);
CustomTags.Add(15, textBox_Weight.Text);
CustomTags.Add(16, richTextBox_Hair.Text);
CustomTags.Add(17, richTextBox_Eye.Text);
CustomTags.Add(18, richTextBox_Clothing.Text);
CustomTags.Add(19, richTextBox_GeneralAppear.Text);
CustomTags.Add(20, richTextBox_Personality.Text);
CustomTags.Add(21, textBox_Island.Text);
CustomTags.Add(22, comboBox_Region.Text);
CustomTags.Add(23, richTextBox_History.Text);
CustomTags.Add(24, richTextBox_Combat.Text);
// 25 is Weapon Name
// 26 is Item Name
CustomTags.Add(27, textBox_Beli.Text);
CustomTags.Add(28, textBox_AP.Text);
// 29 is AP Name
CustomTags.Add(30, numericUpDown_SDEarned.Value.ToString());
CustomTags.Add(31, textBox_SDRemain.Text);
CustomTags.Add(32, textBox_StatPoints.Text);
CustomTags.Add(33, textBox_SDtoSPCalc.Text);
CustomTags.Add(34, textBox_UsedForStats.Text);
CustomTags.Add(35, numericUpDown_UsedForFort.Value.ToString());
CustomTags.Add(36, numericUpDown_StrengthBase.Value.ToString());
CustomTags.Add(37, textBox_StrengthFinal.Text);
CustomTags.Add(38, label_StrengthCalc.Text);
CustomTags.Add(39, numericUpDown_SpeedBase.Value.ToString());
CustomTags.Add(40, textBox_SpeedFinal.Text);
CustomTags.Add(41, label_SpeedCalc.Text);
CustomTags.Add(42, numericUpDown_StaminaBase.Value.ToString());
CustomTags.Add(43, textBox_StaminaFinal.Text);
CustomTags.Add(44, label_StaminaCalc.Text);
CustomTags.Add(45, numericUpDown_AccuracyBase.Value.ToString());
CustomTags.Add(46, textBox_AccuracyFinal.Text);
CustomTags.Add(47, label_AccuracyCalc.Text);
CustomTags.Add(48, textBox_Fortune.Text);
CustomTags.Add(49, label_FortuneCalc.Text);
// 50 is Trait Name (Gen)
// 51 is Trait Name (Prof)
CustomTags.Add(52, textBox_DFName.Text);
CustomTags.Add(53, comboBox_DFType.Text);
CustomTags.Add(54, richTextBox_DFDesc.Text);
// 55 is Devil Fruit Free Effect [LEGACY]
CustomTags.Add(56, textBox_RegTPUsed.Text);
CustomTags.Add(57, textBox_RegTPTotal.Text);
CustomTags.Add(58, label_RegTPCalc.Text);
CustomTags.Add(59, textBox_SpTPUsed.Text);
CustomTags.Add(60, textBox_SpTPTotal.Text);
// 61 is Sp TP Trait Name
CustomTags.Add(62, label_CritAnatQuick.Text);
// 63 is Sp Tech Category Name
// 64 is Tech Name
// 65 is Tech Rank
// 66 is Tech Tupe
// 67 is Tech Power
// 68 is Tech Stats
// 69 is Tech Reg TP Spent
// 70 is Tech Sp TP Spent
// 71 is Tech Note
// 72 is Tech Description
// 73 is Tech Effects
CustomTags.Add(74, textBox_TotalSD.Text);
CustomTags.Add(75, comboBox_DFTier.Text);
// 76 is Weapon Description
// 77 is Item Description
// 78 is AP Number
// 79 is # Traits Spent (Gen)
// 80 is Trait Desc (Gen)
// 81 is # Traits Spent (Prof)
// 82 is Trait Desc (Prof)
// 83 is Sp Trait TP Used
// 84 is Sp Trait TP Total
// 85 is Profession Primary/Secondary
// 86 is Profession Description
// 87 is Profession Primary Bonus
CustomTags.Add(88, textBox_MasteryMsg.Text);
CustomTags.Add(89, textBox_Focus.Text);
// 90 is Tech AE
// 91 is Image URL
// 92 is Image Label
// 93 is Image Width
// 94 is Image Height
CustomTags.Add(95, genCap.ToString());
CustomTags.Add(96, profCap.ToString());
// 97 is Tech Range
CustomTags.Add(98, numericUpDown_SDintoStats.Value.ToString());
// 99 is AP Description
// 100 is Tech Custom Note
// 101 is DevH Date
// 102 is DevH Title
// 103 is DevH URL
// 104 is DevH SD
// 105 is DevH Beli
// 106 is DevH Note
}
private void button_Generate_Click(object sender, EventArgs e) {
Sheet sheet = new Sheet(1, richTextBox_Template.Text, techList);
Load_CustomTags_Dict();
Sheet.color_hex = textBox_Color.Text;
List<int> AP_Numbers = new List<int>();
AP_Numbers.Add((int)numericUpDown_APTech.Value);
AP_Numbers.Add((int)numericUpDown_APTrait.Value * 2);
AP_Numbers.Add((int)numericUpDown_APPrime.Value);
AP_Numbers.Add((int)numericUpDown_APMulti.Value);
AP_Numbers.Add((int)numericUpDown_APNPC.Value);
AP_Numbers.Add((checkBox_APHaki.Checked) ? 2 : 0);
AP_Numbers.Add((checkBox_APDF.Checked) ? 1 : 0);
sheet.Generate_Template(listBox_Achieve,
profList,
listView_Images,
listView_Weaponry,
listView_Items,
AP_Numbers,
traitList,
spTraitList,
dgv_Techniques,
listView_SubCat,
dgv_Sources);
sheet.ShowDialog();
CustomTags.Clear(); // Clear Dictionary now that we're done.
}
private void button_ResetChar_Click(object sender, EventArgs e) {
DialogResult result = new DialogResult();
result = DialogResult.No;
result = MessageBox.Show("Are you sure you want to reset this character?", "Reset Character",
MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
if (result == DialogResult.Yes) {
resetForm();
}
}
private void toolStripButton_New_Click(object sender, EventArgs e) {
newCharacter();
}
private void toolStripButton_Open_Click(object sender, EventArgs e) {
openCharacter();
}
private void toolStripButton_Save_Click(object sender, EventArgs e) {
saveCharacter();
}
private void toolStripButton_SaveAs_Click(object sender, EventArgs e) {
SaveFileDialog fileDialogSaveProject = new SaveFileDialog();
fileDialogSaveProject.Filter = "OPRP files (*.oprp)|*.oprp";
fileDialogSaveProject.Title = "Save New Project";
fileDialogSaveProject.OverwritePrompt = true;
if (fileDialogSaveProject.ShowDialog() == DialogResult.OK) {
profile.path = fileDialogSaveProject.FileName;
profile.filename = Path.GetFileNameWithoutExtension(fileDialogSaveProject.FileName);
saveFormToCharacter();
saveCharactertoData();
this.Text = profile.filename;
isSavedStatus();
}
}
// Returns True if Template imported successfully, False otherwise
private bool Import_Template() {
OpenFileDialog dlgFileOpen = new OpenFileDialog();
dlgFileOpen.Filter = "Text files (*.txt)|*.txt";
dlgFileOpen.Title = "Import Template";
dlgFileOpen.RestoreDirectory = true;
if (dlgFileOpen.ShowDialog() == DialogResult.OK) {
try {
StreamReader sr = new StreamReader(dlgFileOpen.FileName);
label_TemplateType.Text = Path.GetFileNameWithoutExtension(dlgFileOpen.FileName);
label_TemplateType.ForeColor = Color.Blue;
richTextBox_Template.Text = sr.ReadToEnd();
template_imported = true;
MessageBox.Show("Template \"" + label_TemplateType.Text + "\" imported successfully.", "Imported", MessageBoxButtons.OK, MessageBoxIcon.Information);
notSavedStatus();
return true;
}
catch {
MessageBox.Show("Error in importing Template.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
}
else {
return false;
}
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e) {
// Check to save before closing the program
if (!saved) {
DialogResult result = new DialogResult();
result = DialogResult.No;
result = MessageBox.Show("Save changes before closing the tool?", "Save Changes",
MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
if (result == DialogResult.Yes) {
saveCharacter();
}
else if (result == DialogResult.Cancel) {
e.Cancel = true;
}
}
}
#endregion
}
// Class to sort ListView by number
public class ListViewItemNumberSort : IComparer
{
private int col;
public ListViewItemNumberSort(int column) { col = column; }
public int Compare(object x, object y) {
int nx = int.Parse((x as ListViewItem).SubItems[col].Text);
int ny = int.Parse((y as ListViewItem).SubItems[col].Text);
return nx.CompareTo(ny);
}
}
// Class to sort ListView by Text based on selected Column
public class ListViewItemSorter : IComparer
{
private int col;
public ListViewItemSorter(int column) { col = column; }
public int Compare(object x, object y) {
return string.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
}
}
}
|
mrdoowan/OPRPCharBuild
|
OPRPCharBuild/OPRPCharBuild/MainForm.cs
|
C#
|
gpl-3.0
| 116,837
|
from cloudbot import hook
from cloudbot.util import http
api_root = 'http://api.rottentomatoes.com/api/public/v1.0/'
movie_search_url = api_root + 'movies.json'
movie_reviews_url = api_root + 'movies/%s/reviews.json'
@hook.command('rt')
def rottentomatoes(inp, bot=None):
"""rt <title> -- gets ratings for <title> from Rotten Tomatoes"""
api_key = bot.config.get("api_keys", {}).get("rottentomatoes", None)
if not api_key:
return "error: no api key set"
title = inp.strip()
results = http.get_json(movie_search_url, q=title, apikey=api_key)
if results['total'] == 0:
return 'No results.'
movie = results['movies'][0]
title = movie['title']
movie_id = movie['id']
critics_score = movie['ratings']['critics_score']
audience_score = movie['ratings']['audience_score']
url = movie['links']['alternate']
if critics_score == -1:
return
reviews = http.get_json(movie_reviews_url % movie_id, apikey=api_key, review_type='all')
review_count = reviews['total']
fresh = critics_score * review_count / 100
rotten = review_count - fresh
return "{} - Critics Rating: \x02{}%\x02 ({} liked, {} disliked) " \
"Audience Rating: \x02{}%\x02 - {}".format(title, critics_score, fresh, rotten, audience_score, url)
|
Zarthus/CloudBotRefresh
|
plugins/rottentomatoes.py
|
Python
|
gpl-3.0
| 1,312
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Porthos: tst Directory Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">Porthos
 <span id="projectnumber">0.0.0-cmake</span>
</div>
<div id="projectbrief">An-embedded-linux-robot</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.12 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',true,false,'search.php','Search');
$(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_97aefd0d527b934f1d99a682da8fe6a9.html">lib</a></li><li class="navelem"><a class="el" href="dir_0ef8b19a9897c2a66786d943626a6c71.html">tst</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="headertitle">
<div class="title">tst Directory Reference</div> </div>
</div><!--header-->
<div class="contents">
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Wed Nov 30 2016 22:51:05 for Porthos by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.12
</small></address>
</body>
</html>
|
spoorcc/porthos
|
doc/html/dir_0ef8b19a9897c2a66786d943626a6c71.html
|
HTML
|
gpl-3.0
| 2,996
|
/*
ChibiOS - Copyright (C) 2006..2016 Giovanni Di Sirio
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.
*/
/**
* @file SDMMCv1/hal_sdc_lld.c
* @brief STM32 SDC subsystem low level driver source.
*
* @addtogroup SDC
* @{
*/
#include <string.h>
#include "hal.h"
#if HAL_USE_SDC || defined(__DOXYGEN__)
#if !defined(STM32_SDMMCCLK)
#error "STM32_SDMMCCLK not defined"
#endif
#if STM32_SDMMCCLK > 48000000
#error "STM32_SDMMCCLK exceeding 48MHz"
#endif
/*===========================================================================*/
/* Driver local definitions. */
/*===========================================================================*/
#define SDMMC_ICR_ALL_FLAGS \
(SDMMC_ICR_CCRCFAILC | SDMMC_ICR_DCRCFAILC | \
SDMMC_ICR_CTIMEOUTC | SDMMC_ICR_DTIMEOUTC | \
SDMMC_ICR_TXUNDERRC | SDMMC_ICR_RXOVERRC | \
SDMMC_ICR_CMDRENDC | SDMMC_ICR_CMDSENTC | \
SDMMC_ICR_DATAENDC | SDMMC_ICR_DBCKENDC | \
SDMMC_ICR_SDIOITC)
#define SDMMC_STA_ERROR_MASK \
(SDMMC_STA_CCRCFAIL | SDMMC_STA_DCRCFAIL | \
SDMMC_STA_CTIMEOUT | SDMMC_STA_DTIMEOUT | \
SDMMC_STA_TXUNDERR | SDMMC_STA_RXOVERR)
#define SDMMC_CLKDIV_HS (2 - 2)
#define SDMMC_CLKDIV_LS (120 - 2)
#define SDMMC_WRITE_TIMEOUT \
(((STM32_SDMMCCLK / (SDMMC_CLKDIV_HS + 2)) / 1000) * \
STM32_SDC_SDMMC_WRITE_TIMEOUT)
#define SDMMC_READ_TIMEOUT \
(((STM32_SDMMCCLK / (SDMMC_CLKDIV_HS + 2)) / 1000) * \
STM32_SDC_SDMMC_READ_TIMEOUT)
#define SDMMC1_DMA_CHANNEL \
STM32_DMA_GETCHANNEL(STM32_SDC_SDMMC1_DMA_STREAM, \
STM32_SDC_SDMMC1_DMA_CHN)
#define SDMMC2_DMA_CHANNEL \
STM32_DMA_GETCHANNEL(STM32_SDC_SDMMC2_DMA_STREAM, \
STM32_SDC_SDMMC2_DMA_CHN)
/*===========================================================================*/
/* Driver exported variables. */
/*===========================================================================*/
/** @brief SDCD1 driver identifier.*/
#if STM32_SDC_USE_SDMMC1 || defined(__DOXYGEN__)
SDCDriver SDCD1;
#endif
/** @brief SDCD2 driver identifier.*/
#if STM32_SDC_USE_SDMMC2 || defined(__DOXYGEN__)
SDCDriver SDCD2;
#endif
/*===========================================================================*/
/* Driver local variables and types. */
/*===========================================================================*/
#if STM32_SDC_SDMMC_UNALIGNED_SUPPORT
/**
* @brief Buffer for temporary storage during unaligned transfers.
*/
static union {
uint32_t alignment;
uint8_t buf[MMCSD_BLOCK_SIZE];
} u;
#endif /* STM32_SDC_SDMMC_UNALIGNED_SUPPORT */
/**
* @brief SDIO default configuration.
*/
static const SDCConfig sdc_default_cfg = {
NULL,
SDC_MODE_4BIT
};
/*===========================================================================*/
/* Driver local functions. */
/*===========================================================================*/
/**
* @brief Prepares to handle read transaction.
* @details Designed for read special registers from card.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[out] buf pointer to the read buffer
* @param[in] bytes number of bytes to read
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
static bool sdc_lld_prepare_read_bytes(SDCDriver *sdcp,
uint8_t *buf, uint32_t bytes) {
osalDbgCheck(bytes < 0x1000000);
sdcp->sdmmc->DTIMER = SDMMC_READ_TIMEOUT;
/* Checks for errors and waits for the card to be ready for reading.*/
if (_sdc_wait_for_transfer_state(sdcp))
return HAL_FAILED;
/* Prepares the DMA channel for writing.*/
dmaStreamSetMemory0(sdcp->dma, buf);
dmaStreamSetTransactionSize(sdcp->dma, bytes / sizeof (uint32_t));
dmaStreamSetMode(sdcp->dma, sdcp->dmamode | STM32_DMA_CR_DIR_P2M);
dmaStreamEnable(sdcp->dma);
/* Setting up data transfer.*/
sdcp->sdmmc->ICR = SDMMC_ICR_ALL_FLAGS;
sdcp->sdmmc->MASK = SDMMC_MASK_DCRCFAILIE |
SDMMC_MASK_DTIMEOUTIE |
SDMMC_MASK_RXOVERRIE |
SDMMC_MASK_DATAENDIE;
sdcp->sdmmc->DLEN = bytes;
/* Transaction starts just after DTEN bit setting.*/
sdcp->sdmmc->DCTRL = SDMMC_DCTRL_DTDIR |
SDMMC_DCTRL_DTMODE | /* multibyte data transfer */
SDMMC_DCTRL_DMAEN |
SDMMC_DCTRL_DTEN;
return HAL_SUCCESS;
}
/**
* @brief Prepares card to handle read transaction.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] startblk first block to read
* @param[in] n number of blocks to read
* @param[in] resp pointer to the response buffer
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
static bool sdc_lld_prepare_read(SDCDriver *sdcp, uint32_t startblk,
uint32_t n, uint32_t *resp) {
/* Driver handles data in 512 bytes blocks (just like HC cards). But if we
have not HC card than we must convert address from blocks to bytes.*/
if (!(sdcp->cardmode & SDC_MODE_HIGH_CAPACITY))
startblk *= MMCSD_BLOCK_SIZE;
if (n > 1) {
/* Send read multiple blocks command to card.*/
if (sdc_lld_send_cmd_short_crc(sdcp, MMCSD_CMD_READ_MULTIPLE_BLOCK,
startblk, resp) || MMCSD_R1_ERROR(resp[0]))
return HAL_FAILED;
}
else{
/* Send read single block command.*/
if (sdc_lld_send_cmd_short_crc(sdcp, MMCSD_CMD_READ_SINGLE_BLOCK,
startblk, resp) || MMCSD_R1_ERROR(resp[0]))
return HAL_FAILED;
}
return HAL_SUCCESS;
}
/**
* @brief Prepares card to handle write transaction.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] startblk first block to read
* @param[in] n number of blocks to write
* @param[in] resp pointer to the response buffer
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
static bool sdc_lld_prepare_write(SDCDriver *sdcp, uint32_t startblk,
uint32_t n, uint32_t *resp) {
/* Driver handles data in 512 bytes blocks (just like HC cards). But if we
have not HC card than we must convert address from blocks to bytes.*/
if (!(sdcp->cardmode & SDC_MODE_HIGH_CAPACITY))
startblk *= MMCSD_BLOCK_SIZE;
if (n > 1) {
/* Write multiple blocks command.*/
if (sdc_lld_send_cmd_short_crc(sdcp, MMCSD_CMD_WRITE_MULTIPLE_BLOCK,
startblk, resp) || MMCSD_R1_ERROR(resp[0]))
return HAL_FAILED;
}
else{
/* Write single block command.*/
if (sdc_lld_send_cmd_short_crc(sdcp, MMCSD_CMD_WRITE_BLOCK,
startblk, resp) || MMCSD_R1_ERROR(resp[0]))
return HAL_FAILED;
}
return HAL_SUCCESS;
}
/**
* @brief Wait end of data transaction and performs finalizations.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] n number of blocks in transaction
* @param[in] resp pointer to the response buffer
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*/
static bool sdc_lld_wait_transaction_end(SDCDriver *sdcp, uint32_t n,
uint32_t *resp) {
/* Note the mask is checked before going to sleep because the interrupt
may have occurred before reaching the critical zone.*/
osalSysLock();
if (sdcp->sdmmc->MASK != 0)
osalThreadSuspendS(&sdcp->thread);
if ((sdcp->sdmmc->STA & SDMMC_STA_DATAEND) == 0) {
osalSysUnlock();
return HAL_FAILED;
}
/* Waits for transfer completion at DMA level, then the stream is
disabled and cleared.*/
dmaWaitCompletion(sdcp->dma);
sdcp->sdmmc->ICR = SDMMC_ICR_ALL_FLAGS;
sdcp->sdmmc->DCTRL = 0;
osalSysUnlock();
/* Finalize transaction.*/
if (n > 1)
return sdc_lld_send_cmd_short_crc(sdcp, MMCSD_CMD_STOP_TRANSMISSION, 0, resp);
return HAL_SUCCESS;
}
/**
* @brief Gets SDC errors.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] sta value of the STA register
*
* @notapi
*/
static void sdc_lld_collect_errors(SDCDriver *sdcp, uint32_t sta) {
uint32_t errors = SDC_NO_ERROR;
if (sta & SDMMC_STA_CCRCFAIL)
errors |= SDC_CMD_CRC_ERROR;
if (sta & SDMMC_STA_DCRCFAIL)
errors |= SDC_DATA_CRC_ERROR;
if (sta & SDMMC_STA_CTIMEOUT)
errors |= SDC_COMMAND_TIMEOUT;
if (sta & SDMMC_STA_DTIMEOUT)
errors |= SDC_DATA_TIMEOUT;
if (sta & SDMMC_STA_TXUNDERR)
errors |= SDC_TX_UNDERRUN;
if (sta & SDMMC_STA_RXOVERR)
errors |= SDC_RX_OVERRUN;
/* if (sta & SDMMC_STA_STBITERR)
errors |= SDC_STARTBIT_ERROR;*/
sdcp->errors |= errors;
}
/**
* @brief Performs clean transaction stopping in case of errors.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] n number of blocks in transaction
* @param[in] resp pointer to the response buffer
*
* @notapi
*/
static void sdc_lld_error_cleanup(SDCDriver *sdcp,
uint32_t n,
uint32_t *resp) {
uint32_t sta = sdcp->sdmmc->STA;
dmaStreamDisable(sdcp->dma);
sdcp->sdmmc->ICR = SDMMC_ICR_ALL_FLAGS;
sdcp->sdmmc->MASK = 0;
sdcp->sdmmc->DCTRL = 0;
sdc_lld_collect_errors(sdcp, sta);
if (n > 1)
sdc_lld_send_cmd_short_crc(sdcp, MMCSD_CMD_STOP_TRANSMISSION, 0, resp);
}
/*===========================================================================*/
/* Driver interrupt handlers. */
/*===========================================================================*/
/**
* @brief SDMMC1 IRQ handler.
* @details It just wakes transaction thread, errors handling is performed in
* there.
*
* @isr
*/
#if STM32_SDC_USE_SDMMC1 || defined(__DOXYGEN__)
OSAL_IRQ_HANDLER(STM32_SDMMC1_HANDLER) {
OSAL_IRQ_PROLOGUE();
osalSysLockFromISR();
/* Disables the source but the status flags are not reset because the
read/write functions needs to check them.*/
SDMMC1->MASK = 0;
osalThreadResumeI(&SDCD1.thread, MSG_OK);
osalSysUnlockFromISR();
OSAL_IRQ_EPILOGUE();
}
#endif
/**
* @brief SDMMC2 IRQ handler.
* @details It just wakes transaction thread, errors handling is performed in
* there.
*
* @isr
*/
#if STM32_SDC_USE_SDMMC2 || defined(__DOXYGEN__)
OSAL_IRQ_HANDLER(STM32_SDMMC2_HANDLER) {
OSAL_IRQ_PROLOGUE();
osalSysLockFromISR();
/* Disables the source but the status flags are not reset because the
read/write functions needs to check them.*/
SDMMC2->MASK = 0;
osalThreadResumeI(&SDCD2.thread, MSG_OK);
osalSysUnlockFromISR();
OSAL_IRQ_EPILOGUE();
}
#endif
/*===========================================================================*/
/* Driver exported functions. */
/*===========================================================================*/
/**
* @brief Low level SDC driver initialization.
*
* @notapi
*/
void sdc_lld_init(void) {
#if STM32_SDC_USE_SDMMC1
sdcObjectInit(&SDCD1);
SDCD1.thread = NULL;
SDCD1.dma = STM32_DMA_STREAM(STM32_SDC_SDMMC1_DMA_STREAM);
SDCD1.sdmmc = SDMMC1;
nvicEnableVector(STM32_SDMMC1_NUMBER, STM32_SDC_SDMMC1_IRQ_PRIORITY);
#endif
#if STM32_SDC_USE_SDMMC2
sdcObjectInit(&SDCD2);
SDCD2.thread = NULL;
SDCD2.dma = STM32_DMA_STREAM(STM32_SDC_SDMMC2_DMA_STREAM);
SDCD2.sdmmc = SDMMC2;
nvicEnableVector(STM32_SDMMC2_NUMBER, STM32_SDC_SDMMC2_IRQ_PRIORITY);
#endif
}
/**
* @brief Configures and activates the SDC peripheral.
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @notapi
*/
void sdc_lld_start(SDCDriver *sdcp) {
/* Checking configuration, using a default if NULL has been passed.*/
if (sdcp->config == NULL) {
sdcp->config = &sdc_default_cfg;
}
sdcp->dmamode = STM32_DMA_CR_CHSEL(SDMMC1_DMA_CHANNEL) |
STM32_DMA_CR_PL(STM32_SDC_SDMMC1_DMA_PRIORITY) |
STM32_DMA_CR_PSIZE_WORD |
STM32_DMA_CR_MSIZE_WORD |
STM32_DMA_CR_MINC;
#if STM32_DMA_ADVANCED
sdcp->dmamode |= STM32_DMA_CR_PFCTRL |
STM32_DMA_CR_PBURST_INCR4 |
STM32_DMA_CR_MBURST_INCR4;
#endif
/* If in stopped state then clocks are enabled and DMA initialized.*/
if (sdcp->state == BLK_STOP) {
#if STM32_SDC_USE_SDMMC1
if (&SDCD1 == sdcp) {
bool b = dmaStreamAllocate(sdcp->dma, STM32_SDC_SDMMC1_IRQ_PRIORITY,
NULL, NULL);
osalDbgAssert(!b, "stream already allocated");
dmaStreamSetPeripheral(sdcp->dma, &sdcp->sdmmc->FIFO);
#if STM32_DMA_ADVANCED
dmaStreamSetFIFO(sdcp->dma, STM32_DMA_FCR_DMDIS |
STM32_DMA_FCR_FTH_FULL);
#endif
rccEnableSDMMC1(FALSE);
}
#endif /* STM32_SDC_USE_SDMMC1 */
#if STM32_SDC_USE_SDMMC2
if (&SDCD2 == sdcp) {
bool b = dmaStreamAllocate(sdcp->dma, STM32_SDC_SDMMC2_IRQ_PRIORITY,
NULL, NULL);
osalDbgAssert(!b, "stream already allocated");
dmaStreamSetPeripheral(sdcp->dma, &sdcp->sdmmc->FIFO);
#if STM32_DMA_ADVANCED
dmaStreamSetFIFO(sdcp->dma, STM32_DMA_FCR_DMDIS |
STM32_DMA_FCR_FTH_FULL);
#endif
rccEnableSDMMC2(FALSE);
}
#endif /* STM32_SDC_USE_SDMMC2 */
}
/* Configuration, card clock is initially stopped.*/
sdcp->sdmmc->POWER = 0;
sdcp->sdmmc->CLKCR = 0;
sdcp->sdmmc->DCTRL = 0;
sdcp->sdmmc->DTIMER = 0;
}
/**
* @brief Deactivates the SDC peripheral.
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @notapi
*/
void sdc_lld_stop(SDCDriver *sdcp) {
if (sdcp->state != BLK_STOP) {
/* SDIO deactivation.*/
sdcp->sdmmc->POWER = 0;
sdcp->sdmmc->CLKCR = 0;
sdcp->sdmmc->DCTRL = 0;
sdcp->sdmmc->DTIMER = 0;
/* DMA stream released.*/
dmaStreamRelease(sdcp->dma);
/* Clock deactivation.*/
#if STM32_SDC_USE_SDMMC1
if (&SDCD1 == sdcp) {
rccDisableSDMMC1(FALSE);
}
#endif
#if STM32_SDC_USE_SDMMC2
if (&SDCD2 == sdcp) {
rccDisableSDMMC2(FALSE);
}
#endif
}
}
/**
* @brief Starts the SDIO clock and sets it to init mode (400kHz or less).
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @notapi
*/
void sdc_lld_start_clk(SDCDriver *sdcp) {
/* Initial clock setting: 400kHz, 1bit mode.*/
sdcp->sdmmc->CLKCR = SDMMC_CLKDIV_LS;
sdcp->sdmmc->POWER |= SDMMC_POWER_PWRCTRL_0 | SDMMC_POWER_PWRCTRL_1;
sdcp->sdmmc->CLKCR |= SDMMC_CLKCR_CLKEN;
/* Clock activation delay.*/
osalThreadSleep(OSAL_MS2ST(STM32_SDC_SDMMC_CLOCK_DELAY));
}
/**
* @brief Sets the SDIO clock to data mode (25MHz or less).
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] clk the clock mode
*
* @notapi
*/
void sdc_lld_set_data_clk(SDCDriver *sdcp, sdcbusclk_t clk) {
#if 0
if (SDC_CLK_50MHz == clk) {
sdcp->sdmmc->CLKCR = (sdcp->sdmmc->CLKCR & 0xFFFFFF00U) |
SDMMC_CLKDIV_HS | SDMMC_CLKCR_BYPASS;
}
else
sdcp->sdmmc->CLKCR = (sdcp->sdmmc->CLKCR & 0xFFFFFF00U) | SDMMC_CLKDIV_HS;
#else
(void)clk;
sdcp->sdmmc->CLKCR = (sdcp->sdmmc->CLKCR & 0xFFFFFF00U) | SDMMC_CLKDIV_HS;
#endif
}
/**
* @brief Stops the SDIO clock.
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @notapi
*/
void sdc_lld_stop_clk(SDCDriver *sdcp) {
sdcp->sdmmc->CLKCR = 0;
sdcp->sdmmc->POWER = 0;
}
/**
* @brief Switches the bus to 4 bits mode.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] mode bus mode
*
* @notapi
*/
void sdc_lld_set_bus_mode(SDCDriver *sdcp, sdcbusmode_t mode) {
uint32_t clk = sdcp->sdmmc->CLKCR & ~SDMMC_CLKCR_WIDBUS;
switch (mode) {
case SDC_MODE_1BIT:
sdcp->sdmmc->CLKCR = clk;
break;
case SDC_MODE_4BIT:
sdcp->sdmmc->CLKCR = clk | SDMMC_CLKCR_WIDBUS_0;
break;
case SDC_MODE_8BIT:
sdcp->sdmmc->CLKCR = clk | SDMMC_CLKCR_WIDBUS_1;
break;
}
}
/**
* @brief Sends an SDIO command with no response expected.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] cmd card command
* @param[in] arg command argument
*
* @notapi
*/
void sdc_lld_send_cmd_none(SDCDriver *sdcp, uint8_t cmd, uint32_t arg) {
sdcp->sdmmc->ARG = arg;
sdcp->sdmmc->CMD = (uint32_t)cmd | SDMMC_CMD_CPSMEN;
while ((sdcp->sdmmc->STA & SDMMC_STA_CMDSENT) == 0)
;
sdcp->sdmmc->ICR = SDMMC_ICR_CMDSENTC;
}
/**
* @brief Sends an SDIO command with a short response expected.
* @note The CRC is not verified.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] cmd card command
* @param[in] arg command argument
* @param[out] resp pointer to the response buffer (one word)
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_send_cmd_short(SDCDriver *sdcp, uint8_t cmd, uint32_t arg,
uint32_t *resp) {
uint32_t sta;
sdcp->sdmmc->ARG = arg;
sdcp->sdmmc->CMD = (uint32_t)cmd | SDMMC_CMD_WAITRESP_0 | SDMMC_CMD_CPSMEN;
while (((sta = sdcp->sdmmc->STA) & (SDMMC_STA_CMDREND | SDMMC_STA_CTIMEOUT |
SDMMC_STA_CCRCFAIL)) == 0)
;
sdcp->sdmmc->ICR = sta & (SDMMC_STA_CMDREND | SDMMC_STA_CTIMEOUT |
SDMMC_STA_CCRCFAIL);
if ((sta & (SDMMC_STA_CTIMEOUT)) != 0) {
sdc_lld_collect_errors(sdcp, sta);
return HAL_FAILED;
}
*resp = sdcp->sdmmc->RESP1;
return HAL_SUCCESS;
}
/**
* @brief Sends an SDIO command with a short response expected and CRC.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] cmd card command
* @param[in] arg command argument
* @param[out] resp pointer to the response buffer (one word)
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_send_cmd_short_crc(SDCDriver *sdcp, uint8_t cmd, uint32_t arg,
uint32_t *resp) {
uint32_t sta;
sdcp->sdmmc->ARG = arg;
sdcp->sdmmc->CMD = (uint32_t)cmd | SDMMC_CMD_WAITRESP_0 | SDMMC_CMD_CPSMEN;
while (((sta = sdcp->sdmmc->STA) & (SDMMC_STA_CMDREND | SDMMC_STA_CTIMEOUT |
SDMMC_STA_CCRCFAIL)) == 0)
;
sdcp->sdmmc->ICR = sta & (SDMMC_STA_CMDREND | SDMMC_STA_CTIMEOUT | SDMMC_STA_CCRCFAIL);
if ((sta & (SDMMC_STA_CTIMEOUT | SDMMC_STA_CCRCFAIL)) != 0) {
sdc_lld_collect_errors(sdcp, sta);
return HAL_FAILED;
}
*resp = sdcp->sdmmc->RESP1;
return HAL_SUCCESS;
}
/**
* @brief Sends an SDIO command with a long response expected and CRC.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] cmd card command
* @param[in] arg command argument
* @param[out] resp pointer to the response buffer (four words)
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_send_cmd_long_crc(SDCDriver *sdcp, uint8_t cmd, uint32_t arg,
uint32_t *resp) {
uint32_t sta;
(void)sdcp;
sdcp->sdmmc->ARG = arg;
sdcp->sdmmc->CMD = (uint32_t)cmd | SDMMC_CMD_WAITRESP_0 | SDMMC_CMD_WAITRESP_1 |
SDMMC_CMD_CPSMEN;
while (((sta = sdcp->sdmmc->STA) & (SDMMC_STA_CMDREND | SDMMC_STA_CTIMEOUT |
SDMMC_STA_CCRCFAIL)) == 0)
;
sdcp->sdmmc->ICR = sta & (SDMMC_STA_CMDREND | SDMMC_STA_CTIMEOUT |
SDMMC_STA_CCRCFAIL);
if ((sta & (SDMMC_STA_ERROR_MASK)) != 0) {
sdc_lld_collect_errors(sdcp, sta);
return HAL_FAILED;
}
/* Save bytes in reverse order because MSB in response comes first.*/
*resp++ = sdcp->sdmmc->RESP4;
*resp++ = sdcp->sdmmc->RESP3;
*resp++ = sdcp->sdmmc->RESP2;
*resp = sdcp->sdmmc->RESP1;
return HAL_SUCCESS;
}
/**
* @brief Reads special registers using data bus.
* @details Needs only during card detection procedure.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[out] buf pointer to the read buffer
* @param[in] bytes number of bytes to read
* @param[in] cmd card command
* @param[in] arg argument for command
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_read_special(SDCDriver *sdcp, uint8_t *buf, size_t bytes,
uint8_t cmd, uint32_t arg) {
uint32_t resp[1];
if(sdc_lld_prepare_read_bytes(sdcp, buf, bytes))
goto error;
if (sdc_lld_send_cmd_short_crc(sdcp, cmd, arg, resp)
|| MMCSD_R1_ERROR(resp[0]))
goto error;
if (sdc_lld_wait_transaction_end(sdcp, 1, resp))
goto error;
return HAL_SUCCESS;
error:
sdc_lld_error_cleanup(sdcp, 1, resp);
return HAL_FAILED;
}
/**
* @brief Reads one or more blocks.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] startblk first block to read
* @param[out] buf pointer to the read buffer
* @param[in] blocks number of blocks to read
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_read_aligned(SDCDriver *sdcp, uint32_t startblk,
uint8_t *buf, uint32_t blocks) {
uint32_t resp[1];
osalDbgCheck(blocks < 0x1000000 / MMCSD_BLOCK_SIZE);
sdcp->sdmmc->DTIMER = SDMMC_READ_TIMEOUT;
/* Checks for errors and waits for the card to be ready for reading.*/
if (_sdc_wait_for_transfer_state(sdcp))
return HAL_FAILED;
/* Prepares the DMA channel for writing.*/
dmaStreamSetMemory0(sdcp->dma, buf);
dmaStreamSetTransactionSize(sdcp->dma,
(blocks * MMCSD_BLOCK_SIZE) / sizeof (uint32_t));
dmaStreamSetMode(sdcp->dma, sdcp->dmamode | STM32_DMA_CR_DIR_P2M);
dmaStreamEnable(sdcp->dma);
/* Setting up data transfer.*/
sdcp->sdmmc->ICR = SDMMC_ICR_ALL_FLAGS;
sdcp->sdmmc->MASK = SDMMC_MASK_DCRCFAILIE |
SDMMC_MASK_DTIMEOUTIE |
SDMMC_MASK_RXOVERRIE |
SDMMC_MASK_DATAENDIE;
sdcp->sdmmc->DLEN = blocks * MMCSD_BLOCK_SIZE;
/* Transaction starts just after DTEN bit setting.*/
sdcp->sdmmc->DCTRL = SDMMC_DCTRL_DTDIR |
SDMMC_DCTRL_DBLOCKSIZE_3 |
SDMMC_DCTRL_DBLOCKSIZE_0 |
SDMMC_DCTRL_DMAEN |
SDMMC_DCTRL_DTEN;
if (sdc_lld_prepare_read(sdcp, startblk, blocks, resp) == TRUE)
goto error;
if (sdc_lld_wait_transaction_end(sdcp, blocks, resp) == TRUE)
goto error;
return HAL_SUCCESS;
error:
sdc_lld_error_cleanup(sdcp, blocks, resp);
return HAL_FAILED;
}
/**
* @brief Writes one or more blocks.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] startblk first block to write
* @param[out] buf pointer to the write buffer
* @param[in] n number of blocks to write
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_write_aligned(SDCDriver *sdcp, uint32_t startblk,
const uint8_t *buf, uint32_t blocks) {
uint32_t resp[1];
osalDbgCheck(blocks < 0x1000000 / MMCSD_BLOCK_SIZE);
sdcp->sdmmc->DTIMER = SDMMC_WRITE_TIMEOUT;
/* Checks for errors and waits for the card to be ready for writing.*/
if (_sdc_wait_for_transfer_state(sdcp))
return HAL_FAILED;
/* Prepares the DMA channel for writing.*/
dmaStreamSetMemory0(sdcp->dma, buf);
dmaStreamSetTransactionSize(sdcp->dma,
(blocks * MMCSD_BLOCK_SIZE) / sizeof (uint32_t));
dmaStreamSetMode(sdcp->dma, sdcp->dmamode | STM32_DMA_CR_DIR_M2P);
dmaStreamEnable(sdcp->dma);
/* Setting up data transfer.*/
sdcp->sdmmc->ICR = SDMMC_ICR_ALL_FLAGS;
sdcp->sdmmc->MASK = SDMMC_MASK_DCRCFAILIE |
SDMMC_MASK_DTIMEOUTIE |
SDMMC_MASK_TXUNDERRIE |
SDMMC_MASK_DATAENDIE;
sdcp->sdmmc->DLEN = blocks * MMCSD_BLOCK_SIZE;
/* Talk to card what we want from it.*/
if (sdc_lld_prepare_write(sdcp, startblk, blocks, resp) == TRUE)
goto error;
/* Transaction starts just after DTEN bit setting.*/
sdcp->sdmmc->DCTRL = SDMMC_DCTRL_DBLOCKSIZE_3 |
SDMMC_DCTRL_DBLOCKSIZE_0 |
SDMMC_DCTRL_DMAEN |
SDMMC_DCTRL_DTEN;
if (sdc_lld_wait_transaction_end(sdcp, blocks, resp) == TRUE)
goto error;
return HAL_SUCCESS;
error:
sdc_lld_error_cleanup(sdcp, blocks, resp);
return HAL_FAILED;
}
/**
* @brief Reads one or more blocks.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] startblk first block to read
* @param[out] buf pointer to the read buffer
* @param[in] blocks number of blocks to read
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_read(SDCDriver *sdcp, uint32_t startblk,
uint8_t *buf, uint32_t blocks) {
#if STM32_SDC_SDMMC_UNALIGNED_SUPPORT
if (((unsigned)buf & 3) != 0) {
uint32_t i;
for (i = 0; i < blocks; i++) {
if (sdc_lld_read_aligned(sdcp, startblk, u.buf, 1))
return HAL_FAILED;
memcpy(buf, u.buf, MMCSD_BLOCK_SIZE);
buf += MMCSD_BLOCK_SIZE;
startblk++;
}
return HAL_SUCCESS;
}
#else /* !STM32_SDC_SDIO_UNALIGNED_SUPPORT */
osalDbgAssert((((unsigned)buf & 3) == 0), "unaligned buffer");
#endif /* !STM32_SDC_SDIO_UNALIGNED_SUPPORT */
return sdc_lld_read_aligned(sdcp, startblk, buf, blocks);
}
/**
* @brief Writes one or more blocks.
*
* @param[in] sdcp pointer to the @p SDCDriver object
* @param[in] startblk first block to write
* @param[out] buf pointer to the write buffer
* @param[in] blocks number of blocks to write
*
* @return The operation status.
* @retval HAL_SUCCESS operation succeeded.
* @retval HAL_FAILED operation failed.
*
* @notapi
*/
bool sdc_lld_write(SDCDriver *sdcp, uint32_t startblk,
const uint8_t *buf, uint32_t blocks) {
#if STM32_SDC_SDMMC_UNALIGNED_SUPPORT
if (((unsigned)buf & 3) != 0) {
uint32_t i;
for (i = 0; i < blocks; i++) {
memcpy(u.buf, buf, MMCSD_BLOCK_SIZE);
buf += MMCSD_BLOCK_SIZE;
if (sdc_lld_write_aligned(sdcp, startblk, u.buf, 1))
return HAL_FAILED;
startblk++;
}
return HAL_SUCCESS;
}
#else /* !STM32_SDC_SDIO_UNALIGNED_SUPPORT */
osalDbgAssert((((unsigned)buf & 3) == 0), "unaligned buffer");
#endif /* !STM32_SDC_SDIO_UNALIGNED_SUPPORT */
return sdc_lld_write_aligned(sdcp, startblk, buf, blocks);
}
/**
* @brief Waits for card idle condition.
*
* @param[in] sdcp pointer to the @p SDCDriver object
*
* @return The operation status.
* @retval HAL_SUCCESS the operation succeeded.
* @retval HAL_FAILED the operation failed.
*
* @api
*/
bool sdc_lld_sync(SDCDriver *sdcp) {
/* TODO: Implement.*/
(void)sdcp;
return HAL_SUCCESS;
}
#endif /* HAL_USE_SDC */
/** @} */
|
AdShea/ChibiOS
|
os/hal/ports/STM32/LLD/SDMMCv1/hal_sdc_lld.c
|
C
|
gpl-3.0
| 30,203
|
/***************************************************************************
* Copyright (C) 2011 by Etrnls *
* Etrnls@gmail.com *
* *
* This file is part of Evangel. *
* *
* Evangel 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. *
* *
* Evangel 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 Evangel. If not, see <http://www.gnu.org/licenses/>. *
***************************************************************************/
#ifndef ABSTRACTTASK_H
#define ABSTRACTTASK_H
#include <QObject>
#include <QElapsedTimer>
/*!
* \brief The abstract task interface
*
* \author Etrnls <Etrnls@gmail.com>
*/
class AbstractTask : public QObject
{
Q_OBJECT
Q_CLASSINFO("log", "AbstractTask")
public:
//! \brief Represents the state of the task
enum State
{
RunningState, //!< Downloading & (maybe) uploading
SharingState, //!< Uploading only
PausedState, //!< Paused (a state which can switch to Running or Sharing fast)
StoppedState, //!< Stopped (not completed yet)
CompletedState, //!< Completed and stopped
};
Q_ENUMS(State)
AbstractTask() : downloaded(0), uploaded(0), state(StoppedState) { }
virtual ~AbstractTask() { }
virtual QString getName() const = 0;
virtual qint64 getSize() const = 0;
virtual qreal getProgress() const = 0;
QString getStateString() const;
inline State getState() const
{
return state;
}
inline qint64 getDownloaded() const
{
return downloaded;
}
inline qint64 getUploaded() const
{
return uploaded;
}
inline int getTransferTime() const
{
return state == RunningState || state == SharingState ? timer.elapsed() : 0;
}
public slots:
virtual void start() = 0;
virtual void pause() = 0;
virtual void stop() = 0;
signals:
void stateChanged() const;
protected:
virtual void stateUpdating(State state) = 0;
void setState(State state);
qint64 downloaded; //!< Number of bytes downloaded
qint64 uploaded; //!< Number of bytes uploaded
QElapsedTimer timer;
private:
State state;
};
#endif
|
Etrnls/evangel
|
core/abstracttask.h
|
C
|
gpl-3.0
| 3,006
|
/*
* Copyright (c) 2010 Remko Tronçon
* Licensed under the GNU General Public License v3.
* See Documentation/Licenses/GPLv3.txt for more information.
*/
/*
* Copyright (c) 2011, Isode Limited, London, England.
* All rights reserved.
*/
package com.isode.stroke.compress;
import com.jcraft.jzlib.JZlib;
public class ZLibCompressor extends ZLibCodecompressor {
private static final int COMPRESSION_LEVEL = 9;
public ZLibCompressor() {
int result = stream_.deflateInit(COMPRESSION_LEVEL);
assert (result == JZlib.Z_OK);
}
protected int processZStream() {
return stream_.deflate(JZlib.Z_SYNC_FLUSH);
}
}
|
swift/stroke
|
src/com/isode/stroke/compress/ZLibCompressor.java
|
Java
|
gpl-3.0
| 663
|
# -*- coding: utf-8 -*-
# This file is part of translate.
#
# translate 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.
#
# translate 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
# translate. If not, see <http://www.gnu.org/licenses/>.
"""
translate.client.exceptions
~~~~~~~~~~~~~~~~~~~~~~~~~~~
These are exception classes that are used by translate.client.Client. Most of
these classes are simple wrappers, just to differentiate different types of
errors. They can be constructed from a requests response object, or JSON
,returned from an API call.
"""
import json
import logging
log = logging.getLogger(__name__)
class TranslateException(Exception):
"""Mostly empty base class for exceptions relating to translate.
This class is used as a catch-all for exceptions thrown by the server. If
possible, a more specific subclass of this exception will be used.
"""
@classmethod
def from_json(cls, obj, status_code=400):
"""Return the proper exception class from the JSON object returned from
the server.
"""
exceptions = {
429: RateLimitException,
431: SizeLimitException,
452: TranslationException,
453: TranslatorException,
454: BadLanguagePairException
}
try:
code = obj['code'] if ('code' in obj) else status_code
klass = exceptions[code]
return klass.from_json(obj)
except KeyError:
return cls("Unknown error occured: " + repr(obj))
@classmethod
def from_response(cls, resp):
"""Generate a proper exception from the given requests response object
and return it.
"""
try:
obj = json.loads(resp.text)
return TranslateException.from_json(obj, resp.status_code)
except ValueError:
log.error("Was given invalid JSON, bailing...")
return TranslateException.from_json({}, resp.status_code)
class HTTPException(TranslateException):
"""Raised when an error occurs with the HTTP connection to the server
(e.g. host is not available, doesn't respond, etc.)
"""
pass
class RateLimitException(TranslateException):
"""Exception raised when a client goes over the ratelimit."""
def __init__(self, limit, per, reset):
self.limit = limit
self.per = per
self.reset = reset
@classmethod
def from_json(cls, obj):
try:
details = obj.get('details', {})
return cls(limit=details['limit'], per=details['per'],
reset=details['reset'])
except KeyError:
log.error("Received invalid JSON: " + repr(obj))
return cls(limit=0, per=0, reset=0)
def __str__(self):
return "Rate limit exceeded: {0} reqs / {1}s. Try again at {2}".format(
self.limit, self.per, self.reset)
class SizeLimitException(TranslateException):
"""Exception raised when a client tries to translate a text that is over
the server's size limit.
"""
def __init__(self, len, limit):
self.len = len
self.limit = limit
@classmethod
def from_json(cls, obj):
try:
details = obj['details']
return cls(len=details['len'], limit=details['limit'])
except KeyError:
log.error("Received invalid JSON: %s", repr(obj))
return cls(len=0, limit=0)
def __str__(self):
return "Specified text was too large: %d bytes. Maximum is %d bytes"\
.format(self.len, self.limit)
class TranslationException(TranslateException):
"""Returned on bad parameters to /translate"""
@classmethod
def from_json(cls, obj):
try:
msg = obj['message']
return cls("Bad parameters to translate API method: " + msg)
except KeyError:
log.error("Received invalid JSON: " + repr(obj))
return cls("Bad parameters to translate API method.")
class TranslatorException(TranslateException):
"""Returned when bad parameters are passed to the /translate method. (This
probably indicates some kind of API / Client bug.)
"""
def __init__(self, lang_pair, tried):
self.lang_pair = lang_pair
self.tried = tried
@classmethod
def from_json(cls, obj):
try:
details = obj['details']
pair = (details['from'], details['to'])
return cls(lang_pair=pair, tried=details['tried'])
except KeyError:
log.error("Received invalid JSON: " + repr(obj))
return cls(lang_pair=('unknown', 'unknown'), tried=['unknown'])
def __str__(self):
return "Failed to translate {0} (tried: {1})".format(self.lang_pair,
self.tried)
class BadLanguagePairException(TranslateException):
"""Raised when the client tried to translate using a language pair not
supported by the server
"""
def __init__(self, lang_pair):
self.lang_pair = lang_pair
@classmethod
def from_json(cls, obj):
try:
details = obj['details']
return cls(lang_pair=(details['from'], details['to']))
except KeyError:
log.error("Received invalid JSON: " + repr(obj))
return cls(lang_pair=('unknown', 'unknown'))
def __str__(self):
return "Unsupported language pair: {0}".format(self.lang_pair)
|
erik/translate
|
translate/client/exceptions.py
|
Python
|
gpl-3.0
| 5,955
|
/*
* See Licensing and Copyright notice in naev.h
*/
#ifndef TOOLKIT_PRIV_H
# define TOOLKIT_PRIV_H
#include "naev.h"
#include "log.h"
#include "tk/widget.h"
/*
* Colours to use.
*/
extern const glColour* toolkit_colLight;
extern const glColour* toolkit_col;
extern const glColour* toolkit_colDark;
/**
* @typedef WidgetType
*
* @brief Represents the widget types.
*/
typedef enum WidgetType_ {
WIDGET_NULL,
WIDGET_BUTTON,
WIDGET_TEXT,
WIDGET_IMAGE,
WIDGET_LIST,
WIDGET_RECT,
WIDGET_CUST,
WIDGET_INPUT,
WIDGET_IMAGEARRAY,
WIDGET_FADER,
WIDGET_TABBEDWINDOW,
WIDGET_CHECKBOX,
WIDGET_IMAGE_LAYERED,
WIDGET_IMAGELAYEREDARRAY
} WidgetType;
/**
* @typedef WidgetStatus
*
* @brief Represents widget status.
*
* Only really used by buttons.
*/
typedef enum WidgetStatus_ {
WIDGET_STATUS_NORMAL,
WIDGET_STATUS_MOUSEOVER,
WIDGET_STATUS_MOUSEDOWN,
WIDGET_STATUS_SCROLLING
} WidgetStatus;
#define WGT_FLAG_CANFOCUS (1<<0) /**< Widget can get focus. */
#define WGT_FLAG_RAWINPUT (1<<1) /**< Widget should always get raw input. */
#define WGT_FLAG_ALWAYSMMOVE (1<<2) /**< Widget should always get mouse motion events. */
#define WGT_FLAG_FOCUSED (1<<3) /**< Widget is focused. */
#define WGT_FLAG_KILL (1<<9) /**< Widget should die. */
#define wgt_setFlag(w,f) ((w)->flags |= (f)) /**< Sets a widget flag. */
#define wgt_rmFlag(w,f) ((w)->flags &= ~(f)) /**< Removes a widget flag. */
#define wgt_isFlag(w,f) ((w)->flags & (f)) /**< Checks if a widget has a fla.g */
/**
* @struct Widget
*
* @brief Represents a widget.
*/
typedef struct Widget_ {
struct Widget_ *next; /**< Linked list. */
/* Basic properties. */
char* name; /**< Widget's name. */
WidgetType type; /**< Widget's type. */
int id; /**< Widget ID. */
/* Inheritance. */
unsigned int wdw; /**< Widget's parent window. */
/* Position and dimensions. */
int x; /**< X position within the window. */
int y; /**< Y position within the window. */
int w; /**< Widget width. */
int h; /**< Widget height. */
unsigned int flags; /**< Widget flags. */
/* Event abstraction. */
int (*keyevent) ( struct Widget_ *wgt, SDLKey k, SDLMod m ); /**< Key event handler function for the widget. */
int (*textevent) ( struct Widget_ *wgt, const char *text ); /**< Text event function handler for the widget. */
int (*mmoveevent) ( struct Widget_ *wgt, int x, int y, int rx, int ry); /**< Mouse movement handler function for the widget. */
int (*mclickevent) ( struct Widget_ *wgt, int button, int x, int y ); /**< Mouse click event handler function for the widget. */
#if SDL_VERSION_ATLEAST(2,0,0)
int (*mwheelevent) ( struct Widget_ *wgt, SDL_MouseWheelEvent event ); /**< Mouse click event handler function for the widget. */
#endif /* SDL_VERSION_ATLEAST(2,0,0) */
void (*scrolldone) ( struct Widget_ *wgt ); /**< Scrolling is over. */
int (*rawevent) ( struct Widget_ *wgt, SDL_Event *event ); /**< Raw event handler function for widget. */
void (*exposeevent) ( struct Widget_ *wgt, int exposed ); /**< Widget show and hide handler. */
/* Misc. routines. */
void (*render) ( struct Widget_ *wgt, double x, double y ); /**< Render function for the widget. */
void (*renderOverlay) ( struct Widget_ *wgt, double x, double y ); /**< Overlay render fuction for the widget. */
void (*cleanup) ( struct Widget_ *wgt ); /**< Clean up function for the widget. */
void (*focusGain) ( struct Widget_ *wgt ); /**< Get focus. */
void (*focusLose) ( struct Widget_ *wgt ); /**< Lose focus. */
/* Status of the widget. */
WidgetStatus status; /**< Widget status. */
/* Type specific data (defined by type). */
union {
WidgetButtonData btn; /**< WIDGET_BUTTON */
WidgetTextData txt; /**< WIDGET_TEXT */
WidgetImageData img; /**< WIDGET_IMAGE */
WidgetImageLayeredData imgl; /**< WIDGET_IMAGE */
WidgetListData lst; /**< WIDGET_LIST */
WidgetRectData rct; /**< WIDGET_RECT */
WidgetCustData cst; /**< WIDGET_CUST */
WidgetInputData inp; /**< WIDGET_INPUT */
WidgetImageArrayData iar; /**< WIDGET_IMAGEARRAY */
WidgetImageLayeredArrayData iarl; /**< WIDGET_IMAGELAYEREDARRAY */
WidgetFaderData fad; /**< WIDGET_FADER */
WidgetTabbedWindowData tab; /**< WIDGET_TABBEDWINDOW */
WidgetCheckboxData chk; /**< WIDGET_CHECKBOX */
} dat; /**< Stores the widget specific data. */
} Widget;
#define WINDOW_NOFOCUS (1<<0) /**< Window can not be active window. */
#define WINDOW_NOINPUT (1<<1) /**< Window receives no input. */
#define WINDOW_NORENDER (1<<2) /**< Window does not render even if it should. */
#define WINDOW_NOBORDER (1<<3) /**< Window does not need border. */
#define WINDOW_FULLSCREEN (1<<4) /**< Window is fullscreen. */
#define WINDOW_KILL (1<<9) /**< Window should die. */
#define window_isFlag(w,f) ((w)->flags & (f)) /**< Checks a window flag. */
#define window_setFlag(w,f) ((w)->flags |= (f)) /**< Sets a window flag. */
#define window_rmFlag(w,f) ((w)->flags &= ~(f)) /**< Removes a window flag. */
/**
* @struct Window
*
* @brief Represents a graphical window.
*/
typedef struct Window_ {
struct Window_ *next; /* Linked list. */
unsigned int id; /**< Unique ID. */
char *name; /**< Window name - should be unique. */
unsigned int flags; /**< Window flags. */
int idgen; /**< ID generator for widgets. */
unsigned int parent; /**< Parent window, will close if this one closes. */
void (*close_fptr)(unsigned int wid, char* name); /**< How to close the window. */
void (*accept_fptr)(unsigned int wid, char* name); /**< Triggered by hitting 'enter' with no widget that catches the keypress. */
void (*cancel_fptr)(unsigned int wid, char* name); /**< Triggered by hitting 'escape' with no widget that catches the keypress. */
int (*keyevent)(unsigned int wid,SDLKey,SDLMod); /**< User defined custom key event handler. */
int (*eventevent)(unsigned int wid,SDL_Event *evt); /**< User defined event handler. */
/* Position and dimensions. */
int x; /**< X position of the window. */
int y; /**< Y position of the window. */
double xrel; /**< X position relative to screen width. */
double yrel; /**< Y position relative to screen height. */
int w; /**< Window width. */
int h; /**< Window height. */
int exposed; /**< Whether window is visible or hidden. */
int focus; /**< Current focused widget. */
Widget *widgets; /**< Widget storage. */
void *udata; /**< Custom data of the window. */
} Window;
/* Window stuff. */
Window* toolkit_getActiveWindow (void);
Window* window_wget( const unsigned int wid );
void toolkit_setWindowPos( Window *wdw, int x, int y );
int toolkit_inputWindow( Window *wdw, SDL_Event *event, int purge );
void window_render( Window* w );
void window_renderOverlay( Window* w );
/* Widget stuff. */
Widget* window_newWidget( Window* w, const char *name );
void widget_cleanup( Widget *widget );
Widget* window_getwgt( const unsigned int wid, const char* name );
void toolkit_setPos( Window *wdw, Widget *wgt, int x, int y );
void toolkit_focusSanitize( Window *wdw );
void toolkit_focusClear( Window *wdw );
void toolkit_nextFocus( Window *wdw );
void toolkit_prevFocus( Window *wdw );
void toolkit_focusWidget( Window *wdw, Widget *wgt );
void toolkit_defocusWidget( Window *wdw, Widget *wgt );
/* Render stuff. */
void toolkit_drawOutline( int x, int y, int w, int h, int b,
const glColour* c, const glColour* lc );
void toolkit_drawOutlineThick( int x, int y, int w, int h, int b,
int thick, const glColour* c, const glColour* lc );
void toolkit_drawScrollbar( int x, int y, int w, int h, double pos );
void toolkit_drawRect( int x, int y, int w, int h,
const glColour* c, const glColour* lc );
void toolkit_drawAltText( int bx, int by, const char *alt );
/* Input stuff. */
Uint32 toolkit_inputTranslateCoords( Window *w, SDL_Event *event,
int *x, int *y, int *rx, int *ry );
#endif /* TOOLKIT_PRIV_H */
|
Kinniken/NoxImperii
|
src/tk/toolkit_priv.h
|
C
|
gpl-3.0
| 8,184
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'agent_connect_dlg.ui'
#
# Created: Tue Oct 12 14:22:17 2010
# by: PyQt4 UI code generator 4.7.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObjectName("Dialog")
Dialog.resize(253, 111)
self.gridLayout = QtGui.QGridLayout(Dialog)
self.gridLayout.setObjectName("gridLayout")
self.label = QtGui.QLabel(Dialog)
self.label.setObjectName("label")
self.gridLayout.addWidget(self.label, 0, 0, 1, 1)
self.agent_addrinfo = QtGui.QComboBox(Dialog)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.agent_addrinfo.sizePolicy().hasHeightForWidth())
self.agent_addrinfo.setSizePolicy(sizePolicy)
self.agent_addrinfo.setEditable(True)
self.agent_addrinfo.setObjectName("agent_addrinfo")
self.gridLayout.addWidget(self.agent_addrinfo, 0, 1, 1, 1)
self.disconnect_from_server = QtGui.QCheckBox(Dialog)
self.disconnect_from_server.setObjectName("disconnect_from_server")
self.gridLayout.addWidget(self.disconnect_from_server, 1, 0, 1, 2)
self.buttonBox = QtGui.QDialogButtonBox(Dialog)
self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
self.buttonBox.setObjectName("buttonBox")
self.gridLayout.addWidget(self.buttonBox, 2, 0, 1, 2)
self.retranslateUi(Dialog)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
QtCore.QMetaObject.connectSlotsByName(Dialog)
def retranslateUi(self, Dialog):
Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
self.label.setText(QtGui.QApplication.translate("Dialog", "Agent", None, QtGui.QApplication.UnicodeUTF8))
self.disconnect_from_server.setText(QtGui.QApplication.translate("Dialog", "Disconnect Clients from server", None, QtGui.QApplication.UnicodeUTF8))
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Dialog = QtGui.QDialog()
ui = Ui_Dialog()
ui.setupUi(Dialog)
Dialog.show()
sys.exit(app.exec_())
|
mnunberg/yobot
|
py/gui/agent_connect_dlg.py
|
Python
|
gpl-3.0
| 2,632
|
/*
BoundingVolume.h
Author: Chris Serson
Last Edited: October 14, 2016
Description: Classes and methods defining bounding volumes. Currently only BoundingSphere.
Usage: - Proper shutdown is handled by the destructor.
Future Work: - Add collision detection to Bounding Sphere.
- Add Axis Aligned Bounding Box.
- Add Object Oriented Bounding Box.
- Add K-DOP.
*/
#pragma once
#include <DirectXMath.h>
using namespace DirectX;
class BoundingSphere;
// Find a bounding sphere by finding the circumcenter of 3 points and the distance from the points to the circumcenter
BoundingSphere FindBoundingSphere(XMFLOAT3 a, XMFLOAT3 b, XMFLOAT3 c);
class BoundingSphere {
public:
BoundingSphere(float r = 0.0f, XMFLOAT3 c = XMFLOAT3(0.0f, 0.0f, 0.0f)) : m_valRadius(r), m_vCenter(c) {}
~BoundingSphere() {}
float GetRadius() { return m_valRadius; }
void SetRadius(float r) { m_valRadius = r; }
XMFLOAT3 GetCenter() { return m_vCenter; }
void SetCenter(XMFLOAT3 c) { m_vCenter = c; }
void SetCenter(float x, float y, float z) { m_vCenter = XMFLOAT3(x, y, z); }
private:
float m_valRadius;
XMFLOAT3 m_vCenter;
};
|
Traagen/Render-Terrain
|
Render Terrain/BoundingVolume.h
|
C
|
gpl-3.0
| 1,136
|
/* This file is part of the Neper software package. */
/* Copyright (C) 2003-2022, Romain Quey. */
/* See the COPYING file in the top-level directory. */
#ifdef __cplusplus
extern "C"
{
#endif
extern void net_mtess_flatten_gen (struct TESS *Tess, int TessId,
struct TESS *pFTess, struct FLATTEN *pFlatten);
#ifdef __cplusplus
}
#endif
|
rquey/neper
|
src/neper_t/net_flatten/net_mtess_flatten/net_mtess_flatten_gen/net_mtess_flatten_gen.h
|
C
|
gpl-3.0
| 377
|
from Ponos import init_db
from env_vars import *
import sqlite3
import os
print(DB_PATH)
open(DB_PATH, 'w').close()
init_db()
|
shadowjig/ponos
|
initalize_db.py
|
Python
|
gpl-3.0
| 127
|
using FizzWare.NBuilder;
using FluentAssertions;
using NUnit.Framework;
using NzbDrone.Core.DecisionEngine.Specifications.Search;
using NzbDrone.Core.IndexerSearch.Definitions;
using NzbDrone.Core.Music;
using NzbDrone.Core.Parser.Model;
using NzbDrone.Test.Common;
namespace NzbDrone.Core.Test.DecisionEngineTests.Search
{
[TestFixture]
public class ArtistSpecificationFixture : TestBase<ArtistSpecification>
{
private Artist _artist1;
private Artist _artist2;
private RemoteAlbum _remoteAlbum = new RemoteAlbum();
private SearchCriteriaBase _searchCriteria = new AlbumSearchCriteria();
[SetUp]
public void Setup()
{
_artist1 = Builder<Artist>.CreateNew().With(s => s.Id = 1).Build();
_artist2 = Builder<Artist>.CreateNew().With(s => s.Id = 2).Build();
_remoteAlbum.Artist = _artist1;
}
[Test]
public void should_return_false_if_artist_doesnt_match()
{
_searchCriteria.Artist = _artist2;
Subject.IsSatisfiedBy(_remoteAlbum, _searchCriteria).Accepted.Should().BeFalse();
}
[Test]
public void should_return_true_when_artist_ids_match()
{
_searchCriteria.Artist = _artist1;
Subject.IsSatisfiedBy(_remoteAlbum, _searchCriteria).Accepted.Should().BeTrue();
}
}
}
|
lidarr/Lidarr
|
src/NzbDrone.Core.Test/DecisionEngineTests/Search/ArtistSpecificationFixture.cs
|
C#
|
gpl-3.0
| 1,394
|
#include "ship.h"
#include <stdio.h>
cargo **docks, **shipStr;
pthread_mutex_t *countLock, *entryLock, nthLock;
pthread_cond_t *dockLock, *loadLock, *unloadLock, shipDestroy;
int *waitLoad, *waitUnload, *loading, *unloading;
int *dockCap, **route, *tTime, *shipCap, *aTime, *rLen;
void* shipMain(void*);
int nth=0;
struct timeval simStart;
int **dockQ, *front, *rear;
int Nd, Ns, Nc;
int main()
{
int i,j;
pthread_t tid;
pthread_attr_t attr;
scanf("%d%d%d", &Nd, &Ns, &Nc);
dockLock = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)*Nd);
loadLock = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)*Nd);
unloadLock = (pthread_cond_t*)malloc(sizeof(pthread_cond_t)*Nd);
docks = (cargo**)calloc(sizeof(cargo*), Nd);
shipStr = (cargo**)calloc(sizeof(cargo*), Ns);
countLock = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)*Nd);
entryLock = (pthread_mutex_t*)malloc(sizeof(pthread_mutex_t)*Nd);
dockCap = (int*)malloc(sizeof(int)*Nd);
loading = (int*)malloc(sizeof(int)*Nd);
unloading = (int*)malloc(sizeof(int)*Nd);
dockQ = (int**)malloc(sizeof(int*)*Nd);
front = (int*)malloc(sizeof(int)*Nd);
rear = (int*)malloc(sizeof(int)*Nd);
route = (int**)malloc(sizeof(int*)*Ns);
tTime = (int*)malloc(sizeof(int)*Ns);
shipCap = (int*)malloc(sizeof(int)*Ns);
aTime = (int*)malloc(sizeof(int)*Ns);
rLen = (int*)malloc(sizeof(int)*Ns);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
pthread_cond_init(&shipDestroy, NULL);
pthread_mutex_init(&nthLock, NULL);
for(i=0;i<Nd;i++)
{
scanf("%d", dockCap+i);
if(pthread_cond_init(dockLock+i, NULL)==-1||pthread_cond_init(loadLock+i, NULL)==-1||pthread_cond_init(unloadLock+i, NULL))
{
puts("error on pthread_cond_init");
return 1;
}
if(pthread_mutex_init(entryLock+i, NULL)==-1||pthread_mutex_init(countLock+i,NULL)==-1)
{
puts("error on pthread_mutex_init");
return 1;
}
dockQ[i] = (int*)malloc(sizeof(int)*Ns);
front[i]=rear[i]=0;
loading[i]=unloading[i]=0;
}
for(i=0;i<Ns;i++)
{
scanf("%d%d%d%d", tTime+i, shipCap+i, aTime+i, rLen+i);
route[i] = (int*)malloc(sizeof(int)*rLen[i]);
for(j=0;j<rLen[i];j++)
scanf("%d", route[i]+j);
}
for(i=0;i<Nc;i++)
{
scanf("%d", &j);
cargo *new = malloc(sizeof(cargo));
scanf("%d", &new->dest);
new->id=i;
new->next=docks[j];
new->state=0;
if(pthread_mutex_init(&new->mtx, NULL)==-1)
{
puts("error on cargo mutex_init");
return 1;
}
docks[j] = new;
}
InitWriteOutput();
gettimeofday(&simStart, NULL);
for(i=0;i<Ns;i++)
pthread_create(&tid, &attr, shipMain, (void*)(long)i);
pthread_mutex_lock(&nthLock);
while(nth>0)
pthread_cond_wait(&shipDestroy, &nthLock);
pthread_mutex_unlock(&nthLock);
pthread_cond_destroy(&shipDestroy);
pthread_mutex_destroy(&nthLock);
for(i=0;i<Nd;i++)
{
pthread_cond_destroy(dockLock+i);
pthread_cond_destroy(loadLock+i);
pthread_cond_destroy(unloadLock+i);
pthread_mutex_destroy(entryLock+i);
pthread_mutex_destroy(countLock+i);
free(dockQ[i]);
cargo *it=docks[i];
while(it!=NULL)
{
docks[i]=it;
it=it->next;
pthread_mutex_destroy(&docks[i]->mtx);
free(docks[i]);
}
}
for(i=0;i<Ns;i++)
{
free(route[i]);
cargo *it=shipStr[i];
while(it!=NULL)
{
shipStr[i]=it;
it=it->next;
free(shipStr[i]);
}
}
free(route);
free(countLock);
free(entryLock);
free(dockLock);
free(loadLock);
free(unloadLock);
free(docks);
free(shipStr);
free(tTime);
free(aTime);
free(shipCap);
free(rLen);
free(dockQ);
free(dockCap);
free(front);
free(rear);
free(loading);
free(unloading);
return 0;
}
|
kadircet/CENG
|
334/the2t/main.c
|
C
|
gpl-3.0
| 3,599
|
/*
* Copyright (C) 2021 Christopher J. Howard
*
* This file is part of Antkeeper source code.
*
* Antkeeper source code is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Antkeeper source code is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Antkeeper source code. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ANTKEEPER_FINAL_PASS_HPP
#define ANTKEEPER_FINAL_PASS_HPP
#include "renderer/render-pass.hpp"
#include "math/math.hpp"
#include "gl/shader-program.hpp"
#include "gl/shader-input.hpp"
#include "gl/vertex-buffer.hpp"
#include "gl/vertex-array.hpp"
#include "gl/texture-2d.hpp"
#include "animation/tween.hpp"
class resource_manager;
/**
*
*/
class final_pass: public render_pass
{
public:
final_pass(gl::rasterizer* rasterizer, const gl::framebuffer* framebuffer, resource_manager* resource_manager);
virtual ~final_pass();
virtual void render(render_context* context) const final;
void set_color_texture(const gl::texture_2d* texture);
void set_bloom_texture(const gl::texture_2d* texture);
void set_blue_noise_texture(const gl::texture_2d* texture);
void set_time_tween(const tween<double>* time);
private:
gl::shader_program* shader_program;
const gl::shader_input* color_texture_input;
const gl::shader_input* bloom_texture_input;
const gl::shader_input* blue_noise_texture_input;
const gl::shader_input* blue_noise_scale_input;
const gl::shader_input* resolution_input;
const gl::shader_input* time_input;
gl::vertex_buffer* quad_vbo;
gl::vertex_array* quad_vao;
const gl::texture_2d* color_texture;
const gl::texture_2d* bloom_texture;
const gl::texture_2d* blue_noise_texture;
float blue_noise_scale;
const tween<double>* time_tween;
};
#endif // ANTKEEPER_FINAL_PASS_HPP
|
cjhoward/antkeeper
|
src/renderer/passes/final-pass.hpp
|
C++
|
gpl-3.0
| 2,198
|
/*
Copyright (C) 2011-2013 de4dot@gmail.com
This file is part of de4dot.
de4dot 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.
de4dot 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 de4dot. If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using dnlib.DotNet.Emit;
using de4dot.blocks;
using de4dot.blocks.cflow;
namespace de4dot.code.deobfuscators.dotNET_Reactor.v4 {
class DnrMethodCallInliner : MethodCallInliner {
public DnrMethodCallInliner()
: base(false) {
}
protected override Instruction GetFirstInstruction(IList<Instruction> instrs, ref int index) {
var instr = GetFirstInstruction(instrs, index);
if (instr != null)
index = instrs.IndexOf(instr);
return DotNetUtils.GetInstruction(instrs, ref index);
}
Instruction GetFirstInstruction(IList<Instruction> instrs, int index) {
try {
var instr = instrs[index];
if (!instr.IsBr())
return null;
instr = instr.Operand as Instruction;
if (instr == null)
return null;
if (!instr.IsLdcI4() || instr.GetLdcI4Value() != 0)
return null;
instr = instrs[instrs.IndexOf(instr) + 1];
if (!instr.IsBrtrue())
return null;
return instrs[instrs.IndexOf(instr) + 1];
}
catch {
return null;
}
}
}
}
|
telerik/justdecompile-plugins
|
Reflexil.JustDecompile/reflexil.1.8.src/Libs/Sources/De4dot/sources/de4dot.code/deobfuscators/dotNET_Reactor/v4/DnrMethodCallInliner.cs
|
C#
|
gpl-3.0
| 1,772
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.12"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>libjade: Class Members - Functions</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">libjade
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.12 -->
<script type="text/javascript" src="menudata.js"></script>
<script type="text/javascript" src="menu.js"></script>
<script type="text/javascript">
$(function() {
initMenu('',false,false,'search.php','Search');
});
</script>
<div id="main-nav"></div>
</div><!-- top -->
<div class="contents">
 
<h3><a id="index_u"></a>- u -</h3><ul>
<li>undo()
: <a class="el" href="class_drawing_view.html#add49fbcbf06f76c13650db8675536f27">DrawingView</a>
</li>
<li>undoLimit()
: <a class="el" href="class_drawing_view.html#ab86fc70768259a5c5cc86584294ea611">DrawingView</a>
</li>
<li>undoText()
: <a class="el" href="class_drawing_view.html#a0e90ab426836d80c3fffab16fef24703">DrawingView</a>
</li>
<li>ungroup()
: <a class="el" href="class_drawing_view.html#a9fd86983bb8881e2f6dd32a33138670c">DrawingView</a>
</li>
<li>unsetDefaultValue()
: <a class="el" href="class_drawing_item_style.html#a07bd46874d191501a956ffb77d5c181c">DrawingItemStyle</a>
</li>
<li>unsetValue()
: <a class="el" href="class_drawing_item_style.html#aec1c07010be5864312f1e100b3118d8f">DrawingItemStyle</a>
</li>
</ul>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.12
</small></address>
</body>
</html>
|
jaallen85/libjade
|
docs/functions_func_u.html
|
HTML
|
gpl-3.0
| 2,437
|
import freeze from 'deep-freeze'
import {ensure} from '#/main/core/tests'
import {TYPE_QUIZ, TYPE_STEP} from './../enums'
import select from './selectors'
import {tex, t} from '#/main/core/translation'
describe('Thumbnails selector', () => {
it('returns the quiz and step thumbs with active and errors set', () => {
ensure.equal(select.thumbnails(fixtureState1()), [
{
id: '1',
title: t('parameters'),
type: TYPE_QUIZ,
active: false,
hasErrors: false
},
{
id: 'a',
title: `${tex('step')} 1`,
type: TYPE_STEP,
active: false,
hasErrors: true
},
{
id: 'b',
title: `${tex('step')} 2`,
type: TYPE_STEP,
active: true,
hasErrors: false
}
])
})
})
describe('Current object deep selector', () => {
it('returns quiz properties if quiz is selected', () => {
ensure.equal(select.currentObjectDeep(fixtureState2()), {
type: TYPE_QUIZ,
id: '1'
})
})
it('returns step details if step is selected', () => {
ensure.equal(select.currentObjectDeep(fixtureState3()), {
type: TYPE_STEP,
id: 'b',
title: 'B',
description: 'B desc',
parameters: {
maxAttempts: 5
},
items: [
{
id: 'x',
type: 'text/html'
}
]
})
})
})
describe('Step open panel selector', () => {
it('returns false if no step is selected', () => {
ensure.equal(select.stepOpenPanel(fixtureState4()), false)
})
it('returns open panel key of current step', () => {
ensure.equal(select.stepOpenPanel(fixtureState5()), 'bar')
})
})
describe('Next object selector', () => {
it('returns the quiz if quiz is already current', () => {
ensure.equal(select.nextObject(fixtureState2()), {
id: '1',
type: TYPE_QUIZ
})
})
it('returns the quiz if there is only one the step', () => {
ensure.equal(select.nextObject(fixtureState6()), {
id: '1',
type: TYPE_QUIZ
})
})
it('returns the next step if there is one', () => {
ensure.equal(select.nextObject(fixtureState7()), {
id: 'b',
type: TYPE_STEP
})
})
it('returns the previous step if current is the second and last step', () => {
ensure.equal(select.nextObject(fixtureState8()), {
id: 'a',
type: TYPE_STEP
})
})
})
describe('Valid selector', () => {
it('returns false in case of item errors', () => {
ensure.equal(select.valid(fixtureState1()), false)
})
it('returns false in case of quiz errors', () => {
ensure.equal(select.valid(fixtureState2()), false)
})
it('returns true if no errors', () => {
ensure.equal(select.valid(fixtureState3()), true)
})
})
function fixtureState1() {
return freeze({
quiz: {
id: '1',
steps: ['a', 'b']
},
steps: {
'a': {
id: 'a',
items: ['x']
},
'b': {
id: 'b',
items: []
}
},
items: {
x: {
_errors: {foo: 'bar'}
}
},
editor: {
currentObject: {
id: 'b',
type: TYPE_STEP
}
}
})
}
function fixtureState2() {
return freeze({
quiz: {
id: '1',
steps: ['a', 'b'],
_errors: {bar: 'baz'}
},
steps: {
'a': {
id: 'a',
items: []
},
'b': {
id: 'b',
items: []
}
},
items: {},
editor: {
currentObject: {
id: '1',
type: TYPE_QUIZ
}
}
})
}
function fixtureState3() {
return freeze({
quiz: {
id: '1',
steps: ['a', 'b']
},
steps: {
'a': {
id: 'a',
items: []
},
'b': {
id: 'b',
title: 'B',
description: 'B desc',
parameters: {maxAttempts: 5},
items: ['x']
}
},
items: {
'x': {
id: 'x',
type: 'text/html'
}
},
editor: {
currentObject: {
id: 'b',
type: TYPE_STEP
}
}
})
}
function fixtureState4() {
return freeze({
editor: {
currentObject: {
id: 'a',
type: TYPE_QUIZ
},
openPanels: {
[TYPE_QUIZ]: 'foo',
[TYPE_STEP]: {}
}
}
})
}
function fixtureState5() {
return freeze({
editor: {
currentObject: {
id: 'b',
type: TYPE_STEP
},
openPanels: {
[TYPE_QUIZ]: false,
[TYPE_STEP]: {
'a': 'foo',
'b': 'bar'
}
}
}
})
}
function fixtureState6() {
return freeze({
quiz: {
id: '1',
steps: ['a']
},
steps: {
'a': {
id: 'a',
items: []
}
},
editor: {
currentObject: {
id: 'a',
type: TYPE_STEP
}
}
})
}
function fixtureState7() {
return freeze({
quiz: {
id: '1',
steps: ['a', 'b']
},
steps: {
'a': {
id: 'a',
items: []
},
'b': {
id: 'b',
items: []
}
},
items: {},
editor: {
currentObject: {
id: 'a',
type: TYPE_STEP
}
}
})
}
function fixtureState8() {
return freeze({
quiz: {
id: '1',
steps: ['a', 'b']
},
steps: {
'a': {
id: 'a',
items: []
},
'b': {
id: 'b',
items: []
}
},
items: {},
editor: {
currentObject: {
id: 'b',
type: TYPE_STEP
}
}
})
}
|
ClaroBot/Distribution
|
plugin/exo/Resources/modules/quiz/editor/selectors.test.js
|
JavaScript
|
gpl-3.0
| 5,556
|
require 'nokogiri'
require 'digest'
require_relative '../objects/system'
require_relative '../objects/module'
class SystemReader
# uses nokogiri to extract all system information from scenario.xml
# This includes module filters, which are module objects that contain filters for selecting
# from the actual modules that are available
# @return [Array] Array containing Systems objects
def self.read_scenario(scenario_file)
systems = []
Print.verbose "Reading scenario file: #{scenario_file}"
doc, xsd = nil
begin
doc = Nokogiri::XML(File.read(scenario_file))
rescue
Print.err "Failed to read scenario configuration file (#{scenario_file})"
exit
end
# validate scenario XML against schema
begin
xsd = Nokogiri::XML::Schema(File.open(SCENARIO_SCHEMA_FILE))
xsd.validate(doc).each do |error|
Print.err "Error in scenario configuration file (#{scenario_file}):"
Print.err ' ' + error.message
exit
end
rescue Exception => e
Print.err "Failed to validate scenario configuration file (#{scenario_file}): against schema (#{SCENARIO_SCHEMA_FILE})"
Print.err e.message
exit
end
# remove xml namespaces for ease of processing
doc.remove_namespaces!
doc.xpath('/scenario/system').each_with_index do |system_node, system_index|
module_selectors = []
system_attributes = {}
system_name = system_node.at_xpath('system_name').text
Print.verbose "system: #{system_name}"
# system attributes, such as basebox selection
system_node.xpath('@*').each do |attr|
system_attributes["#{attr.name}"] = attr.text unless attr.text.nil? || attr.text == ''
end
# literal values to store directly in a datastore
system_node.xpath('*[@into_datastore]/value').each do |value|
name = value.xpath('../@into_datastore').to_s
($datastore[name] ||= []).push(value.text)
end
# datastore in a datastore
if system_node.xpath('//*[@into_datastore]/datastore').to_s != ""
Print.err "WARNING: a datastore cannot capture the values from another datastore (this will be ignored)"
Print.err "The scenario has datastore(s) that try to save directly into another datastore -- currently this is only possible via an encoder"
sleep 2
end
# for each module selection
system_node.xpath('//vulnerability | //service | //utility | //build | //network | //base | //encoder | //generator').each do |module_node|
# create a selector module, which is a regular module instance used as a placeholder for matching requirements
module_selector = Module.new(module_node.name)
# create a unique id for tracking variables between modules
module_selector.unique_id = module_node.path.gsub(/[^a-zA-Z0-9]/, '')
# check if we need to be sending the module output to another module
module_node.xpath('parent::input').each do |input|
# Parent is input -- track that we need to send write value somewhere
# if we need to feed results to parent module
if input.xpath('@into').to_s
input.xpath('..').each do |input_parent|
module_selector.write_output_variable = input.xpath('@into').to_s
module_selector.write_to_module_with_id = input_parent.path.gsub(/[^a-zA-Z0-9]/, '')
end
end
# check if we need to send the module output to a datastore
if input.xpath('@into_datastore').to_s
module_selector.write_to_datastore = input.xpath('@into_datastore').to_s
end
end
# check if we are being passed an input *literal value*
module_node.xpath('input/value').each do |input_value|
variable = input_value.xpath('../@into').to_s
value = input_value.text
Print.verbose " -- literal value: #{variable} = #{value}"
(module_selector.received_inputs[variable] ||= []).push(value)
end
# check if we are being passed a datastore as input
module_node.xpath('input/datastore').each do |input_value|
access = input_value.xpath('@access').to_s
if access == ''
access = 'all'
end
variable = input_value.xpath('../@into').to_s
value = input_value.text
Print.verbose " -- datastore: #{variable} = #{value}"
(module_selector.received_datastores[variable] ||= []).push('variablename' => value, 'access' => access)
end
module_node.xpath('@*').each do |attr|
module_selector.attributes["#{attr.name}"] = [attr.text] unless attr.text.nil? || attr.text == ''
end
Print.verbose " #{module_node.name} (#{module_selector.unique_id}), selecting based on:"
module_selector.attributes.each do |attr|
if attr[0] && attr[1] && attr[0].to_s != "module_type"
Print.verbose " - #{attr[0].to_s} ~= #{attr[1].to_s}"
end
end
# If this module is for this system
if module_selector.system_number == (system_index + 1)
# insert into module list
# if this module feeds output to another, ensure list order makes sense for processing...
if module_selector.write_output_variable != nil
Print.verbose " -- writes to: #{module_selector.write_to_module_with_id} - #{module_selector.write_output_variable}"
# insert into module list before the module we are writing to
insert_pos = -1 # end of list
for i in 0..module_selectors.size-1
if module_selector.write_to_module_with_id == module_selectors[i].unique_id
# found position of earlier module this one feeds into, so put this one first
insert_pos = i
end
end
module_selectors.insert(insert_pos, module_selector)
else
# otherwise just append module to end of list
module_selectors << module_selector
end
end
end
systems << System.new(system_name, system_attributes, module_selectors)
end
return systems
end
end
|
Jjk422/SecGen
|
lib/readers/system_reader.rb
|
Ruby
|
gpl-3.0
| 6,232
|
Param($computer,[switch]$xahome,[switch]$calabrio,[switch]$log,[switch]$lhc)
if($computer -eq $null){$computer = "."}
if($xahome){$computer = get-xaapplicationreport home | select -expand servernames | sort}
foreach($comp in $computer){
if($log)
{
if(test-path \\$comp\c$\reboot.log){more \\$comp\c$\reboot.log}
elseif(test-path \\$comp\m$\reboot.log){more \\$comp\m$\reboot.log}
else{write-host "This script hasn't been executed on $comp yet."}
}
$psobj = new-object PSObject
$wmiOsInformation = Get-WmiObject -computer $comp -class Win32_OperatingSystem
$startup = $wmiOsInformation.ConvertToDateTime($wmiOsInformation.LastBootUpTime)
$psobj | add-member NoteProperty Computer $comp
$psobj | add-member NoteProperty StartUpTime $startup
if($lhc)
{
if(test-path \\$comp\c$\reboot.log){
Get-Content \\$comp\c$\reboot.log | %{
if($_.Contains(" LHC ")){$psobj | add-member NoteProperty LHCStatus $_}
}
}
elseif(test-path \\$comp\m$\reboot.log){
Get-Content \\$comp\m$\reboot.log | %{
if($_.Contains(" LHC ")){$psobj | add-member NoteProperty LHCStatus $_}
}
}
else{$psobj | add-member NoteProperty LHCStatus "no record"}
}
$psobj
}
|
tsmooth3/pscripts
|
Get-StartUpTime.ps1
|
PowerShell
|
gpl-3.0
| 1,182
|
#pragma once
/***************************************************************
* This source files comes from the xLights project
* https://www.xlights.org
* https://github.com/smeighan/xLights
* See the github commit history for a record of contributing
* developers.
* Copyright claimed based on commit dates recorded in Github
* License: https://github.com/smeighan/xLights/blob/master/License.txt
**************************************************************/
#include "Model.h"
class SingleLineModel : public ModelWithScreenLocation<TwoPointScreenLocation>
{
public:
SingleLineModel(wxXmlNode *node, const ModelManager &manager, bool zeroBased = false);
SingleLineModel(int lights, const Model &base, int strand, int node = -1);
SingleLineModel(const ModelManager &manager);
virtual ~SingleLineModel();
void InitLine();
void Reset(int lights, const Model &base, int strand, int node = -1, bool forceDirection = false);
virtual const std::vector<std::string> &GetBufferStyles() const override;
virtual int GetLightsPerNode() const override { return parm3; } // default to one unless a model supports this
virtual void AddTypeProperties(wxPropertyGridInterface* grid) override;
virtual int OnPropertyGridChange(wxPropertyGridInterface *grid, wxPropertyGridEvent& event) override;
virtual bool SupportsExportAsCustom() const override { return true; }
virtual bool SupportsWiringView() const override { return false; }
protected:
static std::vector<std::string> LINE_BUFFER_STYLES;
virtual void InitModel() override;
private:
};
|
cjd/xLights
|
xLights/models/SingleLineModel.h
|
C
|
gpl-3.0
| 1,687
|
/*
This file is part of ghtml.
ghtml 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.
ghtml 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 ghtml. If not, see <http://www.gnu.org/licenses/>.
*/
void ghtml_webview_js_console_arguments (void * environment, void * console, int argc, char * argv[]) {
void *jsArgData[argc + 1], *jsTemp;
void **jsUsrArgs = (jsArgData + 1);
int i = 0;
// Set the "application path" argument.
jsArgData[0] = (void *) JSValueMakeString(
environment, jsTemp = JSStringCreateWithUTF8CString(ghtml_app_file)
); JSStringRelease(jsTemp);
// Set remaining arguments
for (i = 0; i < argc ; i++) {
jsUsrArgs[i] = (void *) JSValueMakeString(
environment, jsTemp = JSStringCreateWithUTF8CString(argv[i])
); JSStringRelease(jsTemp);
}
void *jsarguments = seed_make_array(
environment, jsArgData, argc + 1, NULL
);
JSObjectSetProperty(
environment, console, jsTemp = JSStringCreateWithUTF8CString("arguments"),
jsarguments, kJSPropertyAttributeReadOnly | kJSPropertyAttributeDontDelete,
NULL
); JSStringRelease(jsTemp);
}
|
hypersoft/ghtml
|
include/webview/js/console/arguments.c
|
C
|
gpl-3.0
| 1,554
|
# Addierer mit += 1
# Eingaben erhalten
a = input("Dies ist ein Addierer!\nGeben Sie a ein: ")
b = input("Geben Sie b ein: ")
# Zeichenketten in Zahlen umwandeln
a = int(a)
b = int(b)
# neue Variable verwenden, Eingaben nicht verändern
result = a
i = 0
if b > 0: # wenn b größer Null
while i < b: # dann Schleife positiv durchlaufen
result += 1
i += 1
elif b < 0: # wenn b kleiner Null
while i > b: # dann Schleife negativ durchlaufen
result -= 1
i -= 1
print("\nDas Ergebnis ist: " + str(result))
|
Informatik-AG-KGN-2016/Dokumente
|
2016-11-28/aufgabe-addierer.py
|
Python
|
gpl-3.0
| 587
|
/*
* Sequence.java
*
* BEAST: Bayesian Evolutionary Analysis by Sampling Trees
* Copyright (C) 2014 BEAST Developers
*
* BEAST 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.
*
* BEAST 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 BEAST. If not, see <http://www.gnu.org/licenses/>.
*/
package beast.evolution.sequence;
import beast.evolution.datatype.AminoAcids;
import beast.evolution.datatype.DataType;
import beast.evolution.datatype.Nucleotides;
import beast.evolution.datatype.TwoStates;
import beast.evolution.util.Taxon;
import beast.util.Attributable;
import beast.util.Identifiable;
import beast.xml.AbstractXMLObjectParser;
import beast.xml.ElementRule;
import beast.xml.XMLObject;
import beast.xml.XMLObjectParser;
import beast.xml.XMLParseException;
import beast.xml.XMLSyntaxRule;
import java.util.Iterator;
import java.util.StringTokenizer;
/**
* Class for storing a molecular sequence.
*
* @author Alexei Drummond
* @author Andrew Rambaut
* @version $Id: Sequence.java,v 1.35 2005/05/25 09:35:28 rambaut Exp $
*/
public class Sequence implements Identifiable, Attributable {
/**
* Empty constructor.
*/
public Sequence() {
sequenceString = new StringBuffer();
}
/**
* Constructor with initial sequence string.
*
* @param sequence a string representing the sequence
*/
public Sequence(String sequence) {
sequenceString = new StringBuffer();
setSequenceString(sequence);
}
/**
* Clone constructor
*
* @param sequence the sequence to clone
*/
public Sequence(Sequence sequence) {
// should clone taxon as well!
this(sequence.getTaxon(), sequence.getSequenceString());
}
/**
* Constructor with taxon and sequence string.
*
* @param taxon the sequence's taxon
* @param sequence the sequence's symbol string
*/
public Sequence(Taxon taxon, String sequence) {
sequenceString = new StringBuffer();
setTaxon(taxon);
setSequenceString(sequence);
}
/**
* @return the DataType of the sequences.
*/
public DataType getDataType() {
return dataType;
}
/**
* @return the length of the sequences.
*/
public int getLength() {
return sequenceString.length();
}
/**
* @return a String containing the sequences.
*/
public String getSequenceString() {
return sequenceString.toString();
}
/**
* @return a char containing the state at index.
*/
public char getChar(int index) {
return sequenceString.charAt(index);
}
/**
* @return the state at site index.
*/
public int getState(int index) {
return dataType.getState(sequenceString.charAt(index));
}
/**
*/
public final void setState(int index, int state) {
sequenceString.setCharAt(index, dataType.getChar(state));
}
/**
* Characters are copied from the sequences into the destination character array dst.
*/
public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) {
sequenceString.getChars(srcBegin, srcEnd, dst, dstBegin);
}
/**
* Set the DataType of the sequences.
*/
public void setDataType(DataType dataType) {
this.dataType = dataType;
}
/**
* Set the DataType of the sequences.
*/
public DataType guessDataType() {
return DataType.guessDataType(sequenceString.toString());
}
/**
* Set the sequences using a string.
*/
public void setSequenceString(String sequence) {
sequenceString.setLength(0);
sequenceString.append(sequence.toUpperCase());
}
/**
* Append a string to the sequences.
*/
public void appendSequenceString(String sequence) {
sequenceString.append(sequence);
}
/**
* Insert a string into the sequences.
*/
public void insertSequenceString(int offset, String sequence) {
sequenceString.insert(offset, sequence);
}
/**
* Sets a taxon for this sequences.
*
* @param taxon the taxon.
*/
public void setTaxon(Taxon taxon) {
this.taxon = taxon;
}
/**
* @return the taxon for this sequences.
*/
public Taxon getTaxon() {
return taxon;
}
// **************************************************************
// Attributable IMPLEMENTATION
// **************************************************************
private Attributable.AttributeHelper attributes = null;
/**
* Sets an named attribute for this object.
*
* @param name the name of the attribute.
* @param value the new value of the attribute.
*/
public void setAttribute(String name, Object value) {
if (attributes == null)
attributes = new Attributable.AttributeHelper();
attributes.setAttribute(name, value);
}
/**
* @param name the name of the attribute of interest.
* @return an object representing the named attributed for this object.
*/
public Object getAttribute(String name) {
if (attributes == null)
return null;
else
return attributes.getAttribute(name);
}
/**
* @return an iterator of the attributes that this object has.
*/
public Iterator<String> getAttributeNames() {
if (attributes == null)
return null;
else
return attributes.getAttributeNames();
}
// **************************************************************
// Identifiable IMPLEMENTATION
// **************************************************************
protected String id = null;
/**
* @return the id.
*/
public String getId() {
return id;
}
/**
* Sets the id.
*/
public void setId(String id) {
this.id = id;
}
// **************************************************************
// INSTANCE VARIABLES
// **************************************************************
protected Taxon taxon = null;
protected StringBuffer sequenceString = null;
protected DataType dataType = null;
public static final XMLObjectParser<Sequence> PARSER = new AbstractXMLObjectParser<Sequence>() {
public static final String SEQUENCE = "sequence";
public String getParserName() { return SEQUENCE; }
/**
* @return a sequence object based on the XML element it was passed.
*/
public Sequence parseXMLObject(XMLObject xo) throws XMLParseException {
Sequence sequence = new Sequence();
Taxon taxon = (Taxon)xo.getChild(Taxon.class);
DataType dataType = null;
if (xo.hasAttribute(DataType.DATA_TYPE)) {
String dataTypeStr = xo.getStringAttribute(DataType.DATA_TYPE);
if (dataTypeStr.equals(Nucleotides.DESCRIPTION)) {
dataType = Nucleotides.INSTANCE;
} else if (dataTypeStr.equals(AminoAcids.DESCRIPTION)) {
dataType = AminoAcids.INSTANCE;
// } else if (dataTypeStr.equals(Codons.DESCRIPTION)) {
// dataType = Codons.UNIVERSAL;
} else if (dataTypeStr.equals(TwoStates.DESCRIPTION)) {
dataType = TwoStates.INSTANCE;
}
}
StringBuffer seqBuf = new StringBuffer();
for (int i = 0; i < xo.getChildCount(); i++) {
Object child = xo.getChild(i);
if (child instanceof String) {
StringTokenizer st = new StringTokenizer((String)child);
while (st.hasMoreTokens()) {
seqBuf.append(st.nextToken());
}
}
}
// We really need to filter the input string to check for illegal characters.
// Perhaps sequence.setSequenceString could throw an exception if any characters
// don't fit the dataType.
String sequenceString = seqBuf.toString();
if (sequenceString.length() == 0) {
throw new XMLParseException("Sequence data missing from sequence element!");
}
if (dataType != null) {
sequence.setDataType(dataType);
}
sequence.setSequenceString(sequenceString);
sequence.setTaxon(taxon);
return sequence;
}
public String getParserDescription() {
return "A biomolecular sequence.";
}
public Class getReturnType() { return Sequence.class; }
public XMLSyntaxRule[] getSyntaxRules() { return rules; }
private XMLSyntaxRule[] rules = new XMLSyntaxRule[] {
new ElementRule(Taxon.class),
new ElementRule(String.class, "A character string representing the aligned molecular sequence", "ACGACTAGCATCGAGCTTCG--GATAGCATGC")
};
};
}
|
armanbilge/B3
|
src/beast/evolution/sequence/Sequence.java
|
Java
|
gpl-3.0
| 9,555
|
using InsuranceSystem.BLL.DTO.Catalogs;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace InsuranceSystem.BLL.Interfaces.Catalogs
{
public interface IAddressService : IService<AddressDTO>
{
Task<List<AddressDTO>> GetByFirstLineAsync(string firstLine);
Task<List<AddressDTO>> GetBySecondLineAsync(string secondAddress);
Task<List<AddressDTO>> GetByCountyAsync(string county);
Task<List<AddressDTO>> GetByCityAsync(string city);
Task<List<AddressDTO>> GetByStateAsync(string state);
Task<List<AddressDTO>> GetByZipAsync(string zip);
Task<List<AddressDTO>> GetByCountryAsync(string country);
}
}
|
mishakos/InsuranceSystem.Library
|
InsuranceSystem.BLL/Interfaces/Catalogs/IAddressService.cs
|
C#
|
gpl-3.0
| 689
|
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>Kyoto Cabinet: File Members</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.3 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">Kyoto Cabinet</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li class="current"><a href="globals.html"><span>File Members</span></a></li>
</ul>
</div>
<div id="navrow3" class="tabs2">
<ul class="tablist">
<li><a href="globals.html"><span>All</span></a></li>
<li><a href="globals_func.html"><span>Functions</span></a></li>
<li><a href="globals_vars.html"><span>Variables</span></a></li>
<li><a href="globals_type.html"><span>Typedefs</span></a></li>
<li><a href="globals_eval.html"><span>Enumerator</span></a></li>
<li class="current"><a href="globals_defs.html"><span>Defines</span></a></li>
</ul>
</div>
</div>
<div class="contents">
 <ul>
<li>__KCFUNC__
: <a class="el" href="kccommon_8h.html#a9b46a1fd9496b7187580d5dc80efe5ef">kccommon.h</a>
</li>
<li>__STDC_LIMIT_MACROS
: <a class="el" href="kclangc_8h.html#aeb7e7a856ab7a794b05b6b63ef36ea3e">kclangc.h</a>
</li>
<li>_assert_
: <a class="el" href="kccommon_8h.html#a005970c3b0a18effac75150706e288ce">kccommon.h</a>
</li>
<li>_KCCODELINE_
: <a class="el" href="kccommon_8h.html#a26fb24eb99b893101d4fa76ecfde7745">kccommon.h</a>
</li>
<li>_testyield_
: <a class="el" href="kccommon_8h.html#ae237e2868a3aa24d5d7c49cb5cd52b54">kccommon.h</a>
</li>
<li>_yield_
: <a class="el" href="kccommon_8h.html#a531af164a6cf738617301635151b2a03">kccommon.h</a>
</li>
<li>KCDBSSMAGICDATA
: <a class="el" href="kcdb_8h.html#a138202f6a5dc6f9d9d9de115e252109b">kcdb.h</a>
</li>
<li>KCDDBATRANPREFIX
: <a class="el" href="kcdirdb_8h.html#af04ba50862579cdf88c6e79ebe3a1240">kcdirdb.h</a>
</li>
<li>KCDDBCHKSUMSEED
: <a class="el" href="kcdirdb_8h.html#afbe30419a413a579c7dcfdc9ec004c5b">kcdirdb.h</a>
</li>
<li>KCDDBMAGICEOF
: <a class="el" href="kcdirdb_8h.html#a59dcb061a20bb77e30e0e96d36fe2a51">kcdirdb.h</a>
</li>
<li>KCDDBMAGICFILE
: <a class="el" href="kcdirdb_8h.html#a1b7ec59ea8f757c27bd3b95a0d2c8edd">kcdirdb.h</a>
</li>
<li>KCDDBMETAFILE
: <a class="el" href="kcdirdb_8h.html#a984aed13c425e88ac144534f2b9ef148">kcdirdb.h</a>
</li>
<li>KCDDBOPAQUEFILE
: <a class="el" href="kcdirdb_8h.html#a91c2e57af9a7aa6af1687ca44441576e">kcdirdb.h</a>
</li>
<li>KCDDBTMPPATHEXT
: <a class="el" href="kcdirdb_8h.html#a38acb7049d48f4b37d2d5a4d4a22b6e7">kcdirdb.h</a>
</li>
<li>KCDDBWALPATHEXT
: <a class="el" href="kcdirdb_8h.html#a6d8417b9a3638da98249f63852f8d3c8">kcdirdb.h</a>
</li>
<li>KCHDBCHKSUMSEED
: <a class="el" href="kchashdb_8h.html#aac059bd6139ae7e7dde3d1ee61488463">kchashdb.h</a>
</li>
<li>KCHDBMAGICDATA
: <a class="el" href="kchashdb_8h.html#aa7098a544e8653eab6e2e5667acc5bec">kchashdb.h</a>
</li>
<li>KCHDBTMPPATHEXT
: <a class="el" href="kchashdb_8h.html#aff8dea53e1012e153718041a93f6819b">kchashdb.h</a>
</li>
<li>KCPDBMETAKEY
: <a class="el" href="kcplantdb_8h.html#a6c6fcc9b66a37ab0567d37efe8df21cf">kcplantdb.h</a>
</li>
<li>KCPDBTMPPATHEXT
: <a class="el" href="kcplantdb_8h.html#abf4ed00eb8d98b0e2d7de4d154c1a090">kcplantdb.h</a>
</li>
<li>KCPDRECBUFSIZ
: <a class="el" href="kcplantdb_8h.html#a456c4709e5188d00ff07bf79db1be235">kcplantdb.h</a>
</li>
</ul>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Thu Dec 15 2011 23:27:26 for Kyoto Cabinet by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address>
</body>
</html>
|
xushiwei/kyotocabinet
|
doc/api/globals_defs.html
|
HTML
|
gpl-3.0
| 4,457
|
/**
* Marlin 3D Printer Firmware
* Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* Configuration_adv.h
*
* Advanced settings.
* Only change these if you know exactly what you're doing.
* Some of these settings can damage your printer if improperly set!
*
* Basic settings can be found in Configuration.h
*
*/
#define CONFIGURATION_ADV_H_VERSION 020000
// @section temperature
//===========================================================================
//=============================Thermal Settings ============================
//===========================================================================
//
// Hephestos 2 24V heated bed upgrade kit.
// https://store.bq.com/en/heated-bed-kit-hephestos2
//
//#define HEPHESTOS2_HEATED_BED_KIT
#if ENABLED(HEPHESTOS2_HEATED_BED_KIT)
#undef TEMP_SENSOR_BED
#define TEMP_SENSOR_BED 70
#define HEATER_BED_INVERTING true
#endif
#if DISABLED(PIDTEMPBED)
#define BED_CHECK_INTERVAL 5000 // ms between checks in bang-bang control
#if ENABLED(BED_LIMIT_SWITCHING)
#define BED_HYSTERESIS 2 // Only disable heating if T>target+BED_HYSTERESIS and enable heating if T>target-BED_HYSTERESIS
#endif
#endif
/**
* Thermal Protection provides additional protection to your printer from damage
* and fire. Marlin always includes safe min and max temperature ranges which
* protect against a broken or disconnected thermistor wire.
*
* The issue: If a thermistor falls out, it will report the much lower
* temperature of the air in the room, and the the firmware will keep
* the heater on.
*
* The solution: Once the temperature reaches the target, start observing.
* If the temperature stays too far below the target (hysteresis) for too
* long (period), the firmware will halt the machine as a safety precaution.
*
* If you get false positives for "Thermal Runaway", increase
* THERMAL_PROTECTION_HYSTERESIS and/or THERMAL_PROTECTION_PERIOD
*/
#if ENABLED(THERMAL_PROTECTION_HOTENDS)
#define THERMAL_PROTECTION_PERIOD 40 // Seconds
#define THERMAL_PROTECTION_HYSTERESIS 4 // Degrees Celsius
//#define ADAPTIVE_FAN_SLOWING // Slow part cooling fan if temperature drops
#if ENABLED(ADAPTIVE_FAN_SLOWING) && ENABLED(PIDTEMP)
//#define NO_FAN_SLOWING_IN_PID_TUNING // Don't slow fan speed during M303
#endif
/**
* Whenever an M104, M109, or M303 increases the target temperature, the
* firmware will wait for the WATCH_TEMP_PERIOD to expire. If the temperature
* hasn't increased by WATCH_TEMP_INCREASE degrees, the machine is halted and
* requires a hard reset. This test restarts with any M104/M109/M303, but only
* if the current temperature is far enough below the target for a reliable
* test.
*
* If you get false positives for "Heating failed", increase WATCH_TEMP_PERIOD
* and/or decrease WATCH_TEMP_INCREASE. WATCH_TEMP_INCREASE should not be set
* below 2.
*/
#define WATCH_TEMP_PERIOD 20 // Seconds
#define WATCH_TEMP_INCREASE 2 // Degrees Celsius
#endif
/**
* Thermal Protection parameters for the bed are just as above for hotends.
*/
#if ENABLED(THERMAL_PROTECTION_BED)
#define THERMAL_PROTECTION_BED_PERIOD 20 // Seconds
#define THERMAL_PROTECTION_BED_HYSTERESIS 2 // Degrees Celsius
/**
* As described above, except for the bed (M140/M190/M303).
*/
#define WATCH_BED_TEMP_PERIOD 60 // Seconds
#define WATCH_BED_TEMP_INCREASE 2 // Degrees Celsius
#endif
/**
* Thermal Protection parameters for the heated chamber.
*/
#if ENABLED(THERMAL_PROTECTION_CHAMBER)
#define THERMAL_PROTECTION_CHAMBER_PERIOD 20 // Seconds
#define THERMAL_PROTECTION_CHAMBER_HYSTERESIS 2 // Degrees Celsius
/**
* Heated chamber watch settings (M141/M191).
*/
#define WATCH_CHAMBER_TEMP_PERIOD 60 // Seconds
#define WATCH_CHAMBER_TEMP_INCREASE 2 // Degrees Celsius
#endif
#if ENABLED(PIDTEMP)
// this adds an experimental additional term to the heating power, proportional to the extrusion speed.
// if Kc is chosen well, the additional required power due to increased melting should be compensated.
//#define PID_EXTRUSION_SCALING
#if ENABLED(PID_EXTRUSION_SCALING)
#define DEFAULT_Kc (100) //heating power=Kc*(e_speed)
#define LPQ_MAX_LEN 50
#endif
#endif
/**
* Automatic Temperature:
* The hotend target temperature is calculated by all the buffered lines of gcode.
* The maximum buffered steps/sec of the extruder motor is called "se".
* Start autotemp mode with M109 S<mintemp> B<maxtemp> F<factor>
* The target temperature is set to mintemp+factor*se[steps/sec] and is limited by
* mintemp and maxtemp. Turn this off by executing M109 without F*
* Also, if the temperature is set to a value below mintemp, it will not be changed by autotemp.
* On an Ultimaker, some initial testing worked with M109 S215 B260 F1 in the start.gcode
*/
#define AUTOTEMP
#if ENABLED(AUTOTEMP)
#define AUTOTEMP_OLDWEIGHT 0.98
#endif
// Show extra position information in M114
//#define M114_DETAIL
// Show Temperature ADC value
// Enable for M105 to include ADC values read from temperature sensors.
//#define SHOW_TEMP_ADC_VALUES
/**
* High Temperature Thermistor Support
*
* Thermistors able to support high temperature tend to have a hard time getting
* good readings at room and lower temperatures. This means HEATER_X_RAW_LO_TEMP
* will probably be caught when the heating element first turns on during the
* preheating process, which will trigger a min_temp_error as a safety measure
* and force stop everything.
* To circumvent this limitation, we allow for a preheat time (during which,
* min_temp_error won't be triggered) and add a min_temp buffer to handle
* aberrant readings.
*
* If you want to enable this feature for your hotend thermistor(s)
* uncomment and set values > 0 in the constants below
*/
// The number of consecutive low temperature errors that can occur
// before a min_temp_error is triggered. (Shouldn't be more than 10.)
//#define MAX_CONSECUTIVE_LOW_TEMPERATURE_ERROR_ALLOWED 0
// The number of milliseconds a hotend will preheat before starting to check
// the temperature. This value should NOT be set to the time it takes the
// hot end to reach the target temperature, but the time it takes to reach
// the minimum temperature your thermistor can read. The lower the better/safer.
// This shouldn't need to be more than 30 seconds (30000)
//#define MILLISECONDS_PREHEAT_TIME 0
// @section extruder
// Extruder runout prevention.
// If the machine is idle and the temperature over MINTEMP
// then extrude some filament every couple of SECONDS.
//#define EXTRUDER_RUNOUT_PREVENT
#if ENABLED(EXTRUDER_RUNOUT_PREVENT)
#define EXTRUDER_RUNOUT_MINTEMP 190
#define EXTRUDER_RUNOUT_SECONDS 30
#define EXTRUDER_RUNOUT_SPEED 1500 // (mm/m)
#define EXTRUDER_RUNOUT_EXTRUDE 5 // (mm)
#endif
// @section temperature
// Calibration for AD595 / AD8495 sensor to adjust temperature measurements.
// The final temperature is calculated as (measuredTemp * GAIN) + OFFSET.
#define TEMP_SENSOR_AD595_OFFSET 0.0
#define TEMP_SENSOR_AD595_GAIN 1.0
#define TEMP_SENSOR_AD8495_OFFSET 0.0
#define TEMP_SENSOR_AD8495_GAIN 1.0
/**
* Controller Fan
* To cool down the stepper drivers and MOSFETs.
*
* The fan will turn on automatically whenever any stepper is enabled
* and turn off after a set period after all steppers are turned off.
*/
//#define USE_CONTROLLER_FAN
#if ENABLED(USE_CONTROLLER_FAN)
//#define CONTROLLER_FAN_PIN -1 // Set a custom pin for the controller fan
#define CONTROLLERFAN_SECS 60 // Duration in seconds for the fan to run after all motors are disabled
#define CONTROLLERFAN_SPEED 255 // 255 == full speed
#endif
// When first starting the main fan, run it at full speed for the
// given number of milliseconds. This gets the fan spinning reliably
// before setting a PWM value. (Does not work with software PWM for fan on Sanguinololu)
//#define FAN_KICKSTART_TIME 100
/**
* PWM Fan Scaling
*
* Define the min/max speeds for PWM fans (as set with M106).
*
* With these options the M106 0-255 value range is scaled to a subset
* to ensure that the fan has enough power to spin, or to run lower
* current fans with higher current. (e.g., 5V/12V fans with 12V/24V)
* Value 0 always turns off the fan.
*
* Define one or both of these to override the default 0-255 range.
*/
//#define FAN_MIN_PWM 50
//#define FAN_MAX_PWM 128
/**
* FAST PWM FAN Settings
*
* Use to change the FAST FAN PWM frequency (if enabled in Configuration.h)
* Combinations of PWM Modes, prescale values and TOP resolutions are used internally to produce a
* frequency as close as possible to the desired frequency.
*
* FAST_PWM_FAN_FREQUENCY [undefined by default]
* Set this to your desired frequency.
* If left undefined this defaults to F = F_CPU/(2*255*1)
* ie F = 31.4 Khz on 16 MHz microcontrollers or F = 39.2 KHz on 20 MHz microcontrollers
* These defaults are the same as with the old FAST_PWM_FAN implementation - no migration is required
* NOTE: Setting very low frequencies (< 10 Hz) may result in unexpected timer behaviour.
*
* USE_OCR2A_AS_TOP [undefined by default]
* Boards that use TIMER2 for PWM have limitations resulting in only a few possible frequencies on TIMER2:
* 16MHz MCUs: [62.5KHz, 31.4KHz (default), 7.8KHz, 3.92KHz, 1.95KHz, 977Hz, 488Hz, 244Hz, 60Hz, 122Hz, 30Hz]
* 20MHz MCUs: [78.1KHz, 39.2KHz (default), 9.77KHz, 4.9KHz, 2.44KHz, 1.22KHz, 610Hz, 305Hz, 153Hz, 76Hz, 38Hz]
* A greater range can be achieved by enabling USE_OCR2A_AS_TOP. But note that this option blocks the use of
* PWM on pin OC2A. Only use this option if you don't need PWM on 0C2A. (Check your schematic.)
* USE_OCR2A_AS_TOP sacrifices duty cycle control resolution to achieve this broader range of frequencies.
*/
#if ENABLED(FAST_PWM_FAN)
//#define FAST_PWM_FAN_FREQUENCY 31400
//#define USE_OCR2A_AS_TOP
#endif
// @section extruder
/**
* Extruder cooling fans
*
* Extruder auto fans automatically turn on when their extruders'
* temperatures go above EXTRUDER_AUTO_FAN_TEMPERATURE.
*
* Your board's pins file specifies the recommended pins. Override those here
* or set to -1 to disable completely.
*
* Multiple extruders can be assigned to the same pin in which case
* the fan will turn on when any selected extruder is above the threshold.
*/
#define E0_AUTO_FAN_PIN -1
#define E1_AUTO_FAN_PIN -1
#define E2_AUTO_FAN_PIN -1
#define E3_AUTO_FAN_PIN -1
#define E4_AUTO_FAN_PIN -1
#define E5_AUTO_FAN_PIN -1
#define CHAMBER_AUTO_FAN_PIN -1
#define EXTRUDER_AUTO_FAN_TEMPERATURE 50
#define EXTRUDER_AUTO_FAN_SPEED 255 // 255 == full speed
/**
* Part-Cooling Fan Multiplexer
*
* This feature allows you to digitally multiplex the fan output.
* The multiplexer is automatically switched at tool-change.
* Set FANMUX[012]_PINs below for up to 2, 4, or 8 multiplexed fans.
*/
#define FANMUX0_PIN -1
#define FANMUX1_PIN -1
#define FANMUX2_PIN -1
/**
* M355 Case Light on-off / brightness
*/
//#define CASE_LIGHT_ENABLE
#if ENABLED(CASE_LIGHT_ENABLE)
//#define CASE_LIGHT_PIN 4 // Override the default pin if needed
#define INVERT_CASE_LIGHT false // Set true if Case Light is ON when pin is LOW
#define CASE_LIGHT_DEFAULT_ON true // Set default power-up state on
#define CASE_LIGHT_DEFAULT_BRIGHTNESS 105 // Set default power-up brightness (0-255, requires PWM pin)
//#define MENU_ITEM_CASE_LIGHT // Add a Case Light option to the LCD main menu
//#define CASE_LIGHT_USE_NEOPIXEL // Use Neopixel LED as case light, requires NEOPIXEL_LED.
#if ENABLED(CASE_LIGHT_USE_NEOPIXEL)
#define CASE_LIGHT_NEOPIXEL_COLOR { 255, 255, 255, 255 } // { Red, Green, Blue, White }
#endif
#endif
//===========================================================================
//============================ Mechanical Settings ==========================
//===========================================================================
// @section homing
// If you want endstops to stay on (by default) even when not homing
// enable this option. Override at any time with M120, M121.
//#define ENDSTOPS_ALWAYS_ON_DEFAULT
// @section extras
//#define Z_LATE_ENABLE // Enable Z the last moment. Needed if your Z driver overheats.
// Employ an external closed loop controller. Override pins here if needed.
//#define EXTERNAL_CLOSED_LOOP_CONTROLLER
#if ENABLED(EXTERNAL_CLOSED_LOOP_CONTROLLER)
//#define CLOSED_LOOP_ENABLE_PIN -1
//#define CLOSED_LOOP_MOVE_COMPLETE_PIN -1
#endif
/**
* Dual Steppers / Dual Endstops
*
* This section will allow you to use extra E drivers to drive a second motor for X, Y, or Z axes.
*
* For example, set X_DUAL_STEPPER_DRIVERS setting to use a second motor. If the motors need to
* spin in opposite directions set INVERT_X2_VS_X_DIR. If the second motor needs its own endstop
* set X_DUAL_ENDSTOPS. This can adjust for "racking." Use X2_USE_ENDSTOP to set the endstop plug
* that should be used for the second endstop. Extra endstops will appear in the output of 'M119'.
*
* Use X_DUAL_ENDSTOP_ADJUSTMENT to adjust for mechanical imperfection. After homing both motors
* this offset is applied to the X2 motor. To find the offset home the X axis, and measure the error
* in X2. Dual endstop offsets can be set at runtime with 'M666 X<offset> Y<offset> Z<offset>'.
*/
//#define X_DUAL_STEPPER_DRIVERS
#if ENABLED(X_DUAL_STEPPER_DRIVERS)
#define INVERT_X2_VS_X_DIR true // Set 'true' if X motors should rotate in opposite directions
//#define X_DUAL_ENDSTOPS
#if ENABLED(X_DUAL_ENDSTOPS)
#define X2_USE_ENDSTOP _XMAX_
#define X_DUAL_ENDSTOPS_ADJUSTMENT 0
#endif
#endif
//#define Y_DUAL_STEPPER_DRIVERS
#if ENABLED(Y_DUAL_STEPPER_DRIVERS)
#define INVERT_Y2_VS_Y_DIR true // Set 'true' if Y motors should rotate in opposite directions
//#define Y_DUAL_ENDSTOPS
#if ENABLED(Y_DUAL_ENDSTOPS)
#define Y2_USE_ENDSTOP _YMAX_
#define Y_DUAL_ENDSTOPS_ADJUSTMENT 0
#endif
#endif
//#define Z_DUAL_STEPPER_DRIVERS
#if ENABLED(Z_DUAL_STEPPER_DRIVERS)
//#define Z_DUAL_ENDSTOPS
#if ENABLED(Z_DUAL_ENDSTOPS)
#define Z2_USE_ENDSTOP _XMAX_
#define Z_DUAL_ENDSTOPS_ADJUSTMENT 0
#endif
#endif
//#define Z_TRIPLE_STEPPER_DRIVERS
#if ENABLED(Z_TRIPLE_STEPPER_DRIVERS)
//#define Z_TRIPLE_ENDSTOPS
#if ENABLED(Z_TRIPLE_ENDSTOPS)
#define Z2_USE_ENDSTOP _XMAX_
#define Z3_USE_ENDSTOP _YMAX_
#define Z_TRIPLE_ENDSTOPS_ADJUSTMENT2 0
#define Z_TRIPLE_ENDSTOPS_ADJUSTMENT3 0
#endif
#endif
/**
* Dual X Carriage
*
* This setup has two X carriages that can move independently, each with its own hotend.
* The carriages can be used to print an object with two colors or materials, or in
* "duplication mode" it can print two identical or X-mirrored objects simultaneously.
* The inactive carriage is parked automatically to prevent oozing.
* X1 is the left carriage, X2 the right. They park and home at opposite ends of the X axis.
* By default the X2 stepper is assigned to the first unused E plug on the board.
*/
//#define DUAL_X_CARRIAGE
#if ENABLED(DUAL_X_CARRIAGE)
#define X1_MIN_POS X_MIN_POS // set minimum to ensure first x-carriage doesn't hit the parked second X-carriage
#define X1_MAX_POS X_BED_SIZE // set maximum to ensure first x-carriage doesn't hit the parked second X-carriage
#define X2_MIN_POS 80 // set minimum to ensure second x-carriage doesn't hit the parked first X-carriage
#define X2_MAX_POS 353 // set maximum to the distance between toolheads when both heads are homed
#define X2_HOME_DIR 1 // the second X-carriage always homes to the maximum endstop position
#define X2_HOME_POS X2_MAX_POS // default home position is the maximum carriage position
// However: In this mode the HOTEND_OFFSET_X value for the second extruder provides a software
// override for X2_HOME_POS. This also allow recalibration of the distance between the two endstops
// without modifying the firmware (through the "M218 T1 X???" command).
// Remember: you should set the second extruder x-offset to 0 in your slicer.
// There are a few selectable movement modes for dual x-carriages using M605 S<mode>
// Mode 0 (DXC_FULL_CONTROL_MODE): Full control. The slicer has full control over both x-carriages and can achieve optimal travel results
// as long as it supports dual x-carriages. (M605 S0)
// Mode 1 (DXC_AUTO_PARK_MODE) : Auto-park mode. The firmware will automatically park and unpark the x-carriages on tool changes so
// that additional slicer support is not required. (M605 S1)
// Mode 2 (DXC_DUPLICATION_MODE) : Duplication mode. The firmware will transparently make the second x-carriage and extruder copy all
// actions of the first x-carriage. This allows the printer to print 2 arbitrary items at
// once. (2nd extruder x offset and temp offset are set using: M605 S2 [Xnnn] [Rmmm])
// This is the default power-up mode which can be later using M605.
#define DEFAULT_DUAL_X_CARRIAGE_MODE DXC_FULL_CONTROL_MODE
// Default x offset in duplication mode (typically set to half print bed width)
#define DEFAULT_DUPLICATION_X_OFFSET 100
#endif // DUAL_X_CARRIAGE
// Activate a solenoid on the active extruder with M380. Disable all with M381.
// Define SOL0_PIN, SOL1_PIN, etc., for each extruder that has a solenoid.
//#define EXT_SOLENOID
// @section homing
// Homing hits each endstop, retracts by these distances, then does a slower bump.
#define X_HOME_BUMP_MM 5
#define Y_HOME_BUMP_MM 5
#define Z_HOME_BUMP_MM 2
#define HOMING_BUMP_DIVISOR { 2, 2, 4 } // Re-Bump Speed Divisor (Divides the Homing Feedrate)
#define QUICK_HOME // If homing includes X and Y, do a diagonal move initially
// When G28 is called, this option will make Y home before X
//#define HOME_Y_BEFORE_X
// Enable this if X or Y can't home without homing the other axis first.
//#define CODEPENDENT_XY_HOMING
/**
* Z Steppers Auto-Alignment
* Add the G34 command to align multiple Z steppers using a bed probe.
*/
//#define Z_STEPPER_AUTO_ALIGN
#if ENABLED(Z_STEPPER_AUTO_ALIGN)
// Define probe X and Y positions for Z1, Z2 [, Z3]
#define Z_STEPPER_ALIGN_X { 10, 150, 290 }
#define Z_STEPPER_ALIGN_Y { 290, 10, 290 }
// Set number of iterations to align
#define Z_STEPPER_ALIGN_ITERATIONS 3
// Enable to restore leveling setup after operation
#define RESTORE_LEVELING_AFTER_G34
// Use the amplification factor to de-/increase correction step.
// In case the stepper (spindle) position is further out than the test point
// Use a value > 1. NOTE: This may cause instability
#define Z_STEPPER_ALIGN_AMP 1.0
// Stop criterion. If the accuracy is better than this stop iterating early
#define Z_STEPPER_ALIGN_ACC 0.02
#endif
// @section machine
#define AXIS_RELATIVE_MODES {false, false, false, false}
// Allow duplication mode with a basic dual-nozzle extruder
//#define DUAL_NOZZLE_DUPLICATION_MODE
// By default pololu step drivers require an active high signal. However, some high power drivers require an active low signal as step.
#define INVERT_X_STEP_PIN false
#define INVERT_Y_STEP_PIN false
#define INVERT_Z_STEP_PIN false
#define INVERT_E_STEP_PIN false
// Default stepper release if idle. Set to 0 to deactivate.
// Steppers will shut down DEFAULT_STEPPER_DEACTIVE_TIME seconds after the last move when DISABLE_INACTIVE_? is true.
// Time can be set by M18 and M84.
#define DEFAULT_STEPPER_DEACTIVE_TIME 120
#define DISABLE_INACTIVE_X true
#define DISABLE_INACTIVE_Y true
#define DISABLE_INACTIVE_Z true // set to false if the nozzle will fall down on your printed part when print has finished.
#define DISABLE_INACTIVE_E true
#define DEFAULT_MINIMUMFEEDRATE 0.0 // minimum feedrate
#define DEFAULT_MINTRAVELFEEDRATE 0.0
//#define HOME_AFTER_DEACTIVATE // Require rehoming after steppers are deactivated
// @section lcd
#if ENABLED(ULTIPANEL)
#define MANUAL_FEEDRATE {50*60, 50*60, 4*60, 60} // Feedrates for manual moves along X, Y, Z, E from panel
#define MANUAL_E_MOVES_RELATIVE // Show LCD extruder moves as relative rather than absolute positions
#define ULTIPANEL_FEEDMULTIPLY // Comment to disable setting feedrate multiplier via encoder
#endif
// @section extras
// minimum time in microseconds that a movement needs to take if the buffer is emptied.
#define DEFAULT_MINSEGMENTTIME 20000
// If defined the movements slow down when the look ahead buffer is only half full
#define SLOWDOWN
// Frequency limit
// See nophead's blog for more info
// Not working O
//#define XY_FREQUENCY_LIMIT 15
// Minimum planner junction speed. Sets the default minimum speed the planner plans for at the end
// of the buffer and all stops. This should not be much greater than zero and should only be changed
// if unwanted behavior is observed on a user's machine when running at very slow speeds.
#define MINIMUM_PLANNER_SPEED 0.05 // (mm/s)
//
// Backlash Compensation
// Adds extra movement to axes on direction-changes to account for backlash.
//
//#define BACKLASH_COMPENSATION
#if ENABLED(BACKLASH_COMPENSATION)
// Define values for backlash distance and correction.
// If BACKLASH_GCODE is enabled these values are the defaults.
#define BACKLASH_DISTANCE_MM { 0, 0, 0 } // (mm)
#define BACKLASH_CORRECTION 0.0 // 0.0 = no correction; 1.0 = full correction
// Set BACKLASH_SMOOTHING_MM to spread backlash correction over multiple segments
// to reduce print artifacts. (Enabling this is costly in memory and computation!)
//#define BACKLASH_SMOOTHING_MM 3 // (mm)
// Add runtime configuration and tuning of backlash values (M425)
//#define BACKLASH_GCODE
#if ENABLED(BACKLASH_GCODE)
// Measure the Z backlash when probing (G29) and set with "M425 Z"
#define MEASURE_BACKLASH_WHEN_PROBING
#if ENABLED(MEASURE_BACKLASH_WHEN_PROBING)
// When measuring, the probe will move up to BACKLASH_MEASUREMENT_LIMIT
// mm away from point of contact in BACKLASH_MEASUREMENT_RESOLUTION
// increments while checking for the contact to be broken.
#define BACKLASH_MEASUREMENT_LIMIT 0.5 // (mm)
#define BACKLASH_MEASUREMENT_RESOLUTION 0.005 // (mm)
#define BACKLASH_MEASUREMENT_FEEDRATE Z_PROBE_SPEED_SLOW // (mm/m)
#endif
#endif
#endif
/**
* Automatic backlash, position and hotend offset calibration
*
* Enable G425 to run automatic calibration using an electrically-
* conductive cube, bolt, or washer mounted on the bed.
*
* G425 uses the probe to touch the top and sides of the calibration object
* on the bed and measures and/or correct positional offsets, axis backlash
* and hotend offsets.
*
* Note: HOTEND_OFFSET and CALIBRATION_OBJECT_CENTER must be set to within
* ±5mm of true values for G425 to succeed.
*/
//#define CALIBRATION_GCODE
#if ENABLED(CALIBRATION_GCODE)
#define CALIBRATION_MEASUREMENT_RESOLUTION 0.01 // mm
#define CALIBRATION_FEEDRATE_SLOW 60 // mm/m
#define CALIBRATION_FEEDRATE_FAST 1200 // mm/m
#define CALIBRATION_FEEDRATE_TRAVEL 3000 // mm/m
// The following parameters refer to the conical section of the nozzle tip.
#define CALIBRATION_NOZZLE_TIP_HEIGHT 1.0 // mm
#define CALIBRATION_NOZZLE_OUTER_DIAMETER 2.0 // mm
// Uncomment to enable reporting (required for "G425 V", but consumes PROGMEM).
//#define CALIBRATION_REPORTING
// The true location and dimension the cube/bolt/washer on the bed.
#define CALIBRATION_OBJECT_CENTER { 264.0, -22.0, -2.0} // mm
#define CALIBRATION_OBJECT_DIMENSIONS { 10.0, 10.0, 10.0} // mm
// Comment out any sides which are unreachable by the probe. For best
// auto-calibration results, all sides must be reachable.
#define CALIBRATION_MEASURE_RIGHT
#define CALIBRATION_MEASURE_FRONT
#define CALIBRATION_MEASURE_LEFT
#define CALIBRATION_MEASURE_BACK
// Probing at the exact top center only works if the center is flat. If
// probing on a screwhead or hollow washer, probe near the edges.
//#define CALIBRATION_MEASURE_AT_TOP_EDGES
// Define pin which is read during calibration
#ifndef CALIBRATION_PIN
#define CALIBRATION_PIN -1 // Override in pins.h or set to -1 to use your Z endstop
#define CALIBRATION_PIN_INVERTING false // set to true to invert the pin
//#define CALIBRATION_PIN_PULLDOWN
#define CALIBRATION_PIN_PULLUP
#endif
#endif
/**
* Adaptive Step Smoothing increases the resolution of multi-axis moves, particularly at step frequencies
* below 1kHz (for AVR) or 10kHz (for ARM), where aliasing between axes in multi-axis moves causes audible
* vibration and surface artifacts. The algorithm adapts to provide the best possible step smoothing at the
* lowest stepping frequencies.
*/
//#define ADAPTIVE_STEP_SMOOTHING
/**
* Custom Microstepping
* Override as-needed for your setup. Up to 3 MS pins are supported.
*/
//#define MICROSTEP1 LOW,LOW,LOW
//#define MICROSTEP2 HIGH,LOW,LOW
//#define MICROSTEP4 LOW,HIGH,LOW
//#define MICROSTEP8 HIGH,HIGH,LOW
//#define MICROSTEP16 LOW,LOW,HIGH
//#define MICROSTEP32 HIGH,LOW,HIGH
// Microstep setting (Only functional when stepper driver microstep pins are connected to MCU.
#define MICROSTEP_MODES { 16, 16, 16, 16, 16, 16 } // [1,2,4,8,16]
/**
* @section stepper motor current
*
* Some boards have a means of setting the stepper motor current via firmware.
*
* The power on motor currents are set by:
* PWM_MOTOR_CURRENT - used by MINIRAMBO & ULTIMAIN_2
* known compatible chips: A4982
* DIGIPOT_MOTOR_CURRENT - used by BQ_ZUM_MEGA_3D, RAMBO & SCOOVO_X9H
* known compatible chips: AD5206
* DAC_MOTOR_CURRENT_DEFAULT - used by PRINTRBOARD_REVF & RIGIDBOARD_V2
* known compatible chips: MCP4728
* DIGIPOT_I2C_MOTOR_CURRENTS - used by 5DPRINT, AZTEEG_X3_PRO, AZTEEG_X5_MINI_WIFI, MIGHTYBOARD_REVE
* known compatible chips: MCP4451, MCP4018
*
* Motor currents can also be set by M907 - M910 and by the LCD.
* M907 - applies to all.
* M908 - BQ_ZUM_MEGA_3D, RAMBO, PRINTRBOARD_REVF, RIGIDBOARD_V2 & SCOOVO_X9H
* M909, M910 & LCD - only PRINTRBOARD_REVF & RIGIDBOARD_V2
*/
//#define PWM_MOTOR_CURRENT { 1300, 1300, 1250 } // Values in milliamps
//#define DIGIPOT_MOTOR_CURRENT { 135,135,135,135,135 } // Values 0-255 (RAMBO 135 = ~0.75A, 185 = ~1A)
//#define DAC_MOTOR_CURRENT_DEFAULT { 70, 80, 90, 80 } // Default drive percent - X, Y, Z, E axis
// Use an I2C based DIGIPOT (e.g., Azteeg X3 Pro)
//#define DIGIPOT_I2C
#if ENABLED(DIGIPOT_I2C) && !defined(DIGIPOT_I2C_ADDRESS_A)
/**
* Common slave addresses:
*
* A (A shifted) B (B shifted) IC
* Smoothie 0x2C (0x58) 0x2D (0x5A) MCP4451
* AZTEEG_X3_PRO 0x2C (0x58) 0x2E (0x5C) MCP4451
* AZTEEG_X5_MINI_WIFI 0x58 0x5C MCP4451
* MIGHTYBOARD_REVE 0x2F (0x5E) MCP4018
*/
#define DIGIPOT_I2C_ADDRESS_A 0x2C // unshifted slave address for first DIGIPOT
#define DIGIPOT_I2C_ADDRESS_B 0x2D // unshifted slave address for second DIGIPOT
#endif
//#define DIGIPOT_MCP4018 // Requires library from https://github.com/stawel/SlowSoftI2CMaster
#define DIGIPOT_I2C_NUM_CHANNELS 8 // 5DPRINT: 4 AZTEEG_X3_PRO: 8 MKS SBASE: 5
// Actual motor currents in Amps. The number of entries must match DIGIPOT_I2C_NUM_CHANNELS.
// These correspond to the physical drivers, so be mindful if the order is changed.
#define DIGIPOT_I2C_MOTOR_CURRENTS { 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0 } // AZTEEG_X3_PRO
//===========================================================================
//=============================Additional Features===========================
//===========================================================================
// @section lcd
// Change values more rapidly when the encoder is rotated faster
#define ENCODER_RATE_MULTIPLIER
#if ENABLED(ENCODER_RATE_MULTIPLIER)
#define ENCODER_10X_STEPS_PER_SEC 30 // (steps/s) Encoder rate for 10x speed
#define ENCODER_100X_STEPS_PER_SEC 80 // (steps/s) Encoder rate for 100x speed
#endif
// Play a beep when the feedrate is changed from the Status Screen
//#define BEEP_ON_FEEDRATE_CHANGE
#if ENABLED(BEEP_ON_FEEDRATE_CHANGE)
#define FEEDRATE_CHANGE_BEEP_DURATION 10
#define FEEDRATE_CHANGE_BEEP_FREQUENCY 440
#endif
// Include a page of printer information in the LCD Main Menu
//#define LCD_INFO_MENU
// Scroll a longer status message into view
#define STATUS_MESSAGE_SCROLLING
// On the Info Screen, display XY with one decimal place when possible
//#define LCD_DECIMAL_SMALL_XY
// The timeout (in ms) to return to the status screen from sub-menus
//#define LCD_TIMEOUT_TO_STATUS 15000
// Add an 'M73' G-code to set the current percentage
//#define LCD_SET_PROGRESS_MANUALLY
#if HAS_CHARACTER_LCD && HAS_PRINT_PROGRESS
//#define LCD_PROGRESS_BAR // Show a progress bar on HD44780 LCDs for SD printing
#if ENABLED(LCD_PROGRESS_BAR)
#define PROGRESS_BAR_BAR_TIME 2000 // (ms) Amount of time to show the bar
#define PROGRESS_BAR_MSG_TIME 3000 // (ms) Amount of time to show the status message
#define PROGRESS_MSG_EXPIRE 0 // (ms) Amount of time to retain the status message (0=forever)
//#define PROGRESS_MSG_ONCE // Show the message for MSG_TIME then clear it
//#define LCD_PROGRESS_BAR_TEST // Add a menu item to test the progress bar
#endif
#endif
/**
* LED Control Menu
* Enable this feature to add LED Control to the LCD menu
*/
//#define LED_CONTROL_MENU
#if ENABLED(LED_CONTROL_MENU)
#define LED_COLOR_PRESETS // Enable the Preset Color menu option
#if ENABLED(LED_COLOR_PRESETS)
#define LED_USER_PRESET_RED 255 // User defined RED value
#define LED_USER_PRESET_GREEN 128 // User defined GREEN value
#define LED_USER_PRESET_BLUE 0 // User defined BLUE value
#define LED_USER_PRESET_WHITE 255 // User defined WHITE value
#define LED_USER_PRESET_BRIGHTNESS 255 // User defined intensity
//#define LED_USER_PRESET_STARTUP // Have the printer display the user preset color on startup
#endif
#endif // LED_CONTROL_MENU
#if ENABLED(SDSUPPORT)
// Some RAMPS and other boards don't detect when an SD card is inserted. You can work
// around this by connecting a push button or single throw switch to the pin defined
// as SD_DETECT_PIN in your board's pins definitions.
// This setting should be disabled unless you are using a push button, pulling the pin to ground.
// Note: This is always disabled for ULTIPANEL (except ELB_FULL_GRAPHIC_CONTROLLER).
#define SD_DETECT_INVERTED
#define SD_FINISHED_STEPPERRELEASE true // Disable steppers when SD Print is finished
#define SD_FINISHED_RELEASECOMMAND "M84 X Y Z E" // You might want to keep the Z enabled so your bed stays in place.
// Reverse SD sort to show "more recent" files first, according to the card's FAT.
// Since the FAT gets out of order with usage, SDCARD_SORT_ALPHA is recommended.
#define SDCARD_RATHERRECENTFIRST
// Add an option in the menu to run all auto#.g files
//#define MENU_ADDAUTOSTART
/**
* Continue after Power-Loss (Creality3D)
*
* Store the current state to the SD Card at the start of each layer
* during SD printing. If the recovery file is found at boot time, present
* an option on the LCD screen to continue the print from the last-known
* point in the file.
*/
//#define POWER_LOSS_RECOVERY
#if ENABLED(POWER_LOSS_RECOVERY)
//#define POWER_LOSS_PIN 44 // Pin to detect power loss
//#define POWER_LOSS_STATE HIGH // State of pin indicating power loss
#endif
/**
* Sort SD file listings in alphabetical order.
*
* With this option enabled, items on SD cards will be sorted
* by name for easier navigation.
*
* By default...
*
* - Use the slowest -but safest- method for sorting.
* - Folders are sorted to the top.
* - The sort key is statically allocated.
* - No added G-code (M34) support.
* - 40 item sorting limit. (Items after the first 40 are unsorted.)
*
* SD sorting uses static allocation (as set by SDSORT_LIMIT), allowing the
* compiler to calculate the worst-case usage and throw an error if the SRAM
* limit is exceeded.
*
* - SDSORT_USES_RAM provides faster sorting via a static directory buffer.
* - SDSORT_USES_STACK does the same, but uses a local stack-based buffer.
* - SDSORT_CACHE_NAMES will retain the sorted file listing in RAM. (Expensive!)
* - SDSORT_DYNAMIC_RAM only uses RAM when the SD menu is visible. (Use with caution!)
*/
#define SDCARD_SORT_ALPHA
// SD Card Sorting options
#if ENABLED(SDCARD_SORT_ALPHA)
#define SDSORT_LIMIT 256 // Maximum number of sorted items (10-256). Costs 27 bytes each.
#define FOLDER_SORTING -1 // -1=above 0=none 1=below
#define SDSORT_GCODE false // Allow turning sorting on/off with LCD and M34 g-code.
#define SDSORT_USES_RAM true // Pre-allocate a static array for faster pre-sorting.
#define SDSORT_USES_STACK false // Prefer the stack for pre-sorting to give back some SRAM. (Negated by next 2 options.)
#define SDSORT_CACHE_NAMES true // Keep sorted items in RAM longer for speedy performance. Most expensive option.
#define SDSORT_DYNAMIC_RAM false // Use dynamic allocation (within SD menus). Least expensive option. Set SDSORT_LIMIT before use!
#define SDSORT_CACHE_VFATS 2 // Maximum number of 13-byte VFAT entries to use for sorting.
// Note: Only affects SCROLL_LONG_FILENAMES with SDSORT_CACHE_NAMES but not SDSORT_DYNAMIC_RAM.
#endif
// This allows hosts to request long names for files and folders with M33
//#define LONG_FILENAME_HOST_SUPPORT
// Enable this option to scroll long filenames in the SD card menu
//#define SCROLL_LONG_FILENAMES
/**
* This option allows you to abort SD printing when any endstop is triggered.
* This feature must be enabled with "M540 S1" or from the LCD menu.
* To have any effect, endstops must be enabled during SD printing.
*/
//#define ABORT_ON_ENDSTOP_HIT_FEATURE_ENABLED
/**
* This option makes it easier to print the same SD Card file again.
* On print completion the LCD Menu will open with the file selected.
* You can just click to start the print, or navigate elsewhere.
*/
//#define SD_REPRINT_LAST_SELECTED_FILE
/**
* Auto-report SdCard status with M27 S<seconds>
*/
//#define AUTO_REPORT_SD_STATUS
/**
* Support for USB thumb drives using an Arduino USB Host Shield or
* equivalent MAX3421E breakout board. The USB thumb drive will appear
* to Marlin as an SD card.
*
* The MAX3421E must be assigned the same pins as the SD card reader, with
* the following pin mapping:
*
* SCLK, MOSI, MISO --> SCLK, MOSI, MISO
* INT --> SD_DETECT_PIN
* SS --> SDSS
*/
//#define USB_FLASH_DRIVE_SUPPORT
#if ENABLED(USB_FLASH_DRIVE_SUPPORT)
#define USB_CS_PIN SDSS
#define USB_INTR_PIN SD_DETECT_PIN
#endif
/**
* When using a bootloader that supports SD-Firmware-Flashing,
* add a menu item to activate SD-FW-Update on the next reboot.
*
* Requires ATMEGA2560 (Arduino Mega)
*
* Tested with this bootloader:
* https://github.com/FleetProbe/MicroBridge-Arduino-ATMega2560
*/
//#define SD_FIRMWARE_UPDATE
#if ENABLED(SD_FIRMWARE_UPDATE)
#define SD_FIRMWARE_UPDATE_EEPROM_ADDR 0x1FF
#define SD_FIRMWARE_UPDATE_ACTIVE_VALUE 0xF0
#define SD_FIRMWARE_UPDATE_INACTIVE_VALUE 0xFF
#endif
// Add an optimized binary file transfer mode, initiated with 'M28 B1'
//#define BINARY_FILE_TRANSFER
#endif // SDSUPPORT
/**
* Additional options for Graphical Displays
*
* Use the optimizations here to improve printing performance,
* which can be adversely affected by graphical display drawing,
* especially when doing several short moves, and when printing
* on DELTA and SCARA machines.
*
* Some of these options may result in the display lagging behind
* controller events, as there is a trade-off between reliable
* printing performance versus fast display updates.
*/
#if HAS_GRAPHICAL_LCD
// Show SD percentage next to the progress bar
//#define DOGM_SD_PERCENT
// Enable to save many cycles by drawing a hollow frame on the Info Screen
#define XYZ_HOLLOW_FRAME
// Enable to save many cycles by drawing a hollow frame on Menu Screens
#define MENU_HOLLOW_FRAME
// A bigger font is available for edit items. Costs 3120 bytes of PROGMEM.
// Western only. Not available for Cyrillic, Kana, Turkish, Greek, or Chinese.
//#define USE_BIG_EDIT_FONT
// A smaller font may be used on the Info Screen. Costs 2300 bytes of PROGMEM.
// Western only. Not available for Cyrillic, Kana, Turkish, Greek, or Chinese.
//#define USE_SMALL_INFOFONT
// Enable this option and reduce the value to optimize screen updates.
// The normal delay is 10µs. Use the lowest value that still gives a reliable display.
//#define DOGM_SPI_DELAY_US 5
// Swap the CW/CCW indicators in the graphics overlay
//#define OVERLAY_GFX_REVERSE
/**
* ST7920-based LCDs can emulate a 16 x 4 character display using
* the ST7920 character-generator for very fast screen updates.
* Enable LIGHTWEIGHT_UI to use this special display mode.
*
* Since LIGHTWEIGHT_UI has limited space, the position and status
* message occupy the same line. Set STATUS_EXPIRE_SECONDS to the
* length of time to display the status message before clearing.
*
* Set STATUS_EXPIRE_SECONDS to zero to never clear the status.
* This will prevent position updates from being displayed.
*/
#if ENABLED(U8GLIB_ST7920)
//#define LIGHTWEIGHT_UI
#if ENABLED(LIGHTWEIGHT_UI)
#define STATUS_EXPIRE_SECONDS 20
#endif
#endif
/**
* Status (Info) Screen customizations
* These options may affect code size and screen render time.
* Custom status screens can forcibly override these settings.
*/
//#define STATUS_COMBINE_HEATERS // Use combined heater images instead of separate ones
//#define STATUS_HOTEND_NUMBERLESS // Use plain hotend icons instead of numbered ones (with 2+ hotends)
#define STATUS_HOTEND_INVERTED // Show solid nozzle bitmaps when heating (Requires STATUS_HOTEND_ANIM)
#define STATUS_HOTEND_ANIM // Use a second bitmap to indicate hotend heating
#define STATUS_BED_ANIM // Use a second bitmap to indicate bed heating
//#define STATUS_ALT_BED_BITMAP // Use the alternative bed bitmap
//#define STATUS_ALT_FAN_BITMAP // Use the alternative fan bitmap
//#define STATUS_FAN_FRAMES 3 // :[0,1,2,3,4] Number of fan animation frames
//#define STATUS_HEAT_PERCENT // Show heating in a progress bar
#endif // HAS_GRAPHICAL_LCD
// @section safety
// The hardware watchdog should reset the microcontroller disabling all outputs,
// in case the firmware gets stuck and doesn't do temperature regulation.
#define USE_WATCHDOG
#if ENABLED(USE_WATCHDOG)
// If you have a watchdog reboot in an ArduinoMega2560 then the device will hang forever, as a watchdog reset will leave the watchdog on.
// The "WATCHDOG_RESET_MANUAL" goes around this by not using the hardware reset.
// However, THIS FEATURE IS UNSAFE!, as it will only work if interrupts are disabled. And the code could hang in an interrupt routine with interrupts disabled.
//#define WATCHDOG_RESET_MANUAL
#endif
// @section lcd
/**
* Babystepping enables movement of the axes by tiny increments without changing
* the current position values. This feature is used primarily to adjust the Z
* axis in the first layer of a print in real-time.
*
* Warning: Does not respect endstops!
*/
#define BABYSTEPPING
#if ENABLED(BABYSTEPPING)
//#define BABYSTEP_WITHOUT_HOMING
//#define BABYSTEP_XY // Also enable X/Y Babystepping. Not supported on DELTA!
#define BABYSTEP_INVERT_Z false // Change if Z babysteps should go the other way
#define BABYSTEP_MULTIPLICATOR 10 // Babysteps are very small. Increase for faster motion.
#define DOUBLECLICK_FOR_Z_BABYSTEPPING // Double-click on the Status Screen for Z Babystepping.
#if ENABLED(DOUBLECLICK_FOR_Z_BABYSTEPPING)
#define DOUBLECLICK_MAX_INTERVAL 1250 // Maximum interval between clicks, in milliseconds.
// Note: Extra time may be added to mitigate controller latency.
//#define BABYSTEP_ALWAYS_AVAILABLE // Allow babystepping at all times (not just during movement).
//#define MOVE_Z_WHEN_IDLE // Jump to the move Z menu on doubleclick when printer is idle.
#if ENABLED(MOVE_Z_WHEN_IDLE)
#define MOVE_Z_IDLE_MULTIPLICATOR 1 // Multiply 1mm by this factor for the move step size.
#endif
#endif
//#define BABYSTEP_ZPROBE_OFFSET // Combine M851 Z and Babystepping
#if ENABLED(BABYSTEP_ZPROBE_OFFSET)
//#define BABYSTEP_HOTEND_Z_OFFSET // For multiple hotends, babystep relative Z offsets
//#define BABYSTEP_ZPROBE_GFX_OVERLAY // Enable graphical overlay on Z-offset editor
#endif
#endif
// @section extruder
/**
* Linear Pressure Control v1.5
*
* Assumption: advance [steps] = k * (delta velocity [steps/s])
* K=0 means advance disabled.
*
* NOTE: K values for LIN_ADVANCE 1.5 differ from earlier versions!
*
* Set K around 0.22 for 3mm PLA Direct Drive with ~6.5cm between the drive gear and heatbreak.
* Larger K values will be needed for flexible filament and greater distances.
* If this algorithm produces a higher speed offset than the extruder can handle (compared to E jerk)
* print acceleration will be reduced during the affected moves to keep within the limit.
*
* See http://marlinfw.org/docs/features/lin_advance.html for full instructions.
* Mention @Sebastianv650 on GitHub to alert the author of any issues.
*/
//#define LIN_ADVANCE
#if ENABLED(LIN_ADVANCE)
#define LIN_ADVANCE_K 0.22 // Unit: mm compression per 1mm/s extruder speed
//#define LA_DEBUG // If enabled, this will generate debug information output over USB.
#endif
// @section leveling
#if ENABLED(MESH_BED_LEVELING) || ENABLED(AUTO_BED_LEVELING_UBL)
// Override the mesh area if the automatic (max) area is too large
//#define MESH_MIN_X MESH_INSET
//#define MESH_MIN_Y MESH_INSET
//#define MESH_MAX_X X_BED_SIZE - (MESH_INSET)
//#define MESH_MAX_Y Y_BED_SIZE - (MESH_INSET)
#endif
/**
* Repeatedly attempt G29 leveling until it succeeds.
* Stop after G29_MAX_RETRIES attempts.
*/
//#define G29_RETRY_AND_RECOVER
#if ENABLED(G29_RETRY_AND_RECOVER)
#define G29_MAX_RETRIES 3
#define G29_HALT_ON_FAILURE
/**
* Specify the GCODE commands that will be executed when leveling succeeds,
* between attempts, and after the maximum number of retries have been tried.
*/
#define G29_SUCCESS_COMMANDS "M117 Bed leveling done."
#define G29_RECOVER_COMMANDS "M117 Probe failed. Rewiping.\nG28\nG12 P0 S12 T0"
#define G29_FAILURE_COMMANDS "M117 Bed leveling failed.\nG0 Z10\nM300 P25 S880\nM300 P50 S0\nM300 P25 S880\nM300 P50 S0\nM300 P25 S880\nM300 P50 S0\nG4 S1"
#endif
// @section extras
//
// G2/G3 Arc Support
//
//#define ARC_SUPPORT // Disable this feature to save ~3226 bytes
#if ENABLED(ARC_SUPPORT)
#define MM_PER_ARC_SEGMENT 1 // Length of each arc segment
#define N_ARC_CORRECTION 25 // Number of intertpolated segments between corrections
//#define ARC_P_CIRCLES // Enable the 'P' parameter to specify complete circles
//#define CNC_WORKSPACE_PLANES // Allow G2/G3 to operate in XY, ZX, or YZ planes
#endif
// Support for G5 with XYZE destination and IJPQ offsets. Requires ~2666 bytes.
//#define BEZIER_CURVE_SUPPORT
// G38.2 and G38.3 Probe Target
// Set MULTIPLE_PROBING if you want G38 to double touch
//#define G38_PROBE_TARGET
#if ENABLED(G38_PROBE_TARGET)
#define G38_MINIMUM_MOVE 0.0275 // minimum distance in mm that will produce a move (determined using the print statement in check_move)
#endif
// Moves (or segments) with fewer steps than this will be joined with the next move
#define MIN_STEPS_PER_SEGMENT 6
/**
* Minimum delay after setting the stepper DIR (in ns)
* 0 : No delay (Expect at least 10µS since one Stepper ISR must transpire)
* 20 : Minimum for TMC2xxx drivers
* 200 : Minimum for A4988 drivers
* 400 : Minimum for A5984 drivers
* 500 : Minimum for LV8729 drivers (guess, no info in datasheet)
* 650 : Minimum for DRV8825 drivers
* 1500 : Minimum for TB6600 drivers (guess, no info in datasheet)
* 15000 : Minimum for TB6560 drivers (guess, no info in datasheet)
*
* Override the default value based on the driver type set in Configuration.h.
*/
//#define MINIMUM_STEPPER_DIR_DELAY 650
/**
* Minimum stepper driver pulse width (in µs)
* 0 : Smallest possible width the MCU can produce, compatible with TMC2xxx drivers
* 1 : Minimum for A4988, A5984, and LV8729 stepper drivers
* 2 : Minimum for DRV8825 stepper drivers
* 3 : Minimum for TB6600 stepper drivers
* 30 : Minimum for TB6560 stepper drivers
*
* Override the default value based on the driver type set in Configuration.h.
*/
//#define MINIMUM_STEPPER_PULSE 2
/**
* Maximum stepping rate (in Hz) the stepper driver allows
* If undefined, defaults to 1MHz / (2 * MINIMUM_STEPPER_PULSE)
* 500000 : Maximum for A4988 stepper driver
* 400000 : Maximum for TMC2xxx stepper drivers
* 250000 : Maximum for DRV8825 stepper driver
* 150000 : Maximum for TB6600 stepper driver
* 130000 : Maximum for LV8729 stepper driver
* 15000 : Maximum for TB6560 stepper driver
*
* Override the default value based on the driver type set in Configuration.h.
*/
//#define MAXIMUM_STEPPER_RATE 250000
// @section temperature
// Control heater 0 and heater 1 in parallel.
//#define HEATERS_PARALLEL
//===========================================================================
//================================= Buffers =================================
//===========================================================================
// @section hidden
// The number of linear motions that can be in the plan at any give time.
// THE BLOCK_BUFFER_SIZE NEEDS TO BE A POWER OF 2 (e.g. 8, 16, 32) because shifts and ors are used to do the ring-buffering.
#if ENABLED(SDSUPPORT)
#define BLOCK_BUFFER_SIZE 16 // SD,LCD,Buttons take more memory, block buffer needs to be smaller
#else
#define BLOCK_BUFFER_SIZE 16 // maximize block buffer
#endif
// @section serial
// The ASCII buffer for serial input
#define MAX_CMD_SIZE 96
#define BUFSIZE 4
// Transmission to Host Buffer Size
// To save 386 bytes of PROGMEM (and TX_BUFFER_SIZE+3 bytes of RAM) set to 0.
// To buffer a simple "ok" you need 4 bytes.
// For ADVANCED_OK (M105) you need 32 bytes.
// For debug-echo: 128 bytes for the optimal speed.
// Other output doesn't need to be that speedy.
// :[0, 2, 4, 8, 16, 32, 64, 128, 256]
#define TX_BUFFER_SIZE 0
// Host Receive Buffer Size
// Without XON/XOFF flow control (see SERIAL_XON_XOFF below) 32 bytes should be enough.
// To use flow control, set this buffer size to at least 1024 bytes.
// :[0, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]
//#define RX_BUFFER_SIZE 1024
#if RX_BUFFER_SIZE >= 1024
// Enable to have the controller send XON/XOFF control characters to
// the host to signal the RX buffer is becoming full.
//#define SERIAL_XON_XOFF
#endif
#if ENABLED(SDSUPPORT)
// Enable this option to collect and display the maximum
// RX queue usage after transferring a file to SD.
//#define SERIAL_STATS_MAX_RX_QUEUED
// Enable this option to collect and display the number
// of dropped bytes after a file transfer to SD.
//#define SERIAL_STATS_DROPPED_RX
#endif
// Enable an emergency-command parser to intercept certain commands as they
// enter the serial receive buffer, so they cannot be blocked.
// Currently handles M108, M112, M410
// Does not work on boards using AT90USB (USBCON) processors!
//#define EMERGENCY_PARSER
// Bad Serial-connections can miss a received command by sending an 'ok'
// Therefore some clients abort after 30 seconds in a timeout.
// Some other clients start sending commands while receiving a 'wait'.
// This "wait" is only sent when the buffer is empty. 1 second is a good value here.
//#define NO_TIMEOUTS 1000 // Milliseconds
// Some clients will have this feature soon. This could make the NO_TIMEOUTS unnecessary.
//#define ADVANCED_OK
// Printrun may have trouble receiving long strings all at once.
// This option inserts short delays between lines of serial output.
#define SERIAL_OVERRUN_PROTECTION
// @section extras
/**
* Extra Fan Speed
* Adds a secondary fan speed for each print-cooling fan.
* 'M106 P<fan> T3-255' : Set a secondary speed for <fan>
* 'M106 P<fan> T2' : Use the set secondary speed
* 'M106 P<fan> T1' : Restore the previous fan speed
*/
//#define EXTRA_FAN_SPEED
/**
* Firmware-based and LCD-controlled retract
*
* Add G10 / G11 commands for automatic firmware-based retract / recover.
* Use M207 and M208 to define parameters for retract / recover.
*
* Use M209 to enable or disable auto-retract.
* With auto-retract enabled, all G1 E moves within the set range
* will be converted to firmware-based retract/recover moves.
*
* Be sure to turn off auto-retract during filament change.
*
* Note that M207 / M208 / M209 settings are saved to EEPROM.
*
*/
//#define FWRETRACT
#if ENABLED(FWRETRACT)
#define FWRETRACT_AUTORETRACT // costs ~500 bytes of PROGMEM
#if ENABLED(FWRETRACT_AUTORETRACT)
#define MIN_AUTORETRACT 0.1 // When auto-retract is on, convert E moves of this length and over
#define MAX_AUTORETRACT 10.0 // Upper limit for auto-retract conversion
#endif
#define RETRACT_LENGTH 3 // Default retract length (positive mm)
#define RETRACT_LENGTH_SWAP 13 // Default swap retract length (positive mm), for extruder change
#define RETRACT_FEEDRATE 45 // Default feedrate for retracting (mm/s)
#define RETRACT_ZRAISE 0 // Default retract Z-raise (mm)
#define RETRACT_RECOVER_LENGTH 0 // Default additional recover length (mm, added to retract length when recovering)
#define RETRACT_RECOVER_LENGTH_SWAP 0 // Default additional swap recover length (mm, added to retract length when recovering from extruder change)
#define RETRACT_RECOVER_FEEDRATE 8 // Default feedrate for recovering from retraction (mm/s)
#define RETRACT_RECOVER_FEEDRATE_SWAP 8 // Default feedrate for recovering from swap retraction (mm/s)
#if ENABLED(MIXING_EXTRUDER)
//#define RETRACT_SYNC_MIXING // Retract and restore all mixing steppers simultaneously
#endif
#endif
/**
* Universal tool change settings.
* Applies to all types of extruders except where explicitly noted.
*/
#if EXTRUDERS > 1
// Z raise distance for tool-change, as needed for some extruders
#define TOOLCHANGE_ZRAISE 2 // (mm)
// Retract and prime filament on tool-change
//#define TOOLCHANGE_FILAMENT_SWAP
#if ENABLED(TOOLCHANGE_FILAMENT_SWAP)
#define TOOLCHANGE_FIL_SWAP_LENGTH 12 // (mm)
#define TOOLCHANGE_FIL_EXTRA_PRIME 2 // (mm)
#define TOOLCHANGE_FIL_SWAP_RETRACT_SPEED 3600 // (mm/m)
#define TOOLCHANGE_FIL_SWAP_PRIME_SPEED 3600 // (mm/m)
#endif
/**
* Position to park head during tool change.
* Doesn't apply to SWITCHING_TOOLHEAD, DUAL_X_CARRIAGE, or PARKING_EXTRUDER
*/
//#define TOOLCHANGE_PARK
#if ENABLED(TOOLCHANGE_PARK)
#define TOOLCHANGE_PARK_XY { X_MIN_POS + 10, Y_MIN_POS + 10 }
#define TOOLCHANGE_PARK_XY_FEEDRATE 6000 // (mm/m)
#endif
#endif
/**
* Advanced Pause
* Experimental feature for filament change support and for parking the nozzle when paused.
* Adds the GCode M600 for initiating filament change.
* If PARK_HEAD_ON_PAUSE enabled, adds the GCode M125 to pause printing and park the nozzle.
*
* Requires an LCD display.
* Requires NOZZLE_PARK_FEATURE.
* This feature is required for the default FILAMENT_RUNOUT_SCRIPT.
*/
#define ADVANCED_PAUSE_FEATURE
#if ENABLED(ADVANCED_PAUSE_FEATURE)
#define PAUSE_PARK_RETRACT_FEEDRATE 60 // (mm/s) Initial retract feedrate.
#define PAUSE_PARK_RETRACT_LENGTH 4 // (mm) Initial retract.
// This short retract is done immediately, before parking the nozzle.
#define FILAMENT_CHANGE_UNLOAD_FEEDRATE 10 // (mm/s) Unload filament feedrate. This can be pretty fast.
#define FILAMENT_CHANGE_UNLOAD_ACCEL 25 // (mm/s^2) Lower acceleration may allow a faster feedrate.
#define FILAMENT_CHANGE_UNLOAD_LENGTH 420 // (mm) The length of filament for a complete unload.
// For Bowden, the full length of the tube and nozzle.
// For direct drive, the full length of the nozzle.
// Set to 0 for manual unloading.
#define FILAMENT_CHANGE_SLOW_LOAD_FEEDRATE 6 // (mm/s) Slow move when starting load.
#define FILAMENT_CHANGE_SLOW_LOAD_LENGTH 0 // (mm) Slow length, to allow time to insert material.
// 0 to disable start loading and skip to fast load only
#define FILAMENT_CHANGE_FAST_LOAD_FEEDRATE 8 // (mm/s) Load filament feedrate. This can be pretty fast.
#define FILAMENT_CHANGE_FAST_LOAD_ACCEL 25 // (mm/s^2) Lower acceleration may allow a faster feedrate.
#define FILAMENT_CHANGE_FAST_LOAD_LENGTH 0 // (mm) Load length of filament, from extruder gear to nozzle.
// For Bowden, the full length of the tube and nozzle.
// For direct drive, the full length of the nozzle.
//#define ADVANCED_PAUSE_CONTINUOUS_PURGE // Purge continuously up to the purge length until interrupted.
#define ADVANCED_PAUSE_PURGE_FEEDRATE 3 // (mm/s) Extrude feedrate (after loading). Should be slower than load feedrate.
#define ADVANCED_PAUSE_PURGE_LENGTH 50 // (mm) Length to extrude after loading.
// Set to 0 for manual extrusion.
// Filament can be extruded repeatedly from the Filament Change menu
// until extrusion is consistent, and to purge old filament.
#define ADVANCED_PAUSE_RESUME_PRIME 0 // (mm) Extra distance to prime nozzle after returning from park.
// Filament Unload does a Retract, Delay, and Purge first:
#define FILAMENT_UNLOAD_RETRACT_LENGTH 13 // (mm) Unload initial retract length.
#define FILAMENT_UNLOAD_DELAY 5000 // (ms) Delay for the filament to cool after retract.
#define FILAMENT_UNLOAD_PURGE_LENGTH 8 // (mm) An unretract is done, then this length is purged.
#define PAUSE_PARK_NOZZLE_TIMEOUT 120 // (seconds) Time limit before the nozzle is turned off for safety.
#define FILAMENT_CHANGE_ALERT_BEEPS 6 // Number of alert beeps to play when a response is needed.
#define PAUSE_PARK_NO_STEPPER_TIMEOUT // Enable for XYZ steppers to stay powered on during filament change.
#define PARK_HEAD_ON_PAUSE // Park the nozzle during pause and filament change.
#define HOME_BEFORE_FILAMENT_CHANGE // Ensure homing has been completed prior to parking for filament change
//#define FILAMENT_LOAD_UNLOAD_GCODES // Add M701/M702 Load/Unload G-codes, plus Load/Unload in the LCD Prepare menu.
//#define FILAMENT_UNLOAD_ALL_EXTRUDERS // Allow M702 to unload all extruders above a minimum target temp (as set by M302)
#endif
// @section tmc
/**
* TMC26X Stepper Driver options
*
* The TMC26XStepper library is required for this stepper driver.
* https://github.com/trinamic/TMC26XStepper
*/
#if HAS_DRIVER(TMC26X)
#if AXIS_DRIVER_TYPE_X(TMC26X)
#define X_MAX_CURRENT 1000 // (mA)
#define X_SENSE_RESISTOR 91 // (mOhms)
#define X_MICROSTEPS 16 // Number of microsteps
#endif
#if AXIS_DRIVER_TYPE_X2(TMC26X)
#define X2_MAX_CURRENT 1000
#define X2_SENSE_RESISTOR 91
#define X2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Y(TMC26X)
#define Y_MAX_CURRENT 1000
#define Y_SENSE_RESISTOR 91
#define Y_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Y2(TMC26X)
#define Y2_MAX_CURRENT 1000
#define Y2_SENSE_RESISTOR 91
#define Y2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Z(TMC26X)
#define Z_MAX_CURRENT 1000
#define Z_SENSE_RESISTOR 91
#define Z_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Z2(TMC26X)
#define Z2_MAX_CURRENT 1000
#define Z2_SENSE_RESISTOR 91
#define Z2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_Z3(TMC26X)
#define Z3_MAX_CURRENT 1000
#define Z3_SENSE_RESISTOR 91
#define Z3_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E0(TMC26X)
#define E0_MAX_CURRENT 1000
#define E0_SENSE_RESISTOR 91
#define E0_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E1(TMC26X)
#define E1_MAX_CURRENT 1000
#define E1_SENSE_RESISTOR 91
#define E1_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E2(TMC26X)
#define E2_MAX_CURRENT 1000
#define E2_SENSE_RESISTOR 91
#define E2_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E3(TMC26X)
#define E3_MAX_CURRENT 1000
#define E3_SENSE_RESISTOR 91
#define E3_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E4(TMC26X)
#define E4_MAX_CURRENT 1000
#define E4_SENSE_RESISTOR 91
#define E4_MICROSTEPS 16
#endif
#if AXIS_DRIVER_TYPE_E5(TMC26X)
#define E5_MAX_CURRENT 1000
#define E5_SENSE_RESISTOR 91
#define E5_MICROSTEPS 16
#endif
#endif // TMC26X
// @section tmc_smart
/**
* To use TMC2130, TMC2160, TMC2660, TMC5130, TMC5160 stepper drivers in SPI mode
* connect your SPI pins to the hardware SPI interface on your board and define
* the required CS pins in your `pins_MYBOARD.h` file. (e.g., RAMPS 1.4 uses AUX3
* pins `X_CS_PIN 53`, `Y_CS_PIN 49`, etc.).
* You may also use software SPI if you wish to use general purpose IO pins.
*
* To use TMC2208 stepper UART-configurable stepper drivers connect #_SERIAL_TX_PIN
* to the driver side PDN_UART pin with a 1K resistor.
* To use the reading capabilities, also connect #_SERIAL_RX_PIN to PDN_UART without
* a resistor.
* The drivers can also be used with hardware serial.
*
* TMCStepper library is required to use TMC stepper drivers.
* https://github.com/teemuatlut/TMCStepper
*/
#if HAS_TRINAMIC
#define HOLD_MULTIPLIER 0.5 // Scales down the holding current from run current
#define INTERPOLATE true // Interpolate X/Y/Z_MICROSTEPS to 256
#if AXIS_IS_TMC(X)
#define X_CURRENT 800 // (mA) RMS current. Multiply by 1.414 for peak current.
#define X_MICROSTEPS 16 // 0..256
#define X_RSENSE 0.11
#endif
#if AXIS_IS_TMC(X2)
#define X2_CURRENT 800
#define X2_MICROSTEPS 16
#define X2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Y)
#define Y_CURRENT 800
#define Y_MICROSTEPS 16
#define Y_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Y2)
#define Y2_CURRENT 800
#define Y2_MICROSTEPS 16
#define Y2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Z)
#define Z_CURRENT 800
#define Z_MICROSTEPS 16
#define Z_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Z2)
#define Z2_CURRENT 800
#define Z2_MICROSTEPS 16
#define Z2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(Z3)
#define Z3_CURRENT 800
#define Z3_MICROSTEPS 16
#define Z3_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E0)
#define E0_CURRENT 800
#define E0_MICROSTEPS 16
#define E0_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E1)
#define E1_CURRENT 800
#define E1_MICROSTEPS 16
#define E1_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E2)
#define E2_CURRENT 800
#define E2_MICROSTEPS 16
#define E2_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E3)
#define E3_CURRENT 800
#define E3_MICROSTEPS 16
#define E3_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E4)
#define E4_CURRENT 800
#define E4_MICROSTEPS 16
#define E4_RSENSE 0.11
#endif
#if AXIS_IS_TMC(E5)
#define E5_CURRENT 800
#define E5_MICROSTEPS 16
#define E5_RSENSE 0.11
#endif
/**
* Override default SPI pins for TMC2130, TMC2160, TMC2660, TMC5130 and TMC5160 drivers here.
* The default pins can be found in your board's pins file.
*/
//#define X_CS_PIN -1
//#define Y_CS_PIN -1
//#define Z_CS_PIN -1
//#define X2_CS_PIN -1
//#define Y2_CS_PIN -1
//#define Z2_CS_PIN -1
//#define Z3_CS_PIN -1
//#define E0_CS_PIN -1
//#define E1_CS_PIN -1
//#define E2_CS_PIN -1
//#define E3_CS_PIN -1
//#define E4_CS_PIN -1
//#define E5_CS_PIN -1
/**
* Use software SPI for TMC2130.
* Software option for SPI driven drivers (TMC2130, TMC2160, TMC2660, TMC5130 and TMC5160).
* The default SW SPI pins are defined the respective pins files,
* but you can override or define them here.
*/
//#define TMC_USE_SW_SPI
//#define TMC_SW_MOSI -1
//#define TMC_SW_MISO -1
//#define TMC_SW_SCK -1
/**
* Software enable
*
* Use for drivers that do not use a dedicated enable pin, but rather handle the same
* function through a communication line such as SPI or UART.
*/
//#define SOFTWARE_DRIVER_ENABLE
/**
* TMC2130, TMC2160, TMC2208, TMC5130 and TMC5160 only
* Use Trinamic's ultra quiet stepping mode.
* When disabled, Marlin will use spreadCycle stepping mode.
*/
#define STEALTHCHOP_XY
#define STEALTHCHOP_Z
#define STEALTHCHOP_E
/**
* Optimize spreadCycle chopper parameters by using predefined parameter sets
* or with the help of an example included in the library.
* Provided parameter sets are
* CHOPPER_DEFAULT_12V
* CHOPPER_DEFAULT_19V
* CHOPPER_DEFAULT_24V
* CHOPPER_DEFAULT_36V
* CHOPPER_PRUSAMK3_24V // Imported parameters from the official Prusa firmware for MK3 (24V)
* CHOPPER_MARLIN_119 // Old defaults from Marlin v1.1.9
*
* Define you own with
* { <off_time[1..15]>, <hysteresis_end[-3..12]>, hysteresis_start[1..8] }
*/
#define CHOPPER_TIMING CHOPPER_DEFAULT_12V
/**
* Monitor Trinamic drivers for error conditions,
* like overtemperature and short to ground. TMC2208 requires hardware serial.
* In the case of overtemperature Marlin can decrease the driver current until error condition clears.
* Other detected conditions can be used to stop the current print.
* Relevant g-codes:
* M906 - Set or get motor current in milliamps using axis codes X, Y, Z, E. Report values if no axis codes given.
* M911 - Report stepper driver overtemperature pre-warn condition.
* M912 - Clear stepper driver overtemperature pre-warn condition flag.
* M122 - Report driver parameters (Requires TMC_DEBUG)
*/
//#define MONITOR_DRIVER_STATUS
#if ENABLED(MONITOR_DRIVER_STATUS)
#define CURRENT_STEP_DOWN 50 // [mA]
#define REPORT_CURRENT_CHANGE
#define STOP_ON_ERROR
#endif
/**
* TMC2130, TMC2160, TMC2208, TMC5130 and TMC5160 only
* The driver will switch to spreadCycle when stepper speed is over HYBRID_THRESHOLD.
* This mode allows for faster movements at the expense of higher noise levels.
* STEALTHCHOP_(XY|Z|E) must be enabled to use HYBRID_THRESHOLD.
* M913 X/Y/Z/E to live tune the setting
*/
//#define HYBRID_THRESHOLD
#define X_HYBRID_THRESHOLD 100 // [mm/s]
#define X2_HYBRID_THRESHOLD 100
#define Y_HYBRID_THRESHOLD 100
#define Y2_HYBRID_THRESHOLD 100
#define Z_HYBRID_THRESHOLD 3
#define Z2_HYBRID_THRESHOLD 3
#define Z3_HYBRID_THRESHOLD 3
#define E0_HYBRID_THRESHOLD 30
#define E1_HYBRID_THRESHOLD 30
#define E2_HYBRID_THRESHOLD 30
#define E3_HYBRID_THRESHOLD 30
#define E4_HYBRID_THRESHOLD 30
#define E5_HYBRID_THRESHOLD 30
/**
* TMC2130, TMC2160, TMC2660, TMC5130, and TMC5160 only
* Use StallGuard2 to sense an obstacle and trigger an endstop.
* Connect the stepper driver's DIAG1 pin to the X/Y endstop pin.
* X, Y, and Z homing will always be done in spreadCycle mode.
*
* X/Y/Z_STALL_SENSITIVITY is used for tuning the trigger sensitivity.
* Higher values make the system LESS sensitive.
* Lower value make the system MORE sensitive.
* Too low values can lead to false positives, while too high values will collide the axis without triggering.
* It is advised to set X/Y/Z_HOME_BUMP_MM to 0.
* M914 X/Y/Z to live tune the setting
*/
//#define SENSORLESS_HOMING // TMC2130 only
/**
* Use StallGuard2 to probe the bed with the nozzle.
*
* CAUTION: This could cause damage to machines that use a lead screw or threaded rod
* to move the Z axis. Take extreme care when attempting to enable this feature.
*/
//#define SENSORLESS_PROBING // TMC2130 only
#if ENABLED(SENSORLESS_HOMING) || ENABLED(SENSORLESS_PROBING)
#define X_STALL_SENSITIVITY 8
#define Y_STALL_SENSITIVITY 8
//#define Z_STALL_SENSITIVITY 8
#endif
/**
* Enable M122 debugging command for TMC stepper drivers.
* M122 S0/1 will enable continous reporting.
*/
//#define TMC_DEBUG
/**
* You can set your own advanced settings by filling in predefined functions.
* A list of available functions can be found on the library github page
* https://github.com/teemuatlut/TMC2130Stepper
* https://github.com/teemuatlut/TMC2208Stepper
*
* Example:
* #define TMC_ADV() { \
* stepperX.diag0_temp_prewarn(1); \
* stepperY.interpolate(0); \
* }
*/
#define TMC_ADV() { }
#endif // HAS_TRINAMIC
// @section L6470
/**
* L6470 Stepper Driver options
*
* Arduino-L6470 library (0.7.0 or higher) is required for this stepper driver.
* https://github.com/ameyer/Arduino-L6470
*
* Requires the following to be defined in your pins_YOUR_BOARD file
* L6470_CHAIN_SCK_PIN
* L6470_CHAIN_MISO_PIN
* L6470_CHAIN_MOSI_PIN
* L6470_CHAIN_SS_PIN
* L6470_RESET_CHAIN_PIN (optional)
*/
#if HAS_DRIVER(L6470)
//#define L6470_CHITCHAT // Display additional status info
#if AXIS_DRIVER_TYPE_X(L6470)
#define X_MICROSTEPS 128 // Number of microsteps (VALID: 1, 2, 4, 8, 16, 32, 128)
#define X_OVERCURRENT 2000 // (mA) Current where the driver detects an over current (VALID: 375 x (1 - 16) - 6A max - rounds down)
#define X_STALLCURRENT 1500 // (mA) Current where the driver detects a stall (VALID: 31.25 * (1-128) - 4A max - rounds down)
#define X_MAX_VOLTAGE 127 // 0-255, Maximum effective voltage seen by stepper
#define X_CHAIN_POS 0 // Position in SPI chain, 0=Not in chain, 1=Nearest MOSI
#endif
#if AXIS_DRIVER_TYPE_X2(L6470)
#define X2_MICROSTEPS 128
#define X2_OVERCURRENT 2000
#define X2_STALLCURRENT 1500
#define X2_MAX_VOLTAGE 127
#define X2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Y(L6470)
#define Y_MICROSTEPS 128
#define Y_OVERCURRENT 2000
#define Y_STALLCURRENT 1500
#define Y_MAX_VOLTAGE 127
#define Y_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Y2(L6470)
#define Y2_MICROSTEPS 128
#define Y2_OVERCURRENT 2000
#define Y2_STALLCURRENT 1500
#define Y2_MAX_VOLTAGE 127
#define Y2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Z(L6470)
#define Z_MICROSTEPS 128
#define Z_OVERCURRENT 2000
#define Z_STALLCURRENT 1500
#define Z_MAX_VOLTAGE 127
#define Z_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Z2(L6470)
#define Z2_MICROSTEPS 128
#define Z2_OVERCURRENT 2000
#define Z2_STALLCURRENT 1500
#define Z2_MAX_VOLTAGE 127
#define Z2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_Z3(L6470)
#define Z3_MICROSTEPS 128
#define Z3_OVERCURRENT 2000
#define Z3_STALLCURRENT 1500
#define Z3_MAX_VOLTAGE 127
#define Z3_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E0(L6470)
#define E0_MICROSTEPS 128
#define E0_OVERCURRENT 2000
#define E0_STALLCURRENT 1500
#define E0_MAX_VOLTAGE 127
#define E0_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E1(L6470)
#define E1_MICROSTEPS 128
#define E1_OVERCURRENT 2000
#define E1_STALLCURRENT 1500
#define E1_MAX_VOLTAGE 127
#define E1_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E2(L6470)
#define E2_MICROSTEPS 128
#define E2_OVERCURRENT 2000
#define E2_STALLCURRENT 1500
#define E2_MAX_VOLTAGE 127
#define E2_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E3(L6470)
#define E3_MICROSTEPS 128
#define E3_OVERCURRENT 2000
#define E3_STALLCURRENT 1500
#define E3_MAX_VOLTAGE 127
#define E3_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E4(L6470)
#define E4_MICROSTEPS 128
#define E4_OVERCURRENT 2000
#define E4_STALLCURRENT 1500
#define E4_MAX_VOLTAGE 127
#define E4_CHAIN_POS 0
#endif
#if AXIS_DRIVER_TYPE_E5(L6470)
#define E5_MICROSTEPS 128
#define E5_OVERCURRENT 2000
#define E5_STALLCURRENT 1500
#define E5_MAX_VOLTAGE 127
#define E5_CHAIN_POS 0
#endif
/**
* Monitor L6470 drivers for error conditions like over temperature and over current.
* In the case of over temperature Marlin can decrease the drive until the error condition clears.
* Other detected conditions can be used to stop the current print.
* Relevant g-codes:
* M906 - I1/2/3/4/5 Set or get motor drive level using axis codes X, Y, Z, E. Report values if no axis codes given.
* I not present or I0 or I1 - X, Y, Z or E0
* I2 - X2, Y2, Z2 or E1
* I3 - Z3 or E3
* I4 - E4
* I5 - E5
* M916 - Increase drive level until get thermal warning
* M917 - Find minimum current thresholds
* M918 - Increase speed until max or error
* M122 S0/1 - Report driver parameters
*/
//#define MONITOR_L6470_DRIVER_STATUS
#if ENABLED(MONITOR_L6470_DRIVER_STATUS)
#define KVAL_HOLD_STEP_DOWN 1
//#define L6470_STOP_ON_ERROR
#endif
#endif // L6470
/**
* TWI/I2C BUS
*
* This feature is an EXPERIMENTAL feature so it shall not be used on production
* machines. Enabling this will allow you to send and receive I2C data from slave
* devices on the bus.
*
* ; Example #1
* ; This macro send the string "Marlin" to the slave device with address 0x63 (99)
* ; It uses multiple M260 commands with one B<base 10> arg
* M260 A99 ; Target slave address
* M260 B77 ; M
* M260 B97 ; a
* M260 B114 ; r
* M260 B108 ; l
* M260 B105 ; i
* M260 B110 ; n
* M260 S1 ; Send the current buffer
*
* ; Example #2
* ; Request 6 bytes from slave device with address 0x63 (99)
* M261 A99 B5
*
* ; Example #3
* ; Example serial output of a M261 request
* echo:i2c-reply: from:99 bytes:5 data:hello
*/
// @section i2cbus
//#define EXPERIMENTAL_I2CBUS
#define I2C_SLAVE_ADDRESS 0 // Set a value from 8 to 127 to act as a slave
// @section extras
/**
* Photo G-code
* Add the M240 G-code to take a photo.
* The photo can be triggered by a digital pin or a physical movement.
*/
//#define PHOTO_GCODE
#if ENABLED(PHOTO_GCODE)
// A position to move to (and raise Z) before taking the photo
//#define PHOTO_POSITION { X_MAX_POS - 5, Y_MAX_POS, 0 } // { xpos, ypos, zraise } (M240 X Y Z)
//#define PHOTO_DELAY_MS 100 // (ms) Duration to pause before moving back (M240 P)
//#define PHOTO_RETRACT_MM 6.5 // (mm) E retract/recover for the photo move (M240 R S)
// Canon RC-1 or homebrew digital camera trigger
// Data from: http://www.doc-diy.net/photo/rc-1_hacked/
//#define PHOTOGRAPH_PIN 23
// Canon Hack Development Kit
// http://captain-slow.dk/2014/03/09/3d-printing-timelapses/
//#define CHDK_PIN 4
// Optional second move with delay to trigger the camera shutter
//#define PHOTO_SWITCH_POSITION { X_MAX_POS, Y_MAX_POS } // { xpos, ypos } (M240 I J)
// Duration to hold the switch or keep CHDK_PIN high
//#define PHOTO_SWITCH_MS 50 // (ms) (M240 D)
#endif
/**
* Spindle & Laser control
*
* Add the M3, M4, and M5 commands to turn the spindle/laser on and off, and
* to set spindle speed, spindle direction, and laser power.
*
* SuperPid is a router/spindle speed controller used in the CNC milling community.
* Marlin can be used to turn the spindle on and off. It can also be used to set
* the spindle speed from 5,000 to 30,000 RPM.
*
* You'll need to select a pin for the ON/OFF function and optionally choose a 0-5V
* hardware PWM pin for the speed control and a pin for the rotation direction.
*
* See http://marlinfw.org/docs/configuration/laser_spindle.html for more config details.
*/
//#define SPINDLE_LASER_ENABLE
#if ENABLED(SPINDLE_LASER_ENABLE)
#define SPINDLE_LASER_ENABLE_INVERT false // set to "true" if the on/off function is reversed
#define SPINDLE_LASER_PWM true // set to true if your controller supports setting the speed/power
#define SPINDLE_LASER_PWM_INVERT true // set to "true" if the speed/power goes up when you want it to go slower
#define SPINDLE_LASER_POWERUP_DELAY 5000 // delay in milliseconds to allow the spindle/laser to come up to speed/power
#define SPINDLE_LASER_POWERDOWN_DELAY 5000 // delay in milliseconds to allow the spindle to stop
#define SPINDLE_DIR_CHANGE true // set to true if your spindle controller supports changing spindle direction
#define SPINDLE_INVERT_DIR false
#define SPINDLE_STOP_ON_DIR_CHANGE true // set to true if Marlin should stop the spindle before changing rotation direction
/**
* The M3 & M4 commands use the following equation to convert PWM duty cycle to speed/power
*
* SPEED/POWER = PWM duty cycle * SPEED_POWER_SLOPE + SPEED_POWER_INTERCEPT
* where PWM duty cycle varies from 0 to 255
*
* set the following for your controller (ALL MUST BE SET)
*/
#define SPEED_POWER_SLOPE 118.4
#define SPEED_POWER_INTERCEPT 0
#define SPEED_POWER_MIN 5000
#define SPEED_POWER_MAX 30000 // SuperPID router controller 0 - 30,000 RPM
//#define SPEED_POWER_SLOPE 0.3922
//#define SPEED_POWER_INTERCEPT 0
//#define SPEED_POWER_MIN 10
//#define SPEED_POWER_MAX 100 // 0-100%
#endif
/**
* Filament Width Sensor
*
* Measures the filament width in real-time and adjusts
* flow rate to compensate for any irregularities.
*
* Also allows the measured filament diameter to set the
* extrusion rate, so the slicer only has to specify the
* volume.
*
* Only a single extruder is supported at this time.
*
* 34 RAMPS_14 : Analog input 5 on the AUX2 connector
* 81 PRINTRBOARD : Analog input 2 on the Exp1 connector (version B,C,D,E)
* 301 RAMBO : Analog input 3
*
* Note: May require analog pins to be defined for other boards.
*/
//#define FILAMENT_WIDTH_SENSOR
#define DEFAULT_STDDEV_FILAMENT_DIA 0.05 // Typical estimate for cheap filament
//#define DEFAULT_STDDEV_FILAMENT_DIA 0.02 // Typical advertised for higher quality filament
#if ENABLED(FILAMENT_WIDTH_SENSOR)
#define FILAMENT_SENSOR_EXTRUDER_NUM 0 // Index of the extruder that has the filament sensor. :[0,1,2,3,4]
#define MEASUREMENT_DELAY_CM 14 // (cm) The distance from the filament sensor to the melting chamber
#define FILWIDTH_ERROR_MARGIN (DEFAULT_STDDEV_FILAMENT_DIA*4) // (mm) If a measurement differs too much from nominal width ignore it
#define MAX_MEASUREMENT_DELAY 20 // (bytes) Buffer size for stored measurements (1 byte per cm). Must be larger than MEASUREMENT_DELAY_CM.
#define DEFAULT_MEASURED_FILAMENT_DIA DEFAULT_NOMINAL_FILAMENT_DIA // Set measured to nominal initially
// Display filament width on the LCD status line. Status messages will expire after 5 seconds.
//#define FILAMENT_LCD_DISPLAY
#endif
/**
* CNC Coordinate Systems
*
* Enables G53 and G54-G59.3 commands to select coordinate systems
* and G92.1 to reset the workspace to native machine space.
*/
//#define CNC_COORDINATE_SYSTEMS
/**
* Auto-report temperatures with M155 S<seconds>
*/
#define AUTO_REPORT_TEMPERATURES
/**
* Include capabilities in M115 output
*/
#define EXTENDED_CAPABILITIES_REPORT
/**
* Disable all Volumetric extrusion options
*/
//#define NO_VOLUMETRICS
#if DISABLED(NO_VOLUMETRICS)
/**
* Volumetric extrusion default state
* Activate to make volumetric extrusion the default method,
* with DEFAULT_NOMINAL_FILAMENT_DIA as the default diameter.
*
* M200 D0 to disable, M200 Dn to set a new diameter.
*/
//#define VOLUMETRIC_DEFAULT_ON
#endif
/**
* Enable this option for a leaner build of Marlin that removes all
* workspace offsets, simplifying coordinate transformations, leveling, etc.
*
* - M206 and M428 are disabled.
* - G92 will revert to its behavior from Marlin 1.0.
*/
#define NO_WORKSPACE_OFFSETS
/**
* Set the number of proportional font spaces required to fill up a typical character space.
* This can help to better align the output of commands like `G29 O` Mesh Output.
*
* For clients that use a fixed-width font (like OctoPrint), leave this set to 1.0.
* Otherwise, adjust according to your client and font.
*/
#define PROPORTIONAL_FONT_RATIO 1.0
/**
* Spend 28 bytes of SRAM to optimize the GCode parser
*/
#define FASTER_GCODE_PARSER
/**
* CNC G-code options
* Support CNC-style G-code dialects used by laser cutters, drawing machine cams, etc.
* Note that G0 feedrates should be used with care for 3D printing (if used at all).
* High feedrates may cause ringing and harm print quality.
*/
//#define PAREN_COMMENTS // Support for parentheses-delimited comments
//#define GCODE_MOTION_MODES // Remember the motion mode (G0 G1 G2 G3 G5 G38.X) and apply for X Y Z E F, etc.
// Enable and set a (default) feedrate for all G0 moves
//#define G0_FEEDRATE 3000 // (mm/m)
#ifdef G0_FEEDRATE
//#define VARIABLE_G0_FEEDRATE // The G0 feedrate is set by F in G0 motion mode
#endif
/**
* G-code Macros
*
* Add G-codes M810-M819 to define and run G-code macros.
* Macros are not saved to EEPROM.
*/
//#define GCODE_MACROS
#if ENABLED(GCODE_MACROS)
#define GCODE_MACROS_SLOTS 5 // Up to 10 may be used
#define GCODE_MACROS_SLOT_SIZE 50 // Maximum length of a single macro
#endif
/**
* User-defined menu items that execute custom GCode
*/
//#define CUSTOM_USER_MENUS
#if ENABLED(CUSTOM_USER_MENUS)
//#define CUSTOM_USER_MENU_TITLE "Custom Commands"
#define USER_SCRIPT_DONE "M117 User Script Done"
#define USER_SCRIPT_AUDIBLE_FEEDBACK
//#define USER_SCRIPT_RETURN // Return to status screen after a script
#define USER_DESC_1 "Home & UBL Info"
#define USER_GCODE_1 "G28\nG29 W"
#define USER_DESC_2 "Preheat for " PREHEAT_1_LABEL
#define USER_GCODE_2 "M140 S" STRINGIFY(PREHEAT_1_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_1_TEMP_HOTEND)
#define USER_DESC_3 "Preheat for " PREHEAT_2_LABEL
#define USER_GCODE_3 "M140 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\nM104 S" STRINGIFY(PREHEAT_2_TEMP_HOTEND)
#define USER_DESC_4 "Heat Bed/Home/Level"
#define USER_GCODE_4 "M140 S" STRINGIFY(PREHEAT_2_TEMP_BED) "\nG28\nG29"
#define USER_DESC_5 "Home & Info"
#define USER_GCODE_5 "G28\nM503"
#endif
/**
* Host Action Commands
*
* Define host streamer action commands in compliance with the standard.
*
* See https://reprap.org/wiki/G-code#Action_commands
* Common commands ........ poweroff, pause, paused, resume, resumed, cancel
* G29_RETRY_AND_RECOVER .. probe_rewipe, probe_failed
*
* Some features add reason codes to extend these commands.
*
* Host Prompt Support enables Marlin to use the host for user prompts so
* filament runout and other processes can be managed from the host side.
*/
//#define HOST_ACTION_COMMANDS
#if ENABLED(HOST_ACTION_COMMANDS)
//#define HOST_PROMPT_SUPPORT
#endif
//===========================================================================
//====================== I2C Position Encoder Settings ======================
//===========================================================================
/**
* I2C position encoders for closed loop control.
* Developed by Chris Barr at Aus3D.
*
* Wiki: http://wiki.aus3d.com.au/Magnetic_Encoder
* Github: https://github.com/Aus3D/MagneticEncoder
*
* Supplier: http://aus3d.com.au/magnetic-encoder-module
* Alternative Supplier: http://reliabuild3d.com/
*
* Reliabuild encoders have been modified to improve reliability.
*/
//#define I2C_POSITION_ENCODERS
#if ENABLED(I2C_POSITION_ENCODERS)
#define I2CPE_ENCODER_CNT 1 // The number of encoders installed; max of 5
// encoders supported currently.
#define I2CPE_ENC_1_ADDR I2CPE_PRESET_ADDR_X // I2C address of the encoder. 30-200.
#define I2CPE_ENC_1_AXIS X_AXIS // Axis the encoder module is installed on. <X|Y|Z|E>_AXIS.
#define I2CPE_ENC_1_TYPE I2CPE_ENC_TYPE_LINEAR // Type of encoder: I2CPE_ENC_TYPE_LINEAR -or-
// I2CPE_ENC_TYPE_ROTARY.
#define I2CPE_ENC_1_TICKS_UNIT 2048 // 1024 for magnetic strips with 2mm poles; 2048 for
// 1mm poles. For linear encoders this is ticks / mm,
// for rotary encoders this is ticks / revolution.
//#define I2CPE_ENC_1_TICKS_REV (16 * 200) // Only needed for rotary encoders; number of stepper
// steps per full revolution (motor steps/rev * microstepping)
//#define I2CPE_ENC_1_INVERT // Invert the direction of axis travel.
#define I2CPE_ENC_1_EC_METHOD I2CPE_ECM_MICROSTEP // Type of error error correction.
#define I2CPE_ENC_1_EC_THRESH 0.10 // Threshold size for error (in mm) above which the
// printer will attempt to correct the error; errors
// smaller than this are ignored to minimize effects of
// measurement noise / latency (filter).
#define I2CPE_ENC_2_ADDR I2CPE_PRESET_ADDR_Y // Same as above, but for encoder 2.
#define I2CPE_ENC_2_AXIS Y_AXIS
#define I2CPE_ENC_2_TYPE I2CPE_ENC_TYPE_LINEAR
#define I2CPE_ENC_2_TICKS_UNIT 2048
//#define I2CPE_ENC_2_TICKS_REV (16 * 200)
//#define I2CPE_ENC_2_INVERT
#define I2CPE_ENC_2_EC_METHOD I2CPE_ECM_MICROSTEP
#define I2CPE_ENC_2_EC_THRESH 0.10
#define I2CPE_ENC_3_ADDR I2CPE_PRESET_ADDR_Z // Encoder 3. Add additional configuration options
#define I2CPE_ENC_3_AXIS Z_AXIS // as above, or use defaults below.
#define I2CPE_ENC_4_ADDR I2CPE_PRESET_ADDR_E // Encoder 4.
#define I2CPE_ENC_4_AXIS E_AXIS
#define I2CPE_ENC_5_ADDR 34 // Encoder 5.
#define I2CPE_ENC_5_AXIS E_AXIS
// Default settings for encoders which are enabled, but without settings configured above.
#define I2CPE_DEF_TYPE I2CPE_ENC_TYPE_LINEAR
#define I2CPE_DEF_ENC_TICKS_UNIT 2048
#define I2CPE_DEF_TICKS_REV (16 * 200)
#define I2CPE_DEF_EC_METHOD I2CPE_ECM_NONE
#define I2CPE_DEF_EC_THRESH 0.1
//#define I2CPE_ERR_THRESH_ABORT 100.0 // Threshold size for error (in mm) error on any given
// axis after which the printer will abort. Comment out to
// disable abort behaviour.
#define I2CPE_TIME_TRUSTED 10000 // After an encoder fault, there must be no further fault
// for this amount of time (in ms) before the encoder
// is trusted again.
/**
* Position is checked every time a new command is executed from the buffer but during long moves,
* this setting determines the minimum update time between checks. A value of 100 works well with
* error rolling average when attempting to correct only for skips and not for vibration.
*/
#define I2CPE_MIN_UPD_TIME_MS 4 // (ms) Minimum time between encoder checks.
// Use a rolling average to identify persistant errors that indicate skips, as opposed to vibration and noise.
#define I2CPE_ERR_ROLLING_AVERAGE
#endif // I2C_POSITION_ENCODERS
/**
* MAX7219 Debug Matrix
*
* Add support for a low-cost 8x8 LED Matrix based on the Max7219 chip as a realtime status display.
* Requires 3 signal wires. Some useful debug options are included to demonstrate its usage.
*/
//#define MAX7219_DEBUG
#if ENABLED(MAX7219_DEBUG)
#define MAX7219_CLK_PIN 64
#define MAX7219_DIN_PIN 57
#define MAX7219_LOAD_PIN 44
//#define MAX7219_GCODE // Add the M7219 G-code to control the LED matrix
#define MAX7219_INIT_TEST 2 // Do a test pattern at initialization (Set to 2 for spiral)
#define MAX7219_NUMBER_UNITS 1 // Number of Max7219 units in chain.
#define MAX7219_ROTATE 0 // Rotate the display clockwise (in multiples of +/- 90°)
// connector at: right=0 bottom=-90 top=90 left=180
//#define MAX7219_REVERSE_ORDER // The individual LED matrix units may be in reversed order
/**
* Sample debug features
* If you add more debug displays, be careful to avoid conflicts!
*/
#define MAX7219_DEBUG_PRINTER_ALIVE // Blink corner LED of 8x8 matrix to show that the firmware is functioning
#define MAX7219_DEBUG_PLANNER_HEAD 3 // Show the planner queue head position on this and the next LED matrix row
#define MAX7219_DEBUG_PLANNER_TAIL 5 // Show the planner queue tail position on this and the next LED matrix row
#define MAX7219_DEBUG_PLANNER_QUEUE 0 // Show the current planner queue depth on this and the next LED matrix row
// If you experience stuttering, reboots, etc. this option can reveal how
// tweaks made to the configuration are affecting the printer in real-time.
#endif
/**
* NanoDLP Sync support
*
* Add support for Synchronized Z moves when using with NanoDLP. G0/G1 axis moves will output "Z_move_comp"
* string to enable synchronization with DLP projector exposure. This change will allow to use
* [[WaitForDoneMessage]] instead of populating your gcode with M400 commands
*/
//#define NANODLP_Z_SYNC
#if ENABLED(NANODLP_Z_SYNC)
//#define NANODLP_ALL_AXIS // Enables "Z_move_comp" output on any axis move.
// Default behaviour is limited to Z axis only.
#endif
/**
* WiFi Support (Espressif ESP32 WiFi)
*/
//#define WIFISUPPORT
#if ENABLED(WIFISUPPORT)
#define WIFI_SSID "Wifi SSID"
#define WIFI_PWD "Wifi Password"
#endif
/**
* Prusa Multi-Material Unit v2
* Enable in Configuration.h
*/
#if ENABLED(PRUSA_MMU2)
// Serial port used for communication with MMU2.
// For AVR enable the UART port used for the MMU. (e.g., internalSerial)
// For 32-bit boards check your HAL for available serial ports. (e.g., Serial2)
#define INTERNAL_SERIAL_PORT 2
#define MMU2_SERIAL internalSerial
// Use hardware reset for MMU if a pin is defined for it
//#define MMU2_RST_PIN 23
// Enable if the MMU2 has 12V stepper motors (MMU2 Firmware 1.0.2 and up)
//#define MMU2_MODE_12V
// G-code to execute when MMU2 F.I.N.D.A. probe detects filament runout
#define MMU2_FILAMENT_RUNOUT_SCRIPT "M600"
// Add an LCD menu for MMU2
//#define MMU2_MENUS
#if ENABLED(MMU2_MENUS)
// Settings for filament load / unload from the LCD menu.
// This is for Prusa MK3-style extruders. Customize for your hardware.
#define MMU2_FILAMENTCHANGE_EJECT_FEED 80.0
#define MMU2_LOAD_TO_NOZZLE_SEQUENCE \
{ 7.2, 562 }, \
{ 14.4, 871 }, \
{ 36.0, 1393 }, \
{ 14.4, 871 }, \
{ 50.0, 198 }
#define MMU2_RAMMING_SEQUENCE \
{ 1.0, 1000 }, \
{ 1.0, 1500 }, \
{ 2.0, 2000 }, \
{ 1.5, 3000 }, \
{ 2.5, 4000 }, \
{ -15.0, 5000 }, \
{ -14.0, 1200 }, \
{ -6.0, 600 }, \
{ 10.0, 700 }, \
{ -10.0, 400 }, \
{ -50.0, 2000 }
#endif
//#define MMU2_DEBUG // Write debug info to serial output
#endif // PRUSA_MMU2
/**
* Advanced Print Counter settings
*/
#if ENABLED(PRINTCOUNTER)
#define SERVICE_WARNING_BUZZES 3
// Activate up to 3 service interval watchdogs
//#define SERVICE_NAME_1 "Service S"
//#define SERVICE_INTERVAL_1 100 // print hours
//#define SERVICE_NAME_2 "Service L"
//#define SERVICE_INTERVAL_2 200 // print hours
//#define SERVICE_NAME_3 "Service 3"
//#define SERVICE_INTERVAL_3 1 // print hours
#endif
// @section develop
/**
* M43 - display pin status, watch pins for changes, watch endstops & toggle LED, Z servo probe test, toggle pins
*/
//#define PINS_DEBUGGING
// Enable Marlin dev mode which adds some special commands
//#define MARLIN_DEV_MODE
|
blole/Marlin
|
config/examples/Creality/CR-10/Configuration_adv.h
|
C
|
gpl-3.0
| 92,039
|
package net.fe.lobbystage;
import java.util.List;
import net.fe.FEMultiplayer;
import net.fe.FEResources;
import net.fe.network.message.ChatMessage;
import org.lwjgl.input.Keyboard;
import org.newdawn.slick.Color;
import chu.engine.Game;
import chu.engine.KeyboardEvent;
import chu.engine.MouseEvent;
import chu.engine.anim.AudioPlayer;
import chu.engine.anim.BitmapFont;
import chu.engine.anim.Renderer;
import chu.engine.menu.TextInputBox;
public class LobbyChatBox extends TextInputBox {
private static final Color UNFOCUSED = new Color(0x58543c);
private static final Color FOCUSED = new Color(0x817b58);
private static final Color CURSOR = new Color(0xeeeeee);
public LobbyChatBox() {
super(6, 294, 250, 20, "default_med");
}
public void beginStep() {
List<MouseEvent> mouseEvents = Game.getMouseEvents();
for(MouseEvent event : mouseEvents) {
if(event.button == 0) {
int mX = Math.round(event.x / Game.getScaleX());
int mY = Math.round((Game.getWindowHeight() - event.y) / Game.getScaleY());
boolean newHover = (mX >= x && mX < x + width && mY >= y && mY < y + height);
hasFocus = newHover;
}
}
super.beginStep();
if(hasFocus) {
List<KeyboardEvent> keys = Game.getKeys();
for(KeyboardEvent ke : keys) {
if(ke.state) {
if(ke.key == FEResources.getKeyMapped(Keyboard.KEY_RETURN)) {
send();
}
}
}
}
}
public void render() {
BitmapFont font = FEResources.getBitmapFont("default_med");
if(hasFocus) {
Renderer.drawRectangle(x, y, x+width, y+height, renderDepth, FOCUSED);
float linepos = x + font.getStringWidth(input.substring(0, cursorPos)) + 2;
Renderer.drawRectangle(linepos, y+1, linepos+1, y+height-1, renderDepth-0.02f, CURSOR);
} else {
Renderer.drawRectangle(x, y, x+width, y+height, renderDepth, UNFOCUSED);
}
Renderer.drawString("default_med", input.toString(), x+2, y+5, renderDepth-0.01f);
}
public void send() {
if(input.length() == 0) return;
AudioPlayer.playAudio("cancel");
byte id = FEMultiplayer.getClient().getID();
FEMultiplayer.getClient().sendMessage(
new ChatMessage(id, input.toString()));
input.delete(0, input.length());
cursorPos = 0;
}
}
|
Pwntagonist/FEMultiPlayer-V2
|
src/net/fe/lobbystage/LobbyChatBox.java
|
Java
|
gpl-3.0
| 2,201
|
namespace OmniXaml.NewAssembler.Commands
{
public class EndObjectCommand : Command
{
public EndObjectCommand(SuperObjectAssembler assembler) : base(assembler)
{
}
public override void Execute()
{
if (!StateCommuter.IsGetObject)
{
StateCommuter.CreateInstanceOfCurrentXamlTypeIfNotCreatedBefore();
if (StateCommuter.Instance is IMarkupExtension)
{
StateCommuter.Instance = StateCommuter.GetValueProvidedByMarkupExtension((IMarkupExtension)StateCommuter.Instance);
StateCommuter.AssociateCurrentInstanceToParent();
}
else if (!StateCommuter.WasAssociatedRightAfterCreation)
{
StateCommuter.AssociateCurrentInstanceToParent();
}
}
Assembler.Result = StateCommuter.Instance;
StateCommuter.DecreaseLevel();
}
}
}
|
danwalmsley/OmniXaml
|
OmniXaml/OmniXaml/NewAssembler/Commands/EndObjectCommand.cs
|
C#
|
gpl-3.0
| 1,002
|
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM - Open Source CRM application.
* Copyright (C) 2014-2021 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* Website: https://www.espocrm.com
*
* EspoCRM 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.
*
* EspoCRM 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 EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Classes\Acl\User;
use Espo\Entities\User;
use Espo\ORM\Entity;
use Espo\Core\{
Acl\OwnershipOwnChecker,
Acl\OwnershipTeamChecker,
};
class OwnershipChecker implements OwnershipOwnChecker, OwnershipTeamChecker
{
public function checkOwn(User $user, Entity $entity): bool
{
return $user->getId() === $entity->getId();
}
public function checkTeam(User $user, Entity $entity): bool
{
$intersect = array_intersect(
$user->getLinkMultipleIdList('teams'),
$entity->getLinkMultipleIdList('teams')
);
if (count($intersect)) {
return true;
}
return false;
}
}
|
ayman-alkom/espocrm
|
application/Espo/Classes/Acl/User/OwnershipChecker.php
|
PHP
|
gpl-3.0
| 2,051
|
package ca.on.oicr.pinery.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
/**
* Subtypes of this class should offer methods for retrieving their resource type from Pinery by
* levereging the {@link #getResource(String) getResource} and {@link #getResourceList(String)
* getResourceList} methods. This class relies on its associated PineryClient to make the actual GET
* requests, and provides the type specification needed between the PineryClient and subtype.
*
* @author dcooke
* @param <T> The type of resource that this client will retrieve from Pinery
*/
public abstract class ResourceClient<T> {
private final Class<T> resourceClass;
private final Class<T[]> arrayClass;
private final PineryClient mainClient;
/**
* Creates a ResourceClient for retrieving a specific resource (object) type from Pinery
*
* @param resourceClass class of resource to retrieve
* @param arrayClass resource array class
* @param mainClient the PineryClient, which will make the actual requests
*/
public ResourceClient(Class<T> resourceClass, Class<T[]> arrayClass, PineryClient mainClient) {
if (resourceClass == null) throw new IllegalArgumentException("Resource class cannot be null");
if (arrayClass == null) throw new IllegalArgumentException("Array class cannot be null");
if (mainClient == null) throw new IllegalArgumentException("PineryClient cannot be null");
this.resourceClass = resourceClass;
this.arrayClass = arrayClass;
this.mainClient = mainClient;
}
/**
* Retrieve a single resource (object) from Pinery
*
* @param resourceUrl the resource URL, relative to the base Pinery URL
* @return the requested resource
* @throws HttpResponseException on any HTTP Status other than 200 OK
*/
protected T getResource(String resourceUrl) throws HttpResponseException {
Response response = null;
try {
response = mainClient.callPinery(resourceUrl);
T resource = response.readEntity(resourceClass);
if (resource == null) {
// The server should really return a 404 error if a specific resource isn't found
throw new HttpResponseException(resourceUrl, Status.NOT_FOUND.getStatusCode());
}
return resource;
} finally {
if (response != null) response.close();
}
}
/**
* Retrieve multiple resources (objects) from Pinery
*
* @param resourceUrl the resource URL, relative to the base Pinery URL
* @return the requested resources, or an empty list if no resources of the requested type are
* available
* @throws HttpResponseException on any HTTP Status other than 200 OK
*/
protected List<T> getResourceList(String resourceUrl) throws HttpResponseException {
Response response = null;
try {
response = mainClient.callPinery(resourceUrl);
T[] entities = response.readEntity(arrayClass);
if (entities == null || entities.length == 0) {
return new ArrayList<T>();
} else {
return Arrays.asList(entities);
}
} finally {
if (response != null) response.close();
}
}
}
|
oicr-gsi/pinery
|
pinery-client/src/main/java/ca/on/oicr/pinery/client/ResourceClient.java
|
Java
|
gpl-3.0
| 3,215
|
<?php
/* ----------------------------------------------------------------------
* views/Browse/browse_results_images_html.php :
* ----------------------------------------------------------------------
* CollectiveAccess
* Open-source collections management software
* ----------------------------------------------------------------------
*
* Software by Whirl-i-Gig (http://www.whirl-i-gig.com)
* Copyright 2014 Whirl-i-Gig
*
* For more information visit http://www.CollectiveAccess.org
*
* This program is free software; you may redistribute it and/or modify it under
* the terms of the provided license as published by Whirl-i-Gig
*
* CollectiveAccess is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* This source code is free and modifiable under the terms of
* GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See
* the "license.txt" file for details, or visit the CollectiveAccess web site at
* http://www.CollectiveAccess.org
*
* ----------------------------------------------------------------------
*/
$qr_res = $this->getVar('result'); // browse results (subclass of SearchResult)
$va_facets = $this->getVar('facets'); // array of available browse facets
$va_criteria = $this->getVar('criteria'); // array of browse criteria
$vs_browse_key = $this->getVar('key'); // cache key for current browse
$va_access_values = $this->getVar('access_values'); // list of access values for this user
$vn_hits_per_block = (int)$this->getVar('hits_per_block'); // number of hits to display per block
$vn_start = (int)$this->getVar('start'); // offset to seek to before outputting results
$va_views = $this->getVar('views');
$vs_current_view = $this->getVar('view');
$va_view_icons = $this->getVar('viewIcons');
$vs_current_sort = $this->getVar('sort');
$t_instance = $this->getVar('t_instance');
$vs_table = $this->getVar('table');
$vs_pk = $this->getVar('primaryKey');
$va_access_values = caGetUserAccessValues($this->request);
$o_config = $this->getVar("config");
$va_options = $this->getVar('options');
$vs_extended_info_template = caGetOption('extendedInformationTemplate', $va_options, null);
$vb_ajax = (bool)$this->request->isAjax();
$o_lightbox_config = caGetLightboxConfig();
$vs_lightbox_icon = $o_lightbox_config->get("addToLightboxIcon");
if(!$vs_lightbox_icon){
$vs_lightbox_icon = "<i class='fa fa-suitcase'></i>";
}
if(!($vs_placeholder = $o_config->get("placeholder_media_icon"))){
$vs_placeholder = "<i class='fa fa-picture-o fa-2x'></i>";
}
$vs_placeholder_tag = "<div class='bResultItemImgPlaceholder'>".$vs_placeholder."</div>";
$vn_col_span = 3;
$vn_col_span_sm = 4;
$vn_col_span_sm = 2;
$vb_refine = false;
if(is_array($va_facets) && sizeof($va_facets)){
$vb_refine = true;
$vn_col_span = 3;
$vn_col_span_sm = 6;
$vn_col_span_xs = 6;
}
if ($vn_start < $qr_res->numHits()) {
$vn_c = 0;
$qr_res->seek($vn_start);
if ($vs_table != 'ca_objects') {
$va_ids = array();
while($qr_res->nextHit() && ($vn_c < $vn_hits_per_block)) {
$va_ids[] = $qr_res->get($vs_pk);
$vn_c++;
}
$va_images = caGetDisplayImagesForAuthorityItems($vs_table, $va_ids, array('version' => 'small', 'relationshipTypes' => caGetOption('selectMediaUsingRelationshipTypes', $va_options, null), 'checkAccess' => $va_access_values));
$vn_c = 0;
$qr_res->seek($vn_start);
}
$vs_add_to_lightbox_msg = addslashes(_t('Add to lightbox'));
while($qr_res->nextHit() && ($vn_c < $vn_hits_per_block)) {
$vn_id = $qr_res->get("{$vs_table}.{$vs_pk}");
$vs_idno_detail_link = caDetailLink($this->request, $qr_res->get("{$vs_table}.idno"), '', $vs_table, $vn_id, array("subsite" => $this->request->session->getVar("coloradoSubSite")));
$vs_label_detail_link = caDetailLink($this->request, $qr_res->get("{$vs_table}.preferred_labels.name"), '', $vs_table, $vn_id, array("subsite" => $this->request->session->getVar("coloradoSubSite")));
$vs_thumbnail = "";
if ($vs_table == 'ca_objects') {
if(!($vs_thumbnail = $qr_res->getMediaTag('ca_object_representations.media', 'medium', array("checkAccess" => $va_access_values)))){
$vs_thumbnail = $vs_placeholder_tag;
}
$vs_rep_detail_link = caDetailLink($this->request, $vs_thumbnail, '', $vs_table, $vn_id, array("subsite" => $this->request->session->getVar("coloradoSubSite")));
} else {
if($va_images[$vn_id]){
$vs_thumbnail = $va_images[$vn_id];
}else{
$vs_thumbnail = $vs_placeholder_tag;
}
$vs_rep_detail_link = caDetailLink($this->request, $vs_thumbnail, '', $vs_table, $vn_id, array("subsite" => $this->request->session->getVar("coloradoSubSite")));
}
$vs_add_to_set_url = caNavUrl($this->request, '', 'Lightbox', 'addItemForm', array($vs_pk => $vn_id));
$vs_expanded_info = $qr_res->getWithTemplate($vs_extended_info_template);
print "
<div class='bResultItemCol col-xs-{$vn_col_span_xs} col-sm-{$vn_col_span_sm} col-md-{$vn_col_span}'>
<div class='bResultItem' onmouseover='jQuery(\"#bResultItemExpandedInfo{$vn_id}\").show();' onmouseout='jQuery(\"#bResultItemExpandedInfo{$vn_id}\").hide();'>
<div class='bResultItemContent'><div class='text-center bResultItemImg'>{$vs_rep_detail_link}</div>
<div class='bResultItemText'>
<small>{$vs_idno_detail_link}</small><br/>{$vs_label_detail_link}
</div><!-- end bResultItemText -->
</div><!-- end bResultItemContent -->
<div class='bResultItemExpandedInfo' id='bResultItemExpandedInfo{$vn_id}'>
<hr>
{$vs_expanded_info}
".(($this->request->config->get("disable_lightbox")) ? "" : "<a href='#' onclick='caMediaPanel.showPanel(\"{$vs_add_to_set_url}\"); return false;' title='{$vs_add_to_lightbox_msg}'>".$vs_lightbox_icon."</i></a>")."
</div><!-- bResultItemExpandedInfo -->
</div><!-- end bResultItem -->
</div><!-- end col -->";
$vn_c++;
}
print caNavLink($this->request, _t('Next %1', $vn_hits_per_block), 'jscroll-next', '*', '*', '*', array('s' => $vn_start + $vn_hits_per_block, 'key' => $vs_browse_key, 'view' => $vs_current_view));
}
?>
|
libis/pa_cct
|
themes/colorado/views/Browse/browse_results_images_html.php
|
PHP
|
gpl-3.0
| 6,352
|
<div class="result">
<div class="search">
<h1>Search [Hit "Enter"]</h1>
<p>
Search Library for: "{{ meta.query }}"
</p>
</div>
<div class="listing">
{% for item in objects %}
<div class="item linkable hoverable">
<div class="row-fluid">
<div class="span2">
<img src="{{ item.main_image }}" />
</div>
<div class="span10">
<a href="{{ item.get_absolute_url }}" class="link-main"><h2>{{ item.name|highlight(meta.query) }}</h2></a>
<div class="related">
{% if item.media|length > 0 %} <span>Tracks:</span>
<ul class="horizontal">
{% for media in item.media %}
<li>
<a href="{{ media.get_absolute_url}}">{{ media.name|highlight(meta.query) }} | {{ media.artist|highlight(meta.query) }}</a>
{% if not loop.last %},{% endif %}
</li>
{% if loop.last %}
<div class="clear"></div>
{% endif %}
{% endfor %}
</ul>
{% endif %}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
|
hzlf/openbroadcast
|
website/apps/alibrary/static/alibrary/nj/release/autocomplete.html
|
HTML
|
gpl-3.0
| 1,073
|
/*
* Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ru.apertum.qsystem.server.model;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import javax.swing.AbstractListModel;
/**
* Список услуг, обрабатываемых пользователем. Класс - рулит списком услуг юзера. Должен строиться для каждого юзера и он же должен отображаться в админской
* проге. Элементы списка это QPlanService. Пока пустой. Нужен для того чтобы при необходимости чот-то переопределить.
*
* List of services to be processed by the user. Class - steers list of services user. Should be built for each user and it should be displayed in admin
* Proge. List items are QPlanService. While empty. It is necessary to redefine if necessary.
* @author Evgeniy Egorov
*/
public class QPlanServiceList extends AbstractListModel implements List {
private final List<QPlanService> services;
public List<QPlanService> getServices() {
return services;
}
public QPlanServiceList(List<QPlanService> services) {
this.services = services;
}
@Override
public int getSize() {
return services.size();
}
@Override
public Object getElementAt(int index) {
return services.get(index);
}
public boolean removeElement(QPlanService obj) {
final int index = services.indexOf(obj);
final boolean res = services.remove(obj);
fireIntervalRemoved(this, index, index);
return res;
}
public void addElement(QPlanService obj) {
final int index = services.size();
services.add(obj);
fireIntervalAdded(this, index, index);
}
@Override
public int size() {
return getSize();
}
@Override
public boolean isEmpty() {
return getSize() == 0;
}
@Override
public boolean contains(Object o) {
return services.contains(o);
}
@Override
public Iterator iterator() {
return services.iterator();
}
@Override
public QPlanService[] toArray() {
return (QPlanService[]) services.toArray();
}
@Override
public boolean add(Object e) {
return services.add((QPlanService) e);
}
@Override
public boolean remove(Object o) {
return services.remove((QPlanService) o);
}
@Override
public boolean containsAll(Collection c) {
return services.containsAll(c);
}
@Override
public boolean addAll(Collection c) {
return services.addAll(c);
}
@Override
public boolean addAll(int index, Collection c) {
return services.addAll(index, c);
}
@Override
public boolean removeAll(Collection c) {
return services.removeAll(c);
}
@Override
public boolean retainAll(Collection c) {
return services.retainAll(c);
}
@Override
public void clear() {
services.clear();
}
@Override
public QPlanService get(int index) {
return services.get(index);
}
@Override
public QPlanService set(int index, Object element) {
return services.set(index, (QPlanService) element);
}
@Override
public void add(int index, Object element) {
services.add(index, (QPlanService) element);
}
@Override
public QPlanService remove(int index) {
return services.remove(index);
}
@Override
public int indexOf(Object o) {
return services.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return services.lastIndexOf(o);
}
@Override
public ListIterator listIterator() {
return services.listIterator();
}
@Override
public ListIterator listIterator(int index) {
return services.listIterator(index);
}
@Override
public List subList(int fromIndex, int toIndex) {
return services.subList(fromIndex, toIndex);
}
@Override
public QPlanService[] toArray(Object[] a) {
return (QPlanService[]) services.toArray(a);
}
}
|
jasmeet17/sbc-qsystem
|
QSystem/src/ru/apertum/qsystem/server/model/QPlanServiceList.java
|
Java
|
gpl-3.0
| 4,987
|
'use strict';
var async = require('async'),
validator = require('validator'),
url = require('url'),
S = require('string'),
utils = require('../../public/src/utils'),
meta = require('../meta'),
events = require('../events'),
db = require('../database'),
Password = require('../password'),
plugins = require('../plugins');
module.exports = function(User) {
User.updateProfile = function(uid, data, callback) {
var fields = ['username', 'email', 'fullname', 'website', 'location', 'birthday', 'signature'];
plugins.fireHook('filter:user.updateProfile', {uid: uid, data: data, fields: fields}, function(err, data) {
if (err) {
return callback(err);
}
fields = data.fields;
data = data.data;
function isSignatureValid(next) {
if (data.signature !== undefined && data.signature.length > meta.config.maximumSignatureLength) {
next(new Error('[[error:signature-too-long, ' + meta.config.maximumSignatureLength + ']]'));
} else {
next();
}
}
function isEmailAvailable(next) {
if (!data.email) {
return next();
}
if (!utils.isEmailValid(data.email)) {
return next(new Error('[[error:invalid-email]]'));
}
User.getUserField(uid, 'email', function(err, email) {
if(email === data.email) {
return next();
}
User.email.available(data.email, function(err, available) {
if (err) {
return next(err);
}
next(!available ? new Error('[[error:email-taken]]') : null);
});
});
}
function isUsernameAvailable(next) {
if (!data.username) {
return next();
}
User.getUserFields(uid, ['username', 'userslug'], function(err, userData) {
var userslug = utils.slugify(data.username);
if(userslug === userData.userslug) {
return next();
}
if (data.username.length < meta.config.minimumUsernameLength) {
return next(new Error('[[error:username-too-short]]'));
}
if (data.username.length > meta.config.maximumUsernameLength) {
return next(new Error('[[error:username-too-long]]'));
}
if(!utils.isUserNameValid(data.username) || !userslug) {
return next(new Error('[[error:invalid-username]]'));
}
User.exists(userslug, function(err, exists) {
if(err) {
return next(err);
}
next(exists ? new Error('[[error:username-taken]]') : null);
});
});
}
async.series([isSignatureValid, isEmailAvailable, isUsernameAvailable], function(err, results) {
if (err) {
return callback(err);
}
async.each(fields, updateField, function(err) {
if (err) {
return callback(err);
}
plugins.fireHook('action:user.updateProfile', {data: data, uid: uid});
User.getUserFields(uid, ['email', 'username', 'userslug', 'picture', 'gravatarpicture'], callback);
});
});
function updateField(field, next) {
if (!(data[field] !== undefined && typeof data[field] === 'string')) {
return next();
}
data[field] = data[field].trim();
if (field === 'email') {
return updateEmail(uid, data.email, next);
} else if (field === 'username') {
return updateUsername(uid, data.username, next);
} else if (field === 'fullname') {
return updateFullname(uid, data.fullname, next);
} else if (field === 'signature') {
data[field] = S(data[field]).stripTags().s;
} else if (field === 'website') {
if (data[field].length > 0) {
var urlObj = url.parse(data[field], false, true);
if (!urlObj.protocol) {
urlObj.protocol = 'http';
urlObj.slashes = true;
}
if (!urlObj.hostname && urlObj.pathname) {
urlObj.hostname = urlObj.pathname;
urlObj.pathname = null;
}
if (urlObj.pathname === '/') {
urlObj.pathname = null;
}
}
data[field] = url.format(urlObj);
}
User.setUserField(uid, field, data[field], next);
}
});
};
function updateEmail(uid, newEmail, callback) {
User.getUserFields(uid, ['email', 'picture', 'uploadedpicture'], function(err, userData) {
if (err) {
return callback(err);
}
userData.email = userData.email || '';
if (userData.email === newEmail) {
return callback();
}
db.deleteObjectField('email:uid', userData.email.toLowerCase(), function(err) {
if (err) {
return callback(err);
}
var gravatarpicture = User.createGravatarURLFromEmail(newEmail);
async.parallel([
function(next) {
User.setUserField(uid, 'gravatarpicture', gravatarpicture, next);
},
function(next) {
db.setObjectField('email:uid', newEmail.toLowerCase(), uid, next);
},
function(next) {
User.setUserField(uid, 'email', newEmail, next);
},
function(next) {
if (parseInt(meta.config.requireEmailConfirmation, 10) === 1 && newEmail) {
User.email.sendValidationEmail(uid, newEmail);
}
User.setUserField(uid, 'email:confirmed', 0, next);
},
function(next) {
if (userData.picture !== userData.uploadedpicture) {
User.setUserField(uid, 'picture', gravatarpicture, next);
} else {
next();
}
},
], callback);
});
});
}
function updateUsername(uid, newUsername, callback) {
if (!newUsername) {
return callback();
}
User.getUserFields(uid, ['username', 'userslug'], function(err, userData) {
function update(field, object, value, callback) {
async.series([
function(next) {
db.deleteObjectField(field + ':uid', userData[field], next);
},
function(next) {
User.setUserField(uid, field, value, next);
},
function(next) {
db.setObjectField(object, value, uid, next);
}
], callback);
}
if (err) {
return callback(err);
}
async.parallel([
function(next) {
if (newUsername === userData.username) {
return next();
}
update('username', 'username:uid', newUsername, next);
},
function(next) {
var newUserslug = utils.slugify(newUsername);
if (newUserslug === userData.userslug) {
return next();
}
update('userslug', 'userslug:uid', newUserslug, next);
}
], callback);
});
}
function updateFullname(uid, newFullname, callback) {
async.waterfall([
function(next) {
User.getUserField(uid, 'fullname', next);
},
function(fullname, next) {
if (newFullname === fullname) {
return callback();
}
db.deleteObjectField('fullname:uid', fullname, next);
},
function(next) {
User.setUserField(uid, 'fullname', newFullname, next);
},
function(next) {
if (newFullname) {
db.setObjectField('fullname:uid', newFullname, uid, next);
} else {
next();
}
}
], callback);
}
User.changePassword = function(uid, data, callback) {
if (!uid || !data || !data.uid) {
return callback(new Error('[[error:invalid-uid]]'));
}
function hashAndSetPassword(callback) {
User.hashPassword(data.newPassword, function(err, hash) {
if (err) {
return callback(err);
}
async.parallel([
async.apply(User.setUserField, data.uid, 'password', hash),
async.apply(User.reset.updateExpiry, data.uid)
], callback);
});
}
if (!utils.isPasswordValid(data.newPassword)) {
return callback(new Error('[[user:change_password_error]]'));
}
if(parseInt(uid, 10) !== parseInt(data.uid, 10)) {
User.isAdministrator(uid, function(err, isAdmin) {
if(err || !isAdmin) {
return callback(err || new Error('[[user:change_password_error_privileges'));
}
hashAndSetPassword(callback);
});
} else {
db.getObjectField('user:' + uid, 'password', function(err, currentPassword) {
if(err) {
return callback(err);
}
if (!currentPassword) {
return hashAndSetPassword(callback);
}
Password.compare(data.currentPassword, currentPassword, function(err, res) {
if (err || !res) {
return callback(err || new Error('[[user:change_password_error_wrong_current]]'));
}
hashAndSetPassword(callback);
});
});
}
};
};
|
HanRJ/mooc
|
src/user/profile.js
|
JavaScript
|
gpl-3.0
| 8,118
|
button {
padding : 8px 16px;
color : white;
background: -webkit-linear-gradient(red,white 10%,red 80%);
border-radius: 7px;
border : none;
outline none;
margin-top : 3px;
}
button:active {
background: -webkit-linear-gradient(rgba(255,0,0,0.3),red,white,red);
box-shadow: 0 12px 16px 0 rgba(0,0,0,0.24), 0 17px 50px 0 rgba(0,0,0,0.19);
}
.modal-content {
background-color: rgba(0,0,0,0.8);
color : white;
padding: 2%;
border: 1px solid #888;
border-radius: 8px;
font-family: "Bookman Old Style";
}
#dialog {
position: fixed;
top : 0;
left : 0;
margin-right: 15%;
margin-left: 15%;
border-radius: 8px;
background-color: rgba(0,0,0,0.3);
width : 70%;
padding : 15px;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
}
.status-bar {
position: fixed;
bottom: 0;
left 0;
width : 100%;
background-color: lightgreen;
color : green;
padding: 5px;
font-size : 14px;
font-family: "Courier";
border-top : 2px solid green;
}
.status-bar span {
display: block;
}
body {
padding: 0;
margin : 0;
}
@-webkit-keyframes scrollDown {from {margin-top: 0%; opacity: 0} to {margin-top: 18%; opacity: 1}}
.scroll-down {
margin-top: 0%;
opacity: 0;
-webkit-animation : scrollDown ease-in 1;
-webkit-animation-fill-mode:forwards;
-webkit-animation-duration : 0.3s;
}
.scroll-down.scroll {
-webkit-animation-delay: 0.2s;
}
|
SwapnilB31/SQLNavigator
|
temp/dialog.css
|
CSS
|
gpl-3.0
| 1,517
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:21 EEST 2016 -->
<title>Uses of Interface net.sf.jasperreports.engine.fill.JRFillCloneable (JasperReports 6.3.0 API)</title>
<meta name="date" content="2016-06-20">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface net.sf.jasperreports.engine.fill.JRFillCloneable (JasperReports 6.3.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?net/sf/jasperreports/engine/fill/class-use/JRFillCloneable.html" target="_top">Frames</a></li>
<li><a href="JRFillCloneable.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface net.sf.jasperreports.engine.fill.JRFillCloneable" class="title">Uses of Interface<br>net.sf.jasperreports.engine.fill.JRFillCloneable</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.iconlabel">net.sf.jasperreports.components.iconlabel</a></td>
<td class="colLast">
<div class="block">Contains classes for the built-in Icon Label component.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.list">net.sf.jasperreports.components.list</a></td>
<td class="colLast">
<div class="block">Contains classes for the built-in List component.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.sort">net.sf.jasperreports.components.sort</a></td>
<td class="colLast">
<div class="block">Contains classes for the built-in Sort component.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.spiderchart">net.sf.jasperreports.components.spiderchart</a></td>
<td class="colLast">
<div class="block">Contains classes for the built-in Spider Chart component.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="#net.sf.jasperreports.components.table.fill">net.sf.jasperreports.components.table.fill</a></td>
<td class="colLast">
<div class="block">Contains fill time implementations for Table component related interfaces.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#net.sf.jasperreports.engine.fill">net.sf.jasperreports.engine.fill</a></td>
<td class="colLast">
<div class="block">Contains fill time implementations for the library's main interfaces and the entire
engine used in the filling process (the actual core of JasperReports).</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sf.jasperreports.components.iconlabel">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> in <a href="../../../../../../net/sf/jasperreports/components/iconlabel/package-summary.html">net.sf.jasperreports.components.iconlabel</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/components/iconlabel/package-summary.html">net.sf.jasperreports.components.iconlabel</a> that return <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">IconLabelComponentFill.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/iconlabel/IconLabelComponentFill.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.components.list">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> in <a href="../../../../../../net/sf/jasperreports/components/list/package-summary.html">net.sf.jasperreports.components.list</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/components/list/package-summary.html">net.sf.jasperreports.components.list</a> that implement <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/BaseFillList.html" title="class in net.sf.jasperreports.components.list">BaseFillList</a></strong></code>
<div class="block">Base fill list component implementation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/FillListContents.html" title="class in net.sf.jasperreports.components.list">FillListContents</a></strong></code>
<div class="block">List contents fill element container.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/HorizontalFillList.html" title="class in net.sf.jasperreports.components.list">HorizontalFillList</a></strong></code>
<div class="block">Horizontal fill list component implementation.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/VerticalFillList.html" title="class in net.sf.jasperreports.components.list">VerticalFillList</a></strong></code>
<div class="block">Vertical fill list component implementation.</div>
</td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/components/list/package-summary.html">net.sf.jasperreports.components.list</a> that return <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">VerticalFillList.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/VerticalFillList.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">HorizontalFillList.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/HorizontalFillList.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">FillListContents.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/list/FillListContents.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.components.sort">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> in <a href="../../../../../../net/sf/jasperreports/components/sort/package-summary.html">net.sf.jasperreports.components.sort</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/components/sort/package-summary.html">net.sf.jasperreports.components.sort</a> that return <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">SortComponentFill.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/sort/SortComponentFill.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.components.spiderchart">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> in <a href="../../../../../../net/sf/jasperreports/components/spiderchart/package-summary.html">net.sf.jasperreports.components.spiderchart</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/components/spiderchart/package-summary.html">net.sf.jasperreports.components.spiderchart</a> that implement <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/spiderchart/FillSpiderChart.html" title="class in net.sf.jasperreports.components.spiderchart">FillSpiderChart</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/components/spiderchart/package-summary.html">net.sf.jasperreports.components.spiderchart</a> that return <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">FillSpiderChart.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/spiderchart/FillSpiderChart.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.components.table.fill">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> in <a href="../../../../../../net/sf/jasperreports/components/table/fill/package-summary.html">net.sf.jasperreports.components.table.fill</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/components/table/fill/package-summary.html">net.sf.jasperreports.components.table.fill</a> that implement <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/components/table/fill/FillTableSubreport.html" title="class in net.sf.jasperreports.components.table.fill">FillTableSubreport</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/components/table/fill/package-summary.html">net.sf.jasperreports.components.table.fill</a> that return <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">FillTableSubreport.</span><code><strong><a href="../../../../../../net/sf/jasperreports/components/table/fill/FillTableSubreport.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.engine.fill">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> in <a href="../../../../../../net/sf/jasperreports/engine/fill/package-summary.html">net.sf.jasperreports.engine.fill</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../../net/sf/jasperreports/engine/fill/package-summary.html">net.sf.jasperreports.engine.fill</a> that implement <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillBand.html" title="class in net.sf.jasperreports.engine.fill">JRFillBand</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillBreak.html" title="class in net.sf.jasperreports.engine.fill">JRFillBreak</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCellContents.html" title="class in net.sf.jasperreports.engine.fill">JRFillCellContents</a></strong></code>
<div class="block">Crosstab cell contents filler.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillChart.html" title="class in net.sf.jasperreports.engine.fill">JRFillChart</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillComponentElement.html" title="class in net.sf.jasperreports.engine.fill">JRFillComponentElement</a></strong></code>
<div class="block">A <a href="../../../../../../net/sf/jasperreports/engine/JRComponentElement.html" title="interface in net.sf.jasperreports.engine"><code>JRComponentElement</code></a> which is used during report fill.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCrosstab.html" title="class in net.sf.jasperreports.engine.fill">JRFillCrosstab</a></strong></code>
<div class="block">Fill-time implementation of a <a href="../../../../../../net/sf/jasperreports/crosstabs/JRCrosstab.html" title="interface in net.sf.jasperreports.crosstabs"><code>crosstab</code></a>.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillElement.html" title="class in net.sf.jasperreports.engine.fill">JRFillElement</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillElementContainer.html" title="class in net.sf.jasperreports.engine.fill">JRFillElementContainer</a></strong></code>
<div class="block">Abstract implementation of an element container filler.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillElementGroup.html" title="class in net.sf.jasperreports.engine.fill">JRFillElementGroup</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillEllipse.html" title="class in net.sf.jasperreports.engine.fill">JRFillEllipse</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillFrame.html" title="class in net.sf.jasperreports.engine.fill">JRFillFrame</a></strong></code>
<div class="block">Fill time implementation of a frame element.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillFrame.JRFillFrameElements.html" title="class in net.sf.jasperreports.engine.fill">JRFillFrame.JRFillFrameElements</a></strong></code>
<div class="block">Frame element container filler.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillGenericElement.html" title="class in net.sf.jasperreports.engine.fill">JRFillGenericElement</a></strong></code>
<div class="block">A <a href="../../../../../../net/sf/jasperreports/engine/JRGenericElement.html" title="interface in net.sf.jasperreports.engine"><code>JRGenericElement</code></a> used during report fill.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillGraphicElement.html" title="class in net.sf.jasperreports.engine.fill">JRFillGraphicElement</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillImage.html" title="class in net.sf.jasperreports.engine.fill">JRFillImage</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillLine.html" title="class in net.sf.jasperreports.engine.fill">JRFillLine</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillRectangle.html" title="class in net.sf.jasperreports.engine.fill">JRFillRectangle</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillStaticText.html" title="class in net.sf.jasperreports.engine.fill">JRFillStaticText</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillSubreport.html" title="class in net.sf.jasperreports.engine.fill">JRFillSubreport</a></strong></code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillTextElement.html" title="class in net.sf.jasperreports.engine.fill">JRFillTextElement</a></strong></code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillTextField.html" title="class in net.sf.jasperreports.engine.fill">JRFillTextField</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/engine/fill/package-summary.html">net.sf.jasperreports.engine.fill</a> that return <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCellContents.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCellContents.html#createClone()">createClone</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillTextField.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillTextField.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillSubreport.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillSubreport.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillStaticText.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillStaticText.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillRectangle.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillRectangle.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillLine.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillLine.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillImage.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillImage.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillGenericElement.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillGenericElement.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillFrame.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillFrame.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillEllipse.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillEllipse.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillElementGroup.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillElementGroup.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCrosstab.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCrosstab.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillComponentElement.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillComponentElement.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCloneable.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code>
<div class="block">Creates a working clone of itself.</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillChart.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillChart.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCellContents.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCellContents.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillBreak.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillBreak.html#createClone(net.sf.jasperreports.engine.fill.JRFillCloneFactory)">createClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html" title="class in net.sf.jasperreports.engine.fill">JRFillCloneFactory</a> factory)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code>protected <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCloneFactory.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html#getCached(net.sf.jasperreports.engine.fill.JRFillCloneable)">getCached</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> original)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCloneFactory.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html#getClone(net.sf.jasperreports.engine.fill.JRFillCloneable)">getClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> original)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../net/sf/jasperreports/engine/fill/package-summary.html">net.sf.jasperreports.engine.fill</a> with parameters of type <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCloneFactory.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html#getCached(net.sf.jasperreports.engine.fill.JRFillCloneable)">getCached</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> original)</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></code></td>
<td class="colLast"><span class="strong">JRFillCloneFactory.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html#getClone(net.sf.jasperreports.engine.fill.JRFillCloneable)">getClone</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> original)</code> </td>
</tr>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><span class="strong">JRFillCloneFactory.</span><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneFactory.html#put(net.sf.jasperreports.engine.fill.JRFillCloneable,%20net.sf.jasperreports.engine.fill.JRFillCloneable)">put</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> original,
<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> clone)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../net/sf/jasperreports/engine/fill/package-summary.html">net.sf.jasperreports.engine.fill</a> with parameters of type <a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../../net/sf/jasperreports/engine/fill/JRClonePool.html#JRClonePool(net.sf.jasperreports.engine.fill.JRFillCloneable,%20boolean,%20boolean)">JRClonePool</a></strong>(<a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">JRFillCloneable</a> original,
boolean trackLockedClones,
boolean useOriginal)</code>
<div class="block">Creates a clone pool.</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../net/sf/jasperreports/engine/fill/JRFillCloneable.html" title="interface in net.sf.jasperreports.engine.fill">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?net/sf/jasperreports/engine/fill/class-use/JRFillCloneable.html" target="_top">Frames</a></li>
<li><a href="JRFillCloneable.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001 - 2016 TIBCO Software Inc. <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
|
MHTaleb/Encologim
|
lib/JasperReport/docs/api/net/sf/jasperreports/engine/fill/class-use/JRFillCloneable.html
|
HTML
|
gpl-3.0
| 45,802
|
# Makefile.in generated by automake 1.14.1 from Makefile.am.
# blueman/plugins/Makefile. Generated from Makefile.in by configure.
# Copyright (C) 1994-2013 Free Software Foundation, Inc.
# This Makefile.in is free software; the Free Software Foundation
# gives unlimited permission to copy and/or distribute it,
# with or without modifications, as long as this notice is preserved.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY, to the extent permitted by law; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE.
am__is_gnu_make = test -n '$(MAKEFILE_LIST)' && test -n '$(MAKELEVEL)'
am__make_running_with_option = \
case $${target_option-} in \
?) ;; \
*) echo "am__make_running_with_option: internal error: invalid" \
"target option '$${target_option-}' specified" >&2; \
exit 1;; \
esac; \
has_opt=no; \
sane_makeflags=$$MAKEFLAGS; \
if $(am__is_gnu_make); then \
sane_makeflags=$$MFLAGS; \
else \
case $$MAKEFLAGS in \
*\\[\ \ ]*) \
bs=\\; \
sane_makeflags=`printf '%s\n' "$$MAKEFLAGS" \
| sed "s/$$bs$$bs[$$bs $$bs ]*//g"`;; \
esac; \
fi; \
skip_next=no; \
strip_trailopt () \
{ \
flg=`printf '%s\n' "$$flg" | sed "s/$$1.*$$//"`; \
}; \
for flg in $$sane_makeflags; do \
test $$skip_next = yes && { skip_next=no; continue; }; \
case $$flg in \
*=*|--*) continue;; \
-*I) strip_trailopt 'I'; skip_next=yes;; \
-*I?*) strip_trailopt 'I';; \
-*O) strip_trailopt 'O'; skip_next=yes;; \
-*O?*) strip_trailopt 'O';; \
-*l) strip_trailopt 'l'; skip_next=yes;; \
-*l?*) strip_trailopt 'l';; \
-[dEDm]) skip_next=yes;; \
-[JT]) skip_next=yes;; \
esac; \
case $$flg in \
*$$target_option*) has_opt=yes; break;; \
esac; \
done; \
test $$has_opt = yes
am__make_dryrun = (target_option=n; $(am__make_running_with_option))
am__make_keepgoing = (target_option=k; $(am__make_running_with_option))
pkgincludedir = $(includedir)/blueman
pkglibdir = $(libdir)/blueman
pkglibexecdir = $(libexecdir)/blueman
am__cd = CDPATH="$${ZSH_VERSION+.}$(PATH_SEPARATOR)" && cd
install_sh_DATA = $(install_sh) -c -m 644
install_sh_PROGRAM = $(install_sh) -c
install_sh_SCRIPT = $(install_sh) -c
INSTALL_HEADER = $(INSTALL_DATA)
transform = $(program_transform_name)
NORMAL_INSTALL = :
PRE_INSTALL = :
POST_INSTALL = :
NORMAL_UNINSTALL = :
PRE_UNINSTALL = :
POST_UNINSTALL = :
build_triplet = x86_64-unknown-linux-gnu
host_triplet = x86_64-unknown-linux-gnu
subdir = blueman/plugins
DIST_COMMON = $(srcdir)/Makefile.in $(srcdir)/Makefile.am \
$(blueman_PYTHON) $(top_srcdir)/py-compile
ACLOCAL_M4 = $(top_srcdir)/aclocal.m4
am__aclocal_m4_deps = $(top_srcdir)/acinclude.m4 \
$(top_srcdir)/configure.ac
am__configure_deps = $(am__aclocal_m4_deps) $(CONFIGURE_DEPENDENCIES) \
$(ACLOCAL_M4)
mkinstalldirs = $(install_sh) -d
CONFIG_HEADER = $(top_builddir)/config.h
CONFIG_CLEAN_FILES =
CONFIG_CLEAN_VPATH_FILES =
AM_V_P = $(am__v_P_$(V))
am__v_P_ = $(am__v_P_$(AM_DEFAULT_VERBOSITY))
am__v_P_0 = false
am__v_P_1 = :
AM_V_GEN = $(am__v_GEN_$(V))
am__v_GEN_ = $(am__v_GEN_$(AM_DEFAULT_VERBOSITY))
am__v_GEN_0 = @echo " GEN " $@;
am__v_GEN_1 =
AM_V_at = $(am__v_at_$(V))
am__v_at_ = $(am__v_at_$(AM_DEFAULT_VERBOSITY))
am__v_at_0 = @
am__v_at_1 =
SOURCES =
DIST_SOURCES =
RECURSIVE_TARGETS = all-recursive check-recursive cscopelist-recursive \
ctags-recursive dvi-recursive html-recursive info-recursive \
install-data-recursive install-dvi-recursive \
install-exec-recursive install-html-recursive \
install-info-recursive install-pdf-recursive \
install-ps-recursive install-recursive installcheck-recursive \
installdirs-recursive pdf-recursive ps-recursive \
tags-recursive uninstall-recursive
am__can_run_installinfo = \
case $$AM_UPDATE_INFO_DIR in \
n|no|NO) false;; \
*) (install-info --version) >/dev/null 2>&1;; \
esac
am__vpath_adj_setup = srcdirstrip=`echo "$(srcdir)" | sed 's|.|.|g'`;
am__vpath_adj = case $$p in \
$(srcdir)/*) f=`echo "$$p" | sed "s|^$$srcdirstrip/||"`;; \
*) f=$$p;; \
esac;
am__strip_dir = f=`echo $$p | sed -e 's|^.*/||'`;
am__install_max = 40
am__nobase_strip_setup = \
srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*|]/\\\\&/g'`
am__nobase_strip = \
for p in $$list; do echo "$$p"; done | sed -e "s|$$srcdirstrip/||"
am__nobase_list = $(am__nobase_strip_setup); \
for p in $$list; do echo "$$p $$p"; done | \
sed "s| $$srcdirstrip/| |;"' / .*\//!s/ .*/ ./; s,\( .*\)/[^/]*$$,\1,' | \
$(AWK) 'BEGIN { files["."] = "" } { files[$$2] = files[$$2] " " $$1; \
if (++n[$$2] == $(am__install_max)) \
{ print $$2, files[$$2]; n[$$2] = 0; files[$$2] = "" } } \
END { for (dir in files) print dir, files[dir] }'
am__base_list = \
sed '$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;$$!N;s/\n/ /g' | \
sed '$$!N;$$!N;$$!N;$$!N;s/\n/ /g'
am__uninstall_files_from_dir = { \
test -z "$$files" \
|| { test ! -d "$$dir" && test ! -f "$$dir" && test ! -r "$$dir"; } \
|| { echo " ( cd '$$dir' && rm -f" $$files ")"; \
$(am__cd) "$$dir" && rm -f $$files; }; \
}
am__py_compile = PYTHON=$(PYTHON) $(SHELL) $(py_compile)
am__installdirs = "$(DESTDIR)$(bluemandir)"
am__pep3147_tweak = \
sed -e 's|\.py$$||' -e 's|[^/]*$$|__pycache__/&.*.py|'
py_compile = $(top_srcdir)/py-compile
RECURSIVE_CLEAN_TARGETS = mostlyclean-recursive clean-recursive \
distclean-recursive maintainer-clean-recursive
am__recursive_targets = \
$(RECURSIVE_TARGETS) \
$(RECURSIVE_CLEAN_TARGETS) \
$(am__extra_recursive_targets)
AM_RECURSIVE_TARGETS = $(am__recursive_targets:-recursive=) TAGS CTAGS \
distdir
am__tagged_files = $(HEADERS) $(SOURCES) $(TAGS_FILES) $(LISP)
# Read a list of newline-separated strings from the standard input,
# and print each of them once, without duplicates. Input order is
# *not* preserved.
am__uniquify_input = $(AWK) '\
BEGIN { nonempty = 0; } \
{ items[$$0] = 1; nonempty = 1; } \
END { if (nonempty) { for (i in items) print i; }; } \
'
# Make sure the list of sources is unique. This is necessary because,
# e.g., the same source file might be shared among _SOURCES variables
# for different programs/libraries.
am__define_uniq_tagged_files = \
list='$(am__tagged_files)'; \
unique=`for i in $$list; do \
if test -f "$$i"; then echo $$i; else echo $(srcdir)/$$i; fi; \
done | $(am__uniquify_input)`
ETAGS = etags
CTAGS = ctags
DIST_SUBDIRS = $(SUBDIRS)
DISTFILES = $(DIST_COMMON) $(DIST_SOURCES) $(TEXINFOS) $(EXTRA_DIST)
am__relativize = \
dir0=`pwd`; \
sed_first='s,^\([^/]*\)/.*$$,\1,'; \
sed_rest='s,^[^/]*/*,,'; \
sed_last='s,^.*/\([^/]*\)$$,\1,'; \
sed_butlast='s,/*[^/]*$$,,'; \
while test -n "$$dir1"; do \
first=`echo "$$dir1" | sed -e "$$sed_first"`; \
if test "$$first" != "."; then \
if test "$$first" = ".."; then \
dir2=`echo "$$dir0" | sed -e "$$sed_last"`/"$$dir2"; \
dir0=`echo "$$dir0" | sed -e "$$sed_butlast"`; \
else \
first2=`echo "$$dir2" | sed -e "$$sed_first"`; \
if test "$$first2" = "$$first"; then \
dir2=`echo "$$dir2" | sed -e "$$sed_rest"`; \
else \
dir2="../$$dir2"; \
fi; \
dir0="$$dir0"/"$$first"; \
fi; \
fi; \
dir1=`echo "$$dir1" | sed -e "$$sed_rest"`; \
done; \
reldir="$$dir2"
pkgdatadir = /usr/local/share/blueman
ACLOCAL = ${SHELL} /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/missing aclocal-1.14
ALL_LINGUAS =
AMTAR = $${TAR-tar}
AM_DEFAULT_VERBOSITY = 1
AR = ar
AUTOCONF = ${SHELL} /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/missing autoconf
AUTOHEADER = ${SHELL} /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/missing autoheader
AUTOMAKE = ${SHELL} /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/missing automake-1.14
AWK = gawk
BINDIR = /usr/local/bin
BLUEZ_CFLAGS = -pthread -I/usr/include/startup-notification-1.0 -I/usr/include/gtk-2.0 -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/freetype2 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/include/pixman-1 -I/usr/include/libpng12 -I/usr/include/libdrm -I/usr/include/harfbuzz -I/usr/include/pygtk-2.0
BLUEZ_LIBS = -pthread -lbluetooth -lstartup-notification-1 -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfontconfig -lfreetype -lgobject-2.0 -lgthread-2.0 -lglib-2.0
CATALOGS =
CATOBJEXT = .gmo
CC = gcc
CCDEPMODE = depmode=gcc3
CFLAGS = -g -O2
CPP = gcc -E
CPPFLAGS =
CYGPATH_W = echo
DATADIR = /usr/local/share
DATADIRNAME = share
DEFS = -DHAVE_CONFIG_H
DEPDIR = .deps
DLLTOOL = false
DSYMUTIL =
DUMPBIN =
ECHO_C =
ECHO_N = -n
ECHO_T =
EGREP = /bin/grep -E
EXEEXT =
FGREP = /bin/grep -F
GETTEXT_PACKAGE = blueman
GMOFILES =
GMSGFMT = /usr/bin/msgfmt
GREP = /bin/grep
INSTALL = /usr/bin/install -c
INSTALL_DATA = ${INSTALL} -m 644
INSTALL_PROGRAM = ${INSTALL}
INSTALL_SCRIPT = ${INSTALL}
INSTALL_STRIP_PROGRAM = $(install_sh) -c -s
INSTOBJEXT = .mo
INTLLIBS =
INTLTOOL_EXTRACT = /usr/bin/intltool-extract
INTLTOOL_MERGE = /usr/bin/intltool-merge
INTLTOOL_PERL = /usr/bin/perl
INTLTOOL_UPDATE = /usr/bin/intltool-update
INTLTOOL_V_MERGE = $(INTLTOOL__v_MERGE_$(V))
INTLTOOL_V_MERGE_OPTIONS = $(intltool__v_merge_options_$(V))
INTLTOOL__v_MERGE_ = $(INTLTOOL__v_MERGE_$(AM_DEFAULT_VERBOSITY))
INTLTOOL__v_MERGE_0 = @echo " ITMRG " $@;
LD = /usr/bin/ld -m elf_x86_64
LDFLAGS =
LIBEXECDIR = /usr/local/libexec
LIBOBJS =
LIBS =
LIBTOOL = $(SHELL) $(top_builddir)/libtool
LIPO =
LN_S = ln -s
LOCALEDIR = /usr/local/share/locale
LTLIBOBJS =
MAINT =
MAKEINFO = ${SHELL} /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/missing makeinfo
MANIFEST_TOOL = :
MKDIR_P = /bin/mkdir -p
MKINSTALLDIRS = ./mkinstalldirs
MSGFMT = /usr/bin/msgfmt
MSGFMT_OPTS = -c
MSGMERGE = /usr/bin/msgmerge
NM = /usr/bin/nm -B
NMEDIT =
OBJDUMP = objdump
OBJEXT = o
OTOOL =
OTOOL64 =
PACKAGE = blueman
PACKAGE_BUGREPORT =
PACKAGE_NAME = blueman
PACKAGE_STRING = blueman 1.23
PACKAGE_TARNAME = blueman
PACKAGE_URL =
PACKAGE_VERSION = 1.23
PATH_SEPARATOR = :
PKGLIBDIR = /usr/local/lib/blueman
PKG_CONFIG = /usr/bin/pkg-config
PKG_CONFIG_LIBDIR =
PKG_CONFIG_PATH =
POFILES =
POSUB = po
PO_IN_DATADIR_FALSE =
PO_IN_DATADIR_TRUE =
PYGTK_CFLAGS = -pthread -I/usr/include/gtk-2.0 -I/usr/include/glib-2.0 -I/usr/lib/x86_64-linux-gnu/glib-2.0/include -I/usr/lib/x86_64-linux-gnu/gtk-2.0/include -I/usr/include/atk-1.0 -I/usr/include/cairo -I/usr/include/gdk-pixbuf-2.0 -I/usr/include/pango-1.0 -I/usr/include/gio-unix-2.0/ -I/usr/include/freetype2 -I/usr/include/pixman-1 -I/usr/include/libpng12 -I/usr/include/libdrm -I/usr/include/harfbuzz -I/usr/include/pygtk-2.0
PYGTK_LIBS = -lgtk-x11-2.0 -lgdk-x11-2.0 -latk-1.0 -lgio-2.0 -lpangoft2-1.0 -lpangocairo-1.0 -lgdk_pixbuf-2.0 -lcairo -lpango-1.0 -lfontconfig -lgobject-2.0 -lglib-2.0 -lfreetype
PYNOTIFY_CFLAGS = -I/usr/include/gnome-python-2.0
PYNOTIFY_LIBS =
PYREXC = /usr/bin/pyrexc
PYTHON = /usr/bin/python
PYTHONDIR = /usr/local/lib/python2.7/dist-packages
PYTHON_EXEC_PREFIX = ${exec_prefix}
PYTHON_INCLUDES = -I/usr/include/python2.7 -I/usr/include/x86_64-linux-gnu/python2.7
PYTHON_LIBS = -lpthread -ldl -lutil -lm -lpython2.7
PYTHON_PLATFORM = linux2
PYTHON_PREFIX = ${prefix}
PYTHON_VERSION = 2.7
RANLIB = ranlib
SED = /bin/sed
SET_MAKE =
SHELL = /bin/bash
STRIP = strip
SYSCONFDIR = /etc
USE_NLS = yes
VERSION = 1.23
XGETTEXT = /usr/bin/xgettext
abs_builddir = /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/blueman/plugins
abs_srcdir = /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/blueman/plugins
abs_top_builddir = /home/schramm/src/blueman-deb/blueman-1.23-git201403102151
abs_top_srcdir = /home/schramm/src/blueman-deb/blueman-1.23-git201403102151
ac_ct_AR = ar
ac_ct_CC = gcc
ac_ct_DUMPBIN =
am__include = include
am__leading_dot = .
am__quote =
am__tar = $${TAR-tar} chof - "$$tardir"
am__untar = $${TAR-tar} xf -
bindir = ${exec_prefix}/bin
build = x86_64-unknown-linux-gnu
build_alias =
build_cpu = x86_64
build_os = linux-gnu
build_vendor = unknown
builddir = .
datadir = ${datarootdir}
datarootdir = ${prefix}/share
dhconfig = /etc/dhcp3/dhcpd.conf
docdir = ${datarootdir}/doc/${PACKAGE_TARNAME}
dvidir = ${docdir}
exec_prefix = ${prefix}
hal_en = no
host = x86_64-unknown-linux-gnu
host_alias =
host_cpu = x86_64
host_os = linux-gnu
host_vendor = unknown
htmldir = ${docdir}
includedir = ${prefix}/include
infodir = ${datarootdir}/info
install_sh = ${SHELL} /home/schramm/src/blueman-deb/blueman-1.23-git201403102151/install-sh
intltool__v_merge_options_ = $(intltool__v_merge_options_$(AM_DEFAULT_VERBOSITY))
intltool__v_merge_options_0 = -q
libdir = ${exec_prefix}/lib
libexecdir = ${exec_prefix}/libexec
localedir = ${datarootdir}/locale
localstatedir = ${prefix}/var
mandir = ${datarootdir}/man
mkdir_p = $(MKDIR_P)
oldincludedir = /usr/include
pdfdir = ${docdir}
pkgpyexecdir = ${pyexecdir}/blueman
pkgpythondir = ${pythondir}/blueman
polkit_val = yes
prefix = /usr/local
program_transform_name = s,x,x,
psdir = ${docdir}
pyexecdir = ${exec_prefix}/lib/python2.7/dist-packages
pythondir = ${prefix}/lib/python2.7/dist-packages
sbindir = ${exec_prefix}/sbin
sharedstatedir = ${prefix}/com
srcdir = .
sysconfdir = /etc
target_alias =
top_build_prefix = ../../
top_builddir = ../..
top_srcdir = ../..
SUBDIRS = \
services \
applet \
config \
mechanism \
manager
bluemandir = $(pythondir)/blueman/plugins
blueman_PYTHON = \
ServicePlugin.py \
AppletPlugin.py \
ConfigPlugin.py \
MechanismPlugin.py \
ManagerPlugin.py \
BasePlugin.py \
ConfigurablePlugin.py \
__init__.py
CLEANFILES = \
$(BUILT_SOURCES)
DISTCLEANFILES = \
$(CLEANFILES)
all: all-recursive
.SUFFIXES:
$(srcdir)/Makefile.in: $(srcdir)/Makefile.am $(am__configure_deps)
@for dep in $?; do \
case '$(am__configure_deps)' in \
*$$dep*) \
( cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh ) \
&& { if test -f $@; then exit 0; else break; fi; }; \
exit 1;; \
esac; \
done; \
echo ' cd $(top_srcdir) && $(AUTOMAKE) --foreign blueman/plugins/Makefile'; \
$(am__cd) $(top_srcdir) && \
$(AUTOMAKE) --foreign blueman/plugins/Makefile
.PRECIOUS: Makefile
Makefile: $(srcdir)/Makefile.in $(top_builddir)/config.status
@case '$?' in \
*config.status*) \
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh;; \
*) \
echo ' cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe)'; \
cd $(top_builddir) && $(SHELL) ./config.status $(subdir)/$@ $(am__depfiles_maybe);; \
esac;
$(top_builddir)/config.status: $(top_srcdir)/configure $(CONFIG_STATUS_DEPENDENCIES)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(top_srcdir)/configure: $(am__configure_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(ACLOCAL_M4): $(am__aclocal_m4_deps)
cd $(top_builddir) && $(MAKE) $(AM_MAKEFLAGS) am--refresh
$(am__aclocal_m4_deps):
mostlyclean-libtool:
-rm -f *.lo
clean-libtool:
-rm -rf .libs _libs
install-bluemanPYTHON: $(blueman_PYTHON)
@$(NORMAL_INSTALL)
@list='$(blueman_PYTHON)'; dlist=; list2=; test -n "$(bluemandir)" || list=; \
if test -n "$$list"; then \
echo " $(MKDIR_P) '$(DESTDIR)$(bluemandir)'"; \
$(MKDIR_P) "$(DESTDIR)$(bluemandir)" || exit 1; \
fi; \
for p in $$list; do \
if test -f "$$p"; then b=; else b="$(srcdir)/"; fi; \
if test -f $$b$$p; then \
$(am__strip_dir) \
dlist="$$dlist $$f"; \
list2="$$list2 $$b$$p"; \
else :; fi; \
done; \
for file in $$list2; do echo $$file; done | $(am__base_list) | \
while read files; do \
echo " $(INSTALL_DATA) $$files '$(DESTDIR)$(bluemandir)'"; \
$(INSTALL_DATA) $$files "$(DESTDIR)$(bluemandir)" || exit $$?; \
done || exit $$?; \
if test -n "$$dlist"; then \
$(am__py_compile) --destdir "$(DESTDIR)" \
--basedir "$(bluemandir)" $$dlist; \
else :; fi
uninstall-bluemanPYTHON:
@$(NORMAL_UNINSTALL)
@list='$(blueman_PYTHON)'; test -n "$(bluemandir)" || list=; \
py_files=`for p in $$list; do echo $$p; done | sed -e 's|^.*/||'`; \
test -n "$$py_files" || exit 0; \
dir='$(DESTDIR)$(bluemandir)'; \
pyc_files=`echo "$$py_files" | sed 's|$$|c|'`; \
pyo_files=`echo "$$py_files" | sed 's|$$|o|'`; \
py_files_pep3147=`echo "$$py_files" | $(am__pep3147_tweak)`; \
echo "$$py_files_pep3147";\
pyc_files_pep3147=`echo "$$py_files_pep3147" | sed 's|$$|c|'`; \
pyo_files_pep3147=`echo "$$py_files_pep3147" | sed 's|$$|o|'`; \
st=0; \
for files in \
"$$py_files" \
"$$pyc_files" \
"$$pyo_files" \
"$$pyc_files_pep3147" \
"$$pyo_files_pep3147" \
; do \
$(am__uninstall_files_from_dir) || st=$$?; \
done; \
exit $$st
# This directory's subdirectories are mostly independent; you can cd
# into them and run 'make' without going through this Makefile.
# To change the values of 'make' variables: instead of editing Makefiles,
# (1) if the variable is set in 'config.status', edit 'config.status'
# (which will cause the Makefiles to be regenerated when you run 'make');
# (2) otherwise, pass the desired values on the 'make' command line.
$(am__recursive_targets):
@fail=; \
if $(am__make_keepgoing); then \
failcom='fail=yes'; \
else \
failcom='exit 1'; \
fi; \
dot_seen=no; \
target=`echo $@ | sed s/-recursive//`; \
case "$@" in \
distclean-* | maintainer-clean-*) list='$(DIST_SUBDIRS)' ;; \
*) list='$(SUBDIRS)' ;; \
esac; \
for subdir in $$list; do \
echo "Making $$target in $$subdir"; \
if test "$$subdir" = "."; then \
dot_seen=yes; \
local_target="$$target-am"; \
else \
local_target="$$target"; \
fi; \
($(am__cd) $$subdir && $(MAKE) $(AM_MAKEFLAGS) $$local_target) \
|| eval $$failcom; \
done; \
if test "$$dot_seen" = "no"; then \
$(MAKE) $(AM_MAKEFLAGS) "$$target-am" || exit 1; \
fi; test -z "$$fail"
ID: $(am__tagged_files)
$(am__define_uniq_tagged_files); mkid -fID $$unique
tags: tags-recursive
TAGS: tags
tags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
set x; \
here=`pwd`; \
if ($(ETAGS) --etags-include --version) >/dev/null 2>&1; then \
include_option=--etags-include; \
empty_fix=.; \
else \
include_option=--include; \
empty_fix=; \
fi; \
list='$(SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
test ! -f $$subdir/TAGS || \
set "$$@" "$$include_option=$$here/$$subdir/TAGS"; \
fi; \
done; \
$(am__define_uniq_tagged_files); \
shift; \
if test -z "$(ETAGS_ARGS)$$*$$unique"; then :; else \
test -n "$$unique" || unique=$$empty_fix; \
if test $$# -gt 0; then \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
"$$@" $$unique; \
else \
$(ETAGS) $(ETAGSFLAGS) $(AM_ETAGSFLAGS) $(ETAGS_ARGS) \
$$unique; \
fi; \
fi
ctags: ctags-recursive
CTAGS: ctags
ctags-am: $(TAGS_DEPENDENCIES) $(am__tagged_files)
$(am__define_uniq_tagged_files); \
test -z "$(CTAGS_ARGS)$$unique" \
|| $(CTAGS) $(CTAGSFLAGS) $(AM_CTAGSFLAGS) $(CTAGS_ARGS) \
$$unique
GTAGS:
here=`$(am__cd) $(top_builddir) && pwd` \
&& $(am__cd) $(top_srcdir) \
&& gtags -i $(GTAGS_ARGS) "$$here"
cscopelist: cscopelist-recursive
cscopelist-am: $(am__tagged_files)
list='$(am__tagged_files)'; \
case "$(srcdir)" in \
[\\/]* | ?:[\\/]*) sdir="$(srcdir)" ;; \
*) sdir=$(subdir)/$(srcdir) ;; \
esac; \
for i in $$list; do \
if test -f "$$i"; then \
echo "$(subdir)/$$i"; \
else \
echo "$$sdir/$$i"; \
fi; \
done >> $(top_builddir)/cscope.files
distclean-tags:
-rm -f TAGS ID GTAGS GRTAGS GSYMS GPATH tags
distdir: $(DISTFILES)
@srcdirstrip=`echo "$(srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
topsrcdirstrip=`echo "$(top_srcdir)" | sed 's/[].[^$$\\*]/\\\\&/g'`; \
list='$(DISTFILES)'; \
dist_files=`for file in $$list; do echo $$file; done | \
sed -e "s|^$$srcdirstrip/||;t" \
-e "s|^$$topsrcdirstrip/|$(top_builddir)/|;t"`; \
case $$dist_files in \
*/*) $(MKDIR_P) `echo "$$dist_files" | \
sed '/\//!d;s|^|$(distdir)/|;s,/[^/]*$$,,' | \
sort -u` ;; \
esac; \
for file in $$dist_files; do \
if test -f $$file || test -d $$file; then d=.; else d=$(srcdir); fi; \
if test -d $$d/$$file; then \
dir=`echo "/$$file" | sed -e 's,/[^/]*$$,,'`; \
if test -d "$(distdir)/$$file"; then \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
if test -d $(srcdir)/$$file && test $$d != $(srcdir); then \
cp -fpR $(srcdir)/$$file "$(distdir)$$dir" || exit 1; \
find "$(distdir)/$$file" -type d ! -perm -700 -exec chmod u+rwx {} \;; \
fi; \
cp -fpR $$d/$$file "$(distdir)$$dir" || exit 1; \
else \
test -f "$(distdir)/$$file" \
|| cp -p $$d/$$file "$(distdir)/$$file" \
|| exit 1; \
fi; \
done
@list='$(DIST_SUBDIRS)'; for subdir in $$list; do \
if test "$$subdir" = .; then :; else \
$(am__make_dryrun) \
|| test -d "$(distdir)/$$subdir" \
|| $(MKDIR_P) "$(distdir)/$$subdir" \
|| exit 1; \
dir1=$$subdir; dir2="$(distdir)/$$subdir"; \
$(am__relativize); \
new_distdir=$$reldir; \
dir1=$$subdir; dir2="$(top_distdir)"; \
$(am__relativize); \
new_top_distdir=$$reldir; \
echo " (cd $$subdir && $(MAKE) $(AM_MAKEFLAGS) top_distdir="$$new_top_distdir" distdir="$$new_distdir" \\"; \
echo " am__remove_distdir=: am__skip_length_check=: am__skip_mode_fix=: distdir)"; \
($(am__cd) $$subdir && \
$(MAKE) $(AM_MAKEFLAGS) \
top_distdir="$$new_top_distdir" \
distdir="$$new_distdir" \
am__remove_distdir=: \
am__skip_length_check=: \
am__skip_mode_fix=: \
distdir) \
|| exit 1; \
fi; \
done
check-am: all-am
check: check-recursive
all-am: Makefile
installdirs: installdirs-recursive
installdirs-am:
for dir in "$(DESTDIR)$(bluemandir)"; do \
test -z "$$dir" || $(MKDIR_P) "$$dir"; \
done
install: install-recursive
install-exec: install-exec-recursive
install-data: install-data-recursive
uninstall: uninstall-recursive
install-am: all-am
@$(MAKE) $(AM_MAKEFLAGS) install-exec-am install-data-am
installcheck: installcheck-recursive
install-strip:
if test -z '$(STRIP)'; then \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
install; \
else \
$(MAKE) $(AM_MAKEFLAGS) INSTALL_PROGRAM="$(INSTALL_STRIP_PROGRAM)" \
install_sh_PROGRAM="$(INSTALL_STRIP_PROGRAM)" INSTALL_STRIP_FLAG=-s \
"INSTALL_PROGRAM_ENV=STRIPPROG='$(STRIP)'" install; \
fi
mostlyclean-generic:
clean-generic:
-test -z "$(CLEANFILES)" || rm -f $(CLEANFILES)
distclean-generic:
-test -z "$(CONFIG_CLEAN_FILES)" || rm -f $(CONFIG_CLEAN_FILES)
-test . = "$(srcdir)" || test -z "$(CONFIG_CLEAN_VPATH_FILES)" || rm -f $(CONFIG_CLEAN_VPATH_FILES)
-test -z "$(DISTCLEANFILES)" || rm -f $(DISTCLEANFILES)
maintainer-clean-generic:
@echo "This command is intended for maintainers to use"
@echo "it deletes files that may require special tools to rebuild."
clean: clean-recursive
clean-am: clean-generic clean-libtool clean-local mostlyclean-am
distclean: distclean-recursive
-rm -f Makefile
distclean-am: clean-am distclean-generic distclean-tags
dvi: dvi-recursive
dvi-am:
html: html-recursive
html-am:
info: info-recursive
info-am:
install-data-am: install-bluemanPYTHON
install-dvi: install-dvi-recursive
install-dvi-am:
install-exec-am:
install-html: install-html-recursive
install-html-am:
install-info: install-info-recursive
install-info-am:
install-man:
install-pdf: install-pdf-recursive
install-pdf-am:
install-ps: install-ps-recursive
install-ps-am:
installcheck-am:
maintainer-clean: maintainer-clean-recursive
-rm -f Makefile
maintainer-clean-am: distclean-am maintainer-clean-generic
mostlyclean: mostlyclean-recursive
mostlyclean-am: mostlyclean-generic mostlyclean-libtool
pdf: pdf-recursive
pdf-am:
ps: ps-recursive
ps-am:
uninstall-am: uninstall-bluemanPYTHON
.MAKE: $(am__recursive_targets) install-am install-strip
.PHONY: $(am__recursive_targets) CTAGS GTAGS TAGS all all-am check \
check-am clean clean-generic clean-libtool clean-local \
cscopelist-am ctags ctags-am distclean distclean-generic \
distclean-libtool distclean-tags distdir dvi dvi-am html \
html-am info info-am install install-am install-bluemanPYTHON \
install-data install-data-am install-dvi install-dvi-am \
install-exec install-exec-am install-html install-html-am \
install-info install-info-am install-man install-pdf \
install-pdf-am install-ps install-ps-am install-strip \
installcheck installcheck-am installdirs installdirs-am \
maintainer-clean maintainer-clean-generic mostlyclean \
mostlyclean-generic mostlyclean-libtool pdf pdf-am ps ps-am \
tags tags-am uninstall uninstall-am uninstall-bluemanPYTHON
clean-local:
rm -rf *.pyc *.pyo
# Tell versions [3.59,3.63) of GNU make to not export all variables.
# Otherwise a system limit (for SysV at least) may be exceeded.
.NOEXPORT:
|
hamonikr-root/blueman
|
blueman/plugins/Makefile
|
Makefile
|
gpl-3.0
| 25,377
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import json
import frappe
from erpnext.accounts.party import get_party_account_currency
from erpnext.controllers.accounts_controller import get_taxes_and_charges
from erpnext.setup.utils import get_exchange_rate
from erpnext.stock.get_item_details import get_pos_profile
from frappe import _
from frappe.core.doctype.communication.email import make
from frappe.utils import nowdate, cint
from six import string_types, iteritems
@frappe.whitelist()
def get_pos_data():
doc = frappe.new_doc('Sales Invoice')
doc.is_pos = 1
pos_profile = get_pos_profile(doc.company) or {}
if not pos_profile:
frappe.throw(_("POS Profile is required to use Point-of-Sale"))
if not doc.company:
doc.company = pos_profile.get('company')
doc.update_stock = pos_profile.get('update_stock')
if pos_profile.get('name'):
pos_profile = frappe.get_doc('POS Profile', pos_profile.get('name'))
pos_profile.validate()
company_data = get_company_data(doc.company)
update_pos_profile_data(doc, pos_profile, company_data)
update_multi_mode_option(doc, pos_profile)
default_print_format = pos_profile.get('print_format') or "Point of Sale"
print_template = frappe.db.get_value('Print Format', default_print_format, 'html')
items_list = get_items_list(pos_profile, doc.company)
customers = get_customers_list(pos_profile)
doc.plc_conversion_rate = update_plc_conversion_rate(doc, pos_profile)
return {
'doc': doc,
'default_customer': pos_profile.get('customer'),
'items': items_list,
'item_groups': get_item_groups(pos_profile),
'customers': customers,
'address': get_customers_address(customers),
'contacts': get_contacts(customers),
'serial_no_data': get_serial_no_data(pos_profile, doc.company),
'batch_no_data': get_batch_no_data(),
'barcode_data': get_barcode_data(items_list),
'tax_data': get_item_tax_data(),
'price_list_data': get_price_list_data(doc.selling_price_list, doc.plc_conversion_rate),
'customer_wise_price_list': get_customer_wise_price_list(),
'bin_data': get_bin_data(pos_profile),
'pricing_rules': get_pricing_rule_data(doc),
'print_template': print_template,
'pos_profile': pos_profile,
'meta': get_meta()
}
def update_plc_conversion_rate(doc, pos_profile):
conversion_rate = 1.0
price_list_currency = frappe.get_cached_value("Price List", doc.selling_price_list, "currency")
if pos_profile.get("currency") != price_list_currency:
conversion_rate = get_exchange_rate(price_list_currency,
pos_profile.get("currency"), nowdate(), args="for_selling") or 1.0
return conversion_rate
def get_meta():
doctype_meta = {
'customer': frappe.get_meta('Customer'),
'invoice': frappe.get_meta('Sales Invoice')
}
for row in frappe.get_all('DocField', fields=['fieldname', 'options'],
filters={'parent': 'Sales Invoice', 'fieldtype': 'Table'}):
doctype_meta[row.fieldname] = frappe.get_meta(row.options)
return doctype_meta
def get_company_data(company):
return frappe.get_all('Company', fields=["*"], filters={'name': company})[0]
def update_pos_profile_data(doc, pos_profile, company_data):
doc.campaign = pos_profile.get('campaign')
if pos_profile and not pos_profile.get('country'):
pos_profile.country = company_data.country
doc.write_off_account = pos_profile.get('write_off_account') or \
company_data.write_off_account
doc.change_amount_account = pos_profile.get('change_amount_account') or \
company_data.default_cash_account
doc.taxes_and_charges = pos_profile.get('taxes_and_charges')
if doc.taxes_and_charges:
update_tax_table(doc)
doc.currency = pos_profile.get('currency') or company_data.default_currency
doc.conversion_rate = 1.0
if doc.currency != company_data.default_currency:
doc.conversion_rate = get_exchange_rate(doc.currency, company_data.default_currency, doc.posting_date, args="for_selling")
doc.selling_price_list = pos_profile.get('selling_price_list') or \
frappe.db.get_value('Selling Settings', None, 'selling_price_list')
doc.naming_series = pos_profile.get('naming_series') or 'SINV-'
doc.letter_head = pos_profile.get('letter_head') or company_data.default_letter_head
doc.ignore_pricing_rule = pos_profile.get('ignore_pricing_rule') or 0
doc.apply_discount_on = pos_profile.get('apply_discount_on') or 'Grand Total'
doc.customer_group = pos_profile.get('customer_group') or get_root('Customer Group')
doc.territory = pos_profile.get('territory') or get_root('Territory')
doc.terms = frappe.db.get_value('Terms and Conditions', pos_profile.get('tc_name'), 'terms') or doc.terms or ''
doc.offline_pos_name = ''
def get_root(table):
root = frappe.db.sql(""" select name from `tab%(table)s` having
min(lft)""" % {'table': table}, as_dict=1)
return root[0].name
def update_multi_mode_option(doc, pos_profile):
from frappe.model import default_fields
if not pos_profile or not pos_profile.get('payments'):
for payment in get_mode_of_payment(doc):
payments = doc.append('payments', {})
payments.mode_of_payment = payment.parent
payments.account = payment.default_account
payments.type = payment.type
return
for payment_mode in pos_profile.payments:
payment_mode = payment_mode.as_dict()
for fieldname in default_fields:
if fieldname in payment_mode:
del payment_mode[fieldname]
doc.append('payments', payment_mode)
def get_mode_of_payment(doc):
return frappe.db.sql("""
select mpa.default_account, mpa.parent, mp.type as type
from `tabMode of Payment Account` mpa,`tabMode of Payment` mp
where mpa.parent = mp.name and mpa.company = %(company)s and mp.enabled = 1""",
{'company': doc.company}, as_dict=1)
def update_tax_table(doc):
taxes = get_taxes_and_charges('Sales Taxes and Charges Template', doc.taxes_and_charges)
for tax in taxes:
doc.append('taxes', tax)
def get_items_list(pos_profile, company):
cond = ""
args_list = []
if pos_profile.get('item_groups'):
# Get items based on the item groups defined in the POS profile
for d in pos_profile.get('item_groups'):
args_list.extend([d.name for d in get_child_nodes('Item Group', d.item_group)])
if args_list:
cond = "and i.item_group in (%s)" % (', '.join(['%s'] * len(args_list)))
return frappe.db.sql("""
select
i.name, i.item_code, i.item_name, i.description, i.item_group, i.has_batch_no,
i.has_serial_no, i.is_stock_item, i.brand, i.stock_uom, i.image,
id.expense_account, id.selling_cost_center, id.default_warehouse,
i.sales_uom, c.conversion_factor, it.item_tax_template, it.valid_from
from
`tabItem` i
left join `tabItem Default` id on id.parent = i.name and id.company = %s
left join `tabItem Tax` it on it.parent = i.name
left join `tabUOM Conversion Detail` c on i.name = c.parent and i.sales_uom = c.uom
where
i.disabled = 0 and i.has_variants = 0 and i.is_sales_item = 1
{cond}
group by i.item_code
""".format(cond=cond), tuple([company] + args_list), as_dict=1)
def get_item_groups(pos_profile):
item_group_dict = {}
item_groups = frappe.db.sql("""Select name,
lft, rgt from `tabItem Group` order by lft""", as_dict=1)
for data in item_groups:
item_group_dict[data.name] = [data.lft, data.rgt]
return item_group_dict
def get_customers_list(pos_profile={}):
cond = "1=1"
customer_groups = []
if pos_profile.get('customer_groups'):
# Get customers based on the customer groups defined in the POS profile
for d in pos_profile.get('customer_groups'):
customer_groups.extend([d.get('name') for d in get_child_nodes('Customer Group', d.get('customer_group'))])
cond = "customer_group in (%s)" % (', '.join(['%s'] * len(customer_groups)))
return frappe.db.sql(""" select name, customer_name, customer_group,
territory, customer_pos_id from tabCustomer where disabled = 0
and {cond}""".format(cond=cond), tuple(customer_groups), as_dict=1) or {}
def get_customers_address(customers):
customer_address = {}
if isinstance(customers, string_types):
customers = [frappe._dict({'name': customers})]
for data in customers:
address = frappe.db.sql(""" select name, address_line1, address_line2, city, state,
email_id, phone, fax, pincode from `tabAddress` where is_primary_address =1 and name in
(select parent from `tabDynamic Link` where link_doctype = 'Customer' and link_name = %s
and parenttype = 'Address')""", data.name, as_dict=1)
address_data = {}
if address:
address_data = address[0]
address_data.update({'full_name': data.customer_name, 'customer_pos_id': data.customer_pos_id})
customer_address[data.name] = address_data
return customer_address
def get_contacts(customers):
customer_contact = {}
if isinstance(customers, string_types):
customers = [frappe._dict({'name': customers})]
for data in customers:
contact = frappe.db.sql(""" select email_id, phone, mobile_no from `tabContact`
where is_primary_contact=1 and name in
(select parent from `tabDynamic Link` where link_doctype = 'Customer' and link_name = %s
and parenttype = 'Contact')""", data.name, as_dict=1)
if contact:
customer_contact[data.name] = contact[0]
return customer_contact
def get_child_nodes(group_type, root):
lft, rgt = frappe.db.get_value(group_type, root, ["lft", "rgt"])
return frappe.db.sql(""" Select name, lft, rgt from `tab{tab}` where
lft >= {lft} and rgt <= {rgt} order by lft""".format(tab=group_type, lft=lft, rgt=rgt), as_dict=1)
def get_serial_no_data(pos_profile, company):
# get itemwise serial no data
# example {'Nokia Lumia 1020': {'SN0001': 'Pune'}}
# where Nokia Lumia 1020 is item code, SN0001 is serial no and Pune is warehouse
cond = "1=1"
if pos_profile.get('update_stock') and pos_profile.get('warehouse'):
cond = "warehouse = %(warehouse)s"
serial_nos = frappe.db.sql("""select name, warehouse, item_code
from `tabSerial No` where {0} and company = %(company)s """.format(cond),{
'company': company, 'warehouse': frappe.db.escape(pos_profile.get('warehouse'))
}, as_dict=1)
itemwise_serial_no = {}
for sn in serial_nos:
if sn.item_code not in itemwise_serial_no:
itemwise_serial_no.setdefault(sn.item_code, {})
itemwise_serial_no[sn.item_code][sn.name] = sn.warehouse
return itemwise_serial_no
def get_batch_no_data():
# get itemwise batch no data
# exmaple: {'LED-GRE': [Batch001, Batch002]}
# where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
itemwise_batch = {}
batches = frappe.db.sql("""select name, item from `tabBatch`
where ifnull(expiry_date, '4000-10-10') >= curdate()""", as_dict=1)
for batch in batches:
if batch.item not in itemwise_batch:
itemwise_batch.setdefault(batch.item, [])
itemwise_batch[batch.item].append(batch.name)
return itemwise_batch
def get_barcode_data(items_list):
# get itemwise batch no data
# exmaple: {'LED-GRE': [Batch001, Batch002]}
# where LED-GRE is item code, SN0001 is serial no and Pune is warehouse
itemwise_barcode = {}
for item in items_list:
barcodes = frappe.db.sql("""
select barcode from `tabItem Barcode` where parent = %s
""", item.item_code, as_dict=1)
for barcode in barcodes:
if item.item_code not in itemwise_barcode:
itemwise_barcode.setdefault(item.item_code, [])
itemwise_barcode[item.item_code].append(barcode.get("barcode"))
return itemwise_barcode
def get_item_tax_data():
# get default tax of an item
# example: {'Consulting Services': {'Excise 12 - TS': '12.000'}}
itemwise_tax = {}
taxes = frappe.db.sql(""" select parent, tax_type, tax_rate from `tabItem Tax Template Detail`""", as_dict=1)
for tax in taxes:
if tax.parent not in itemwise_tax:
itemwise_tax.setdefault(tax.parent, {})
itemwise_tax[tax.parent][tax.tax_type] = tax.tax_rate
return itemwise_tax
def get_price_list_data(selling_price_list, conversion_rate):
itemwise_price_list = {}
price_lists = frappe.db.sql("""Select ifnull(price_list_rate, 0) as price_list_rate,
item_code from `tabItem Price` ip where price_list = %(price_list)s""",
{'price_list': selling_price_list}, as_dict=1)
for item in price_lists:
itemwise_price_list[item.item_code] = item.price_list_rate * conversion_rate
return itemwise_price_list
def get_customer_wise_price_list():
customer_wise_price = {}
customer_price_list_mapping = frappe._dict(frappe.get_all('Customer',fields = ['default_price_list', 'name'], as_list=1))
price_lists = frappe.db.sql(""" Select ifnull(price_list_rate, 0) as price_list_rate,
item_code, price_list from `tabItem Price` """, as_dict=1)
for item in price_lists:
if item.price_list and customer_price_list_mapping.get(item.price_list):
customer_wise_price.setdefault(customer_price_list_mapping.get(item.price_list),{}).setdefault(
item.item_code, item.price_list_rate
)
return customer_wise_price
def get_bin_data(pos_profile):
itemwise_bin_data = {}
filters = { 'actual_qty': ['>', 0] }
if pos_profile.get('warehouse'):
filters.update({ 'warehouse': pos_profile.get('warehouse') })
bin_data = frappe.db.get_all('Bin', fields = ['item_code', 'warehouse', 'actual_qty'], filters=filters)
for bins in bin_data:
if bins.item_code not in itemwise_bin_data:
itemwise_bin_data.setdefault(bins.item_code, {})
itemwise_bin_data[bins.item_code][bins.warehouse] = bins.actual_qty
return itemwise_bin_data
def get_pricing_rule_data(doc):
pricing_rules = ""
if doc.ignore_pricing_rule == 0:
pricing_rules = frappe.db.sql(""" Select * from `tabPricing Rule` where docstatus < 2
and ifnull(for_price_list, '') in (%(price_list)s, '') and selling = 1
and ifnull(company, '') in (%(company)s, '') and disable = 0 and %(date)s
between ifnull(valid_from, '2000-01-01') and ifnull(valid_upto, '2500-12-31')
order by priority desc, name desc""",
{'company': doc.company, 'price_list': doc.selling_price_list, 'date': nowdate()}, as_dict=1)
return pricing_rules
@frappe.whitelist()
def make_invoice(pos_profile, doc_list={}, email_queue_list={}, customers_list={}):
import json
if isinstance(doc_list, string_types):
doc_list = json.loads(doc_list)
if isinstance(email_queue_list, string_types):
email_queue_list = json.loads(email_queue_list)
if isinstance(customers_list, string_types):
customers_list = json.loads(customers_list)
customers_list = make_customer_and_address(customers_list)
name_list = []
for docs in doc_list:
for name, doc in iteritems(docs):
if not frappe.db.exists('Sales Invoice', {'offline_pos_name': name}):
if isinstance(doc, dict):
validate_records(doc)
si_doc = frappe.new_doc('Sales Invoice')
si_doc.offline_pos_name = name
si_doc.update(doc)
si_doc.set_posting_time = 1
si_doc.customer = get_customer_id(doc)
si_doc.due_date = doc.get('posting_date')
name_list = submit_invoice(si_doc, name, doc, name_list)
else:
doc.due_date = doc.get('posting_date')
doc.customer = get_customer_id(doc)
doc.set_posting_time = 1
doc.offline_pos_name = name
name_list = submit_invoice(doc, name, doc, name_list)
else:
name_list.append(name)
email_queue = make_email_queue(email_queue_list)
if isinstance(pos_profile, string_types):
pos_profile = json.loads(pos_profile)
customers = get_customers_list(pos_profile)
return {
'invoice': name_list,
'email_queue': email_queue,
'customers': customers_list,
'synced_customers_list': customers,
'synced_address': get_customers_address(customers),
'synced_contacts': get_contacts(customers)
}
def validate_records(doc):
validate_item(doc)
def get_customer_id(doc, customer=None):
cust_id = None
if doc.get('customer_pos_id'):
cust_id = frappe.db.get_value('Customer',{'customer_pos_id': doc.get('customer_pos_id')}, 'name')
if not cust_id:
customer = customer or doc.get('customer')
if frappe.db.exists('Customer', customer):
cust_id = customer
else:
cust_id = add_customer(doc)
return cust_id
def make_customer_and_address(customers):
customers_list = []
for customer, data in iteritems(customers):
data = json.loads(data)
cust_id = get_customer_id(data, customer)
if not cust_id:
cust_id = add_customer(data)
else:
frappe.db.set_value("Customer", cust_id, "customer_name", data.get('full_name'))
make_contact(data, cust_id)
make_address(data, cust_id)
customers_list.append(customer)
frappe.db.commit()
return customers_list
def add_customer(data):
customer = data.get('full_name') or data.get('customer')
if frappe.db.exists("Customer", customer.strip()):
return customer.strip()
customer_doc = frappe.new_doc('Customer')
customer_doc.customer_name = data.get('full_name') or data.get('customer')
customer_doc.customer_pos_id = data.get('customer_pos_id')
customer_doc.customer_type = 'Company'
customer_doc.customer_group = get_customer_group(data)
customer_doc.territory = get_territory(data)
customer_doc.flags.ignore_mandatory = True
customer_doc.save(ignore_permissions=True)
frappe.db.commit()
return customer_doc.name
def get_territory(data):
if data.get('territory'):
return data.get('territory')
return frappe.db.get_single_value('Selling Settings','territory') or _('All Territories')
def get_customer_group(data):
if data.get('customer_group'):
return data.get('customer_group')
return frappe.db.get_single_value('Selling Settings', 'customer_group') or frappe.db.get_value('Customer Group', {'is_group': 0}, 'name')
def make_contact(args, customer):
if args.get('email_id') or args.get('phone'):
name = frappe.db.get_value('Dynamic Link',
{'link_doctype': 'Customer', 'link_name': customer, 'parenttype': 'Contact'}, 'parent')
args = {
'first_name': args.get('full_name'),
'email_id': args.get('email_id'),
'phone': args.get('phone')
}
doc = frappe.new_doc('Contact')
if name:
doc = frappe.get_doc('Contact', name)
doc.update(args)
doc.is_primary_contact = 1
if not name:
doc.append('links', {
'link_doctype': 'Customer',
'link_name': customer
})
doc.flags.ignore_mandatory = True
doc.save(ignore_permissions=True)
def make_address(args, customer):
if not args.get('address_line1'):
return
name = args.get('name')
if not name:
data = get_customers_address(customer)
name = data[customer].get('name') if data else None
if name:
address = frappe.get_doc('Address', name)
else:
address = frappe.new_doc('Address')
if args.get('company'):
address.country = frappe.get_cached_value('Company',
args.get('company'), 'country')
address.append('links', {
'link_doctype': 'Customer',
'link_name': customer
})
address.is_primary_address = 1
address.is_shipping_address = 1
address.update(args)
address.flags.ignore_mandatory = True
address.save(ignore_permissions=True)
def make_email_queue(email_queue):
name_list = []
for key, data in iteritems(email_queue):
name = frappe.db.get_value('Sales Invoice', {'offline_pos_name': key}, 'name')
if not name: continue
data = json.loads(data)
sender = frappe.session.user
print_format = "POS Invoice" if not cint(frappe.db.get_value('Print Format', 'POS Invoice', 'disabled')) else None
attachments = [frappe.attach_print('Sales Invoice', name, print_format=print_format)]
make(subject=data.get('subject'), content=data.get('content'), recipients=data.get('recipients'),
sender=sender, attachments=attachments, send_email=True,
doctype='Sales Invoice', name=name)
name_list.append(key)
return name_list
def validate_item(doc):
for item in doc.get('items'):
if not frappe.db.exists('Item', item.get('item_code')):
item_doc = frappe.new_doc('Item')
item_doc.name = item.get('item_code')
item_doc.item_code = item.get('item_code')
item_doc.item_name = item.get('item_name')
item_doc.description = item.get('description')
item_doc.stock_uom = item.get('stock_uom')
item_doc.uom = item.get('uom')
item_doc.item_group = item.get('item_group')
item_doc.append('item_defaults', {
"company": doc.get("company"),
"default_warehouse": item.get('warehouse')
})
item_doc.save(ignore_permissions=True)
frappe.db.commit()
def submit_invoice(si_doc, name, doc, name_list):
try:
si_doc.insert()
si_doc.submit()
frappe.db.commit()
name_list.append(name)
except Exception as e:
if frappe.message_log:
frappe.message_log.pop()
frappe.db.rollback()
frappe.log_error(frappe.get_traceback())
name_list = save_invoice(doc, name, name_list)
return name_list
def save_invoice(doc, name, name_list):
try:
if not frappe.db.exists('Sales Invoice', {'offline_pos_name': name}):
si = frappe.new_doc('Sales Invoice')
si.update(doc)
si.set_posting_time = 1
si.customer = get_customer_id(doc)
si.due_date = doc.get('posting_date')
si.flags.ignore_mandatory = True
si.insert(ignore_permissions=True)
frappe.db.commit()
name_list.append(name)
except Exception:
frappe.db.rollback()
frappe.log_error(frappe.get_traceback())
return name_list
|
neilLasrado/erpnext
|
erpnext/accounts/doctype/sales_invoice/pos.py
|
Python
|
gpl-3.0
| 21,154
|
---
layout: page
---
### Table des matières {.toggle}
- [Installation de Centreon 2.2 sur Ubuntu Server
10.04](centreon-ubuntu-install.html#installation-de-centreon-22-sur-ubuntu-server-1004)
- [Installation des
prérequis](centreon-ubuntu-install.html#installation-des-prerequis)
- [Récupération et extraction des
sources](centreon-ubuntu-install.html#recuperation-et-extraction-des-sources)
- [Création du template
d'installation](centreon-ubuntu-install.html#creation-du-template-d-installation)
- [Lancement de
l'installation](centreon-ubuntu-install.html#lancement-de-l-installation)
[](../../../_detail/nagios/centreon_logo.png@id=centreon%253Acentreon-ubuntu-install.html "nagios:centreon_logo.png")
Installation de Centreon 2.2 sur Ubuntu Server 10.04 {#installation-de-centreon-22-sur-ubuntu-server-1004 .sectionedit1}
====================================================
Comme tout bon admin je suis plutôt du genre feignant et je ne vais pas
faire un tutoriel détaillant toutes les options de centreon en mode
interactif. Afin de contourner cela nous allons utiliser le mode
“silencieux”, les réponses aux questions étant fournies par un fichier
de configuration (template).
Installation des prérequis {#installation-des-prerequis .sectionedit2}
--------------------------
- Je pars du principe que Nagios et les plugins nagios sont déjà
installés. Vous pouvez bien sur substituer Icinga à Nagios ou bien
utiliser le tout dernier fork de Nagios, Centreon Engine.
- ndomod et ndo2db doivent également être installés (par contre il est
inutile d’installer la base de donnée car centreon la crée lui même
sous le nom centstatus).
~~~ {.code .bash}
sudo apt-get install rrdtool snmpd php5-cli librrds-perl php-pear snmp snmpd php5-ldap php5-snmp libpng3 libconfig-inifiles-perl libcrypt-des-perl libdigest-hmac-perl libdigest-sha1-perl libgd-gd2-perl libio-socket-inet6-perl libnet-snmp-perl librrds-perl mailutils php5-gd php5-mysql snmptt
~~~
Nous allons faire en sorte que le démon snmpd soit un peu moins parano
(Debian way). Editer le fichier **/etc/snmp/snmpd.cfg**
- Rechercher et commenter la ligne : **com2sec paranoid default
public**
- Rechercher et decommenter la ligne : **\#com2sec readonly default
public**
- Redémarrer le démon snmp
~~~ {.code .bash}
sudo /etc/init.d/snmpd restart
~~~
Récupération et extraction des sources {#recuperation-et-extraction-des-sources .sectionedit3}
--------------------------------------
~~~
cd /tmp
wget http://download.centreon.com/centreon/centreon-2.2.0.tar.gz
tar zxvf centreon-2.2.0.tar.gz
cd centreon-2.2.0
~~~
Création du template d'installation {#creation-du-template-d-installation .sectionedit4}
-----------------------------------
- Voici la liste des variables devant être ajustée pour votre
environnement (pour ma part centreon s’installe dans /opt/centreon
et nagios dans /opt/monitor)
VARIABLE DEFINITION
------------------------ ---------------------------------------------------------
INSTALL\_DIR\_CENTREON Racine de l’installation de centreon
INSTALL\_DIR\_NAGIOS Ou est installé nagios (ou icinga ou centreon engine
NAGIOS\_ETC Ou se trouve la configuration Nagios
NAGIOS\_PLUGIN Ou se trouve les plugins
NAGIOS\_BINARY Chemin du binaire nagios (ou icinga ou centreon engine)
NAGIOSTATS\_BINARY Chemin du binaire nagios (ou icinga ou centreon engine)
NAGIOS\_VAR REPERTOIRE VAR DE NAGIOS
NAGIOS\_USER Identité sous laquelle est lancé nagios
NAGIOS\_GROUP Groupe d’appartenance de l’utilisateur executant nagios
NAGIOS\_P1\_FILE Chemin d’accés au script p1.pl
NDOMOD\_BINARY Chemin d’accés du module broker ndo (ndomod.o)
NAGIOS\_INIT\_SCRIPT Script de démarrage de nagios
- Si vous utilisez une architecture 64 bits vous devais modifier les
variables suivantes
VARIABLE DEFINITION
----------- --------------------------------------------
RRD\_PERL Chemin d’accès pour les librairie perl RRD
- Créer le fichier centreon.tpl dans /tmp/ et coller le contenu
suivant à l’intérieur.
~~~
# -*-Shell-script-*-
# SVN: $URL: http://svn.centreon.com/branches/centreon-2.1/tmpl/vardistrib/sample.tmpl $
# SVN: $Id: sample.tmpl 8586 2009-07-06 20:49:53Z watt $
#
# This file contain reconfigured variables used in install scripts
# By default, when you use ./install.sh -f sample.tmpl, you'll accept GPL licence.
#####################################################################
## Begin: Install modules
#####################################################################
## What do you want to install ?
## 0 = no, 1 = yes
## CentWeb: Web front Centreon for Nagios
PROCESS_CENTREON_WWW=1
## CentStorage: Log and charts archiving.
PROCESS_CENTSTORAGE=1
## CentCore: Distributed Monitoring engine.
PROCESS_CENTCORE=1
## CentPlugins: Centreon Plugins for nagios
PROCESS_CENTREON_PLUGINS=1
## CentTraps: Centreon Snmp traps process for nagios
PROCESS_CENTREON_SNMP_TRAPS=1
#####################################################################
## End: Install modules
#####################################################################
#####################################################################
## Begin: Default variables
#####################################################################
## Your default variables
## $BASE_DIR is the centreon source directory
LOG_DIR="$BASE_DIR/log"
LOG_FILE="$LOG_DIR/install_centreon.log"
## Don't change values above unless you perfectly understand
## what you are doing.
## Centreon temporary directory to work
TMP_DIR="/tmp/centreon-setup"
## default snmp config directory
SNMP_ETC="/etc/snmp/"
## a list of pear modules require by Centreon
PEAR_MODULES_LIST="pear.lst"
## forge install pear module (1=yes/0=no)
PEAR_AUTOINST=1
## no root user can be install centreon
#FORCE_NO_ROOT=0
#####################################################################
## End: Default variables
#####################################################################
#####################################################################
## Begin: Centreon preferences
#####################################################################
## Above variables are necessary to run a silent install
## Where you want to install Centreon (Centreon root directory)
INSTALL_DIR_CENTREON="/opt/centreon"
## Centreon log files directory
CENTREON_LOG="/opt/centreon/var/log"
## Centreon config files
CENTREON_ETC="/opt/centreon/etc"
## Centreon run dir (all .pid, .run, .lock)
CENTREON_RUNDIR="/opt/centreon/var/run"
## Centreon generation config directory
## filesGeneration and filesUpload
CENTREON_GENDIR="/opt/centreon/var/cache"
## CentStorage RRDs directory (where .rrd files go)
CENTSTORAGE_RRD="/opt/centreon/var/lib"
## path to centstorage binary
CENTSTORAGE_BINDIR="/opt/centreon/bin"
## path to centcore binary
CENTCORE_BINDIR="/opt/centreon/bin"
## libraries temporary files directory
CENTREON_VARLIB="/opt/centreon/var/lib"
## Some plugins require temporary datas to process output.
## These temp datas are store in the CENTPLUGINS_TMP path.
CENTPLUGINS_TMP="/opt/centreon/var/lib/centplugins"
## path to centpluginsTraps binaries
CENTPLUGINSTRAPS_BINDIR="/opt/centreon/bin"
## path for snmptt installation
SNMPTT_BINDIR="/usr/sbin"
## force install init script (install in init.d)
## Set to "1" to enable
CENTCORE_INSTALL_INIT=1
CENTSTORAGE_INSTALL_INIT=1
## force install run level for init script (add all link on rcX.d)
## Set to "1" to enable
CENTCORE_INSTALL_RUNLVL=1
CENTSTORAGE_INSTALL_RUNLVL=1
#####################################################################
## End: Centreon preferences
#####################################################################
#####################################################################
## Begin: Nagios preferences
#####################################################################
## Install directory
INSTALL_DIR_NAGIOS="/opt/monitor"
## Configuration directory
NAGIOS_ETC="/opt/monitor/etc"
## Plugins directory
NAGIOS_PLUGIN="/opt/monitor/libexec"
## Images (logos) directory
NAGIOS_IMG="/opt/monitor/var/www/images"
## The nagios binary (optional)
NAGIOS_BINARY="/opt/monitor/bin/nagios"
## The nagiostats binary (optional)
NAGIOSTATS_BINARY="/opt/monitor/bin/nagiostats"
## Logging directory
NAGIOS_VAR="/opt/monitor/var"
## Nagios user (optional)
NAGIOS_USER="nagios"
## If you want to force NAGIOS_USER, set FORCE_NAGIOS_USER to 1 (optional)
#FORCE_NAGIOS_USER=0
## Nagios group (optional)
NAGIOS_GROUP="nagios"
## If you want to force NAGIOS_GROUP, set FORCE_NAGIOS_GROUP to 1 (optional)
#FORCE_NAGIOS_GROUP=0
## Nagios p1.pl file (perl embedded)
NAGIOS_P1_FILE="/opt/monitor/bin/p1.pl"
## If you want to not use NDO (not recommended)
#FORCE_NOT_USE_NDO=1
## Nagios NDO module
NDOMOD_BINARY="/opt/monitor/bin/ndomod.o"
## Nagios init script (optional)
NAGIOS_INIT_SCRIPT="/etc/init.d/nagios"
#####################################################################
## End: Nagios preferences
#####################################################################
#####################################################################
## Begin: Apache preferences
#####################################################################
## Apache configuration directory (optional)
DIR_APACHE="/etc/apache2"
## Apache local specific configuration directory (optional)
DIR_APACHE_CONF="/etc/apache2/conf.d"
## Apache configuration file. Only file name. (optional)
APACHE_CONF="apache2.conf"
## Apache user (optional)
WEB_USER="www-data"
## Apache group (optional)
WEB_GROUP="www-data"
## Force apache reload (optional): set APACHE_RELOAD to 1
APACHE_RELOAD=1
#####################################################################
## End: Apache preferences
#####################################################################
#####################################################################
## Begin: Other binary
#####################################################################
## RRDTOOL (optional)
BIN_RRDTOOL="/usr/bin/rrdtool"
## Mail (optional)
BIN_MAIL="/usr/bin/mail"
## SSH (optional)
BIN_SSH="/usr/bin/ssh"
## SCP (optional)
BIN_SCP="/usr/bin/scp"
## PHP (optional)
PHP_BIN="/usr/bin/php"
## GREP (optional)
#GREP=""
## CAT (optional)
#CAT=""
## SED (optional)
#SED=""
## CHMOD (optional)
#CHMOD=""
## CHOWN (optional)
#CHOWN
#####################################################################
## End: Other binary
#####################################################################
#####################################################################
## Begin: Others
#####################################################################
## Perl path for RRDs.pm file
RRD_PERL="/usr/lib/perl5"
## Path to sudoers file (optional)
SUDO_FILE="/etc/sudoers"
## Force sudo config (optional)
FORCE_SUDO_CONF=1
## Apache user (optional)
WEB_USER="www-data"
## Apache group (optional)
WEB_GROUP="www-data"
## init script directory (optional)
INIT_D="/etc/init.d"
## cron config script directory (optional)
CRON_D="/etc/cron.d"
## Path for PEAR.php file
PEAR_PATH="/usr/share/php"
#####################################################################
## End: Others
#####################################################################
~~~
Lancement de l'installation {#lancement-de-l-installation .sectionedit7}
---------------------------
~~~
cd /tmp/centreon-2.0.0
sudo ./install.sh -v -f /tmp/centreon.tpl
~~~
- L’installeur ne devrais pas vous demander plus
- A la fin de l’installation il suffit d’ouvrir un navigateur et de
taper l’url suivante :
[http://[ipserveur]/centreon](http://[ipserveur]/centreon "http://[ipserveur]/centreon")
|
monitoring-fr/wiki
|
app/_export/xhtml/centreon/centreon-ubuntu-install.md
|
Markdown
|
gpl-3.0
| 11,978
|
import java.util.ArrayList;
import java.util.List;
public class SuperUglyNumber {
/**
* @param n: a positive integer
*
* @param primes: the given prime list
*
* @return: the nth super ugly number
*/
public int nthSuperUglyNumber(int n, int[] primes) {
if (n <= 0 || primes == null || primes.length == 0) {
return 0;
}
int[] index = new int[primes.length];
List<Integer> res = new ArrayList<>();
res.add(1);
int cur = 2;
while (res.size() < n) {
int min = Integer.MAX_VALUE;
for (int i = 0; i < primes.length; i++) {
while (primes[i] * res.get(index[i]) < cur) {
index[i]++;
}
min = Math.min(min, primes[i] * res.get(index[i]));
}
res.add(min);
cur = min + 1;
}
return res.get(n - 1);
}
}
|
gxwangdi/LintCode
|
518-Super-Ugly-Number/SuperUglyNumber.java
|
Java
|
gpl-3.0
| 759
|
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source
// & Institut Laue - Langevin
// SPDX - License - Identifier: GPL - 3.0 +
//
// This program is used to check if the compiler supports basic_string<wchar_t>
//
#include <string>
int main()
{
std::basic_string<wchar_t> s(L"s");
return 0;
}
//
// Local Variables:
// compile-command: "perl test.pl"
// End:
//
|
mganeva/mantid
|
Testing/Tools/cxxtest/test/wchar.cpp
|
C++
|
gpl-3.0
| 526
|
#include "src/v8.h"
#if V8_TARGET_ARCH_X87
// Copyright (c) 1994-2006 Sun Microsystems Inc.
// All Rights Reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// - Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// - Redistribution 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 Sun Microsystems or the names of 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.
// The original source code covered by the above license above has been modified
// significantly by Google Inc.
// Copyright 2012 the V8 project authors. All rights reserved.
#include "src/v8.h"
#if V8_TARGET_ARCH_X87
#include "src/base/bits.h"
#include "src/base/cpu.h"
#include "src/disassembler.h"
#include "src/macro-assembler.h"
namespace v8 {
namespace internal {
// -----------------------------------------------------------------------------
// Implementation of CpuFeatures
void CpuFeatures::ProbeImpl(bool cross_compile) {
base::CPU cpu;
// Only use statically determined features for cross compile (snapshot).
if (cross_compile) return;
}
void CpuFeatures::PrintTarget() { }
void CpuFeatures::PrintFeatures() { }
// -----------------------------------------------------------------------------
// Implementation of Displacement
void Displacement::init(Label* L, Type type) {
DCHECK(!L->is_bound());
int next = 0;
if (L->is_linked()) {
next = L->pos();
DCHECK(next > 0); // Displacements must be at positions > 0
}
// Ensure that we _never_ overflow the next field.
DCHECK(NextField::is_valid(Assembler::kMaximalBufferSize));
data_ = NextField::encode(next) | TypeField::encode(type);
}
// -----------------------------------------------------------------------------
// Implementation of RelocInfo
const int RelocInfo::kApplyMask =
RelocInfo::kCodeTargetMask | 1 << RelocInfo::RUNTIME_ENTRY |
1 << RelocInfo::JS_RETURN | 1 << RelocInfo::INTERNAL_REFERENCE |
1 << RelocInfo::DEBUG_BREAK_SLOT | 1 << RelocInfo::CODE_AGE_SEQUENCE;
bool RelocInfo::IsCodedSpecially() {
// The deserializer needs to know whether a pointer is specially coded. Being
// specially coded on IA32 means that it is a relative address, as used by
// branch instructions. These are also the ones that need changing when a
// code object moves.
return (1 << rmode_) & kApplyMask;
}
bool RelocInfo::IsInConstantPool() {
return false;
}
// Patch the code at the current PC with a call to the target address.
// Additional guard int3 instructions can be added if required.
void RelocInfo::PatchCodeWithCall(Address target, int guard_bytes) {
// Call instruction takes up 5 bytes and int3 takes up one byte.
static const int kCallCodeSize = 5;
int code_size = kCallCodeSize + guard_bytes;
// Create a code patcher.
CodePatcher patcher(pc_, code_size);
// Add a label for checking the size of the code used for returning.
#ifdef DEBUG
Label check_codesize;
patcher.masm()->bind(&check_codesize);
#endif
// Patch the code.
patcher.masm()->call(target, RelocInfo::NONE32);
// Check that the size of the code generated is as expected.
DCHECK_EQ(kCallCodeSize,
patcher.masm()->SizeOfCodeGeneratedSince(&check_codesize));
// Add the requested number of int3 instructions after the call.
DCHECK_GE(guard_bytes, 0);
for (int i = 0; i < guard_bytes; i++) {
patcher.masm()->int3();
}
}
// -----------------------------------------------------------------------------
// Implementation of Operand
Operand::Operand(Register base, int32_t disp, RelocInfo::Mode rmode) {
// [base + disp/r]
if (disp == 0 && RelocInfo::IsNone(rmode) && !base.is(ebp)) {
// [base]
set_modrm(0, base);
if (base.is(esp)) set_sib(times_1, esp, base);
} else if (is_int8(disp) && RelocInfo::IsNone(rmode)) {
// [base + disp8]
set_modrm(1, base);
if (base.is(esp)) set_sib(times_1, esp, base);
set_disp8(disp);
} else {
// [base + disp/r]
set_modrm(2, base);
if (base.is(esp)) set_sib(times_1, esp, base);
set_dispr(disp, rmode);
}
}
Operand::Operand(Register base,
Register index,
ScaleFactor scale,
int32_t disp,
RelocInfo::Mode rmode) {
DCHECK(!index.is(esp)); // illegal addressing mode
// [base + index*scale + disp/r]
if (disp == 0 && RelocInfo::IsNone(rmode) && !base.is(ebp)) {
// [base + index*scale]
set_modrm(0, esp);
set_sib(scale, index, base);
} else if (is_int8(disp) && RelocInfo::IsNone(rmode)) {
// [base + index*scale + disp8]
set_modrm(1, esp);
set_sib(scale, index, base);
set_disp8(disp);
} else {
// [base + index*scale + disp/r]
set_modrm(2, esp);
set_sib(scale, index, base);
set_dispr(disp, rmode);
}
}
Operand::Operand(Register index,
ScaleFactor scale,
int32_t disp,
RelocInfo::Mode rmode) {
DCHECK(!index.is(esp)); // illegal addressing mode
// [index*scale + disp/r]
set_modrm(0, esp);
set_sib(scale, index, ebp);
set_dispr(disp, rmode);
}
bool Operand::is_reg(Register reg) const {
return ((buf_[0] & 0xF8) == 0xC0) // addressing mode is register only.
&& ((buf_[0] & 0x07) == reg.code()); // register codes match.
}
bool Operand::is_reg_only() const {
return (buf_[0] & 0xF8) == 0xC0; // Addressing mode is register only.
}
Register Operand::reg() const {
DCHECK(is_reg_only());
return Register::from_code(buf_[0] & 0x07);
}
// -----------------------------------------------------------------------------
// Implementation of Assembler.
// Emit a single byte. Must always be inlined.
#define EMIT(x) \
*pc_++ = (x)
#ifdef GENERATED_CODE_COVERAGE
static void InitCoverageLog();
#endif
Assembler::Assembler(Isolate* isolate, void* buffer, int buffer_size)
: AssemblerBase(isolate, buffer, buffer_size),
positions_recorder_(this) {
// Clear the buffer in debug mode unless it was provided by the
// caller in which case we can't be sure it's okay to overwrite
// existing code in it; see CodePatcher::CodePatcher(...).
#ifdef DEBUG
if (own_buffer_) {
memset(buffer_, 0xCC, buffer_size_); // int3
}
#endif
reloc_info_writer.Reposition(buffer_ + buffer_size_, pc_);
#ifdef GENERATED_CODE_COVERAGE
InitCoverageLog();
#endif
}
void Assembler::GetCode(CodeDesc* desc) {
// Finalize code (at this point overflow() may be true, but the gap ensures
// that we are still not overlapping instructions and relocation info).
reloc_info_writer.Finish();
DCHECK(pc_ <= reloc_info_writer.pos()); // No overlap.
// Set up code descriptor.
desc->buffer = buffer_;
desc->buffer_size = buffer_size_;
desc->instr_size = pc_offset();
desc->reloc_size = (buffer_ + buffer_size_) - reloc_info_writer.pos();
desc->origin = this;
}
void Assembler::Align(int m) {
DCHECK(base::bits::IsPowerOfTwo32(m));
int mask = m - 1;
int addr = pc_offset();
Nop((m - (addr & mask)) & mask);
}
bool Assembler::IsNop(Address addr) {
Address a = addr;
while (*a == 0x66) a++;
if (*a == 0x90) return true;
if (a[0] == 0xf && a[1] == 0x1f) return true;
return false;
}
void Assembler::Nop(int bytes) {
EnsureSpace ensure_space(this);
// Older CPUs that do not support SSE2 may not support multibyte NOP
// instructions.
for (; bytes > 0; bytes--) {
EMIT(0x90);
}
return;
}
void Assembler::CodeTargetAlign() {
Align(16); // Preferred alignment of jump targets on ia32.
}
void Assembler::cpuid() {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xA2);
}
void Assembler::pushad() {
EnsureSpace ensure_space(this);
EMIT(0x60);
}
void Assembler::popad() {
EnsureSpace ensure_space(this);
EMIT(0x61);
}
void Assembler::pushfd() {
EnsureSpace ensure_space(this);
EMIT(0x9C);
}
void Assembler::popfd() {
EnsureSpace ensure_space(this);
EMIT(0x9D);
}
void Assembler::push(const Immediate& x) {
EnsureSpace ensure_space(this);
if (x.is_int8()) {
EMIT(0x6a);
EMIT(x.x_);
} else {
EMIT(0x68);
emit(x);
}
}
void Assembler::push_imm32(int32_t imm32) {
EnsureSpace ensure_space(this);
EMIT(0x68);
emit(imm32);
}
void Assembler::push(Register src) {
EnsureSpace ensure_space(this);
EMIT(0x50 | src.code());
}
void Assembler::push(const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0xFF);
emit_operand(esi, src);
}
void Assembler::pop(Register dst) {
DCHECK(reloc_info_writer.last_pc() != NULL);
EnsureSpace ensure_space(this);
EMIT(0x58 | dst.code());
}
void Assembler::pop(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0x8F);
emit_operand(eax, dst);
}
void Assembler::enter(const Immediate& size) {
EnsureSpace ensure_space(this);
EMIT(0xC8);
emit_w(size);
EMIT(0);
}
void Assembler::leave() {
EnsureSpace ensure_space(this);
EMIT(0xC9);
}
void Assembler::mov_b(Register dst, const Operand& src) {
CHECK(dst.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0x8A);
emit_operand(dst, src);
}
void Assembler::mov_b(const Operand& dst, int8_t imm8) {
EnsureSpace ensure_space(this);
EMIT(0xC6);
emit_operand(eax, dst);
EMIT(imm8);
}
void Assembler::mov_b(const Operand& dst, Register src) {
CHECK(src.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0x88);
emit_operand(src, dst);
}
void Assembler::mov_w(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x66);
EMIT(0x8B);
emit_operand(dst, src);
}
void Assembler::mov_w(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x66);
EMIT(0x89);
emit_operand(src, dst);
}
void Assembler::mov_w(const Operand& dst, int16_t imm16) {
EnsureSpace ensure_space(this);
EMIT(0x66);
EMIT(0xC7);
emit_operand(eax, dst);
EMIT(static_cast<int8_t>(imm16 & 0xff));
EMIT(static_cast<int8_t>(imm16 >> 8));
}
void Assembler::mov(Register dst, int32_t imm32) {
EnsureSpace ensure_space(this);
EMIT(0xB8 | dst.code());
emit(imm32);
}
void Assembler::mov(Register dst, const Immediate& x) {
EnsureSpace ensure_space(this);
EMIT(0xB8 | dst.code());
emit(x);
}
void Assembler::mov(Register dst, Handle<Object> handle) {
EnsureSpace ensure_space(this);
EMIT(0xB8 | dst.code());
emit(handle);
}
void Assembler::mov(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x8B);
emit_operand(dst, src);
}
void Assembler::mov(Register dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x89);
EMIT(0xC0 | src.code() << 3 | dst.code());
}
void Assembler::mov(const Operand& dst, const Immediate& x) {
EnsureSpace ensure_space(this);
EMIT(0xC7);
emit_operand(eax, dst);
emit(x);
}
void Assembler::mov(const Operand& dst, Handle<Object> handle) {
EnsureSpace ensure_space(this);
EMIT(0xC7);
emit_operand(eax, dst);
emit(handle);
}
void Assembler::mov(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x89);
emit_operand(src, dst);
}
void Assembler::movsx_b(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xBE);
emit_operand(dst, src);
}
void Assembler::movsx_w(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xBF);
emit_operand(dst, src);
}
void Assembler::movzx_b(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xB6);
emit_operand(dst, src);
}
void Assembler::movzx_w(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xB7);
emit_operand(dst, src);
}
void Assembler::cld() {
EnsureSpace ensure_space(this);
EMIT(0xFC);
}
void Assembler::rep_movs() {
EnsureSpace ensure_space(this);
EMIT(0xF3);
EMIT(0xA5);
}
void Assembler::rep_stos() {
EnsureSpace ensure_space(this);
EMIT(0xF3);
EMIT(0xAB);
}
void Assembler::stos() {
EnsureSpace ensure_space(this);
EMIT(0xAB);
}
void Assembler::xchg(Register dst, Register src) {
EnsureSpace ensure_space(this);
if (src.is(eax) || dst.is(eax)) { // Single-byte encoding.
EMIT(0x90 | (src.is(eax) ? dst.code() : src.code()));
} else {
EMIT(0x87);
EMIT(0xC0 | src.code() << 3 | dst.code());
}
}
void Assembler::xchg(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x87);
emit_operand(dst, src);
}
void Assembler::adc(Register dst, int32_t imm32) {
EnsureSpace ensure_space(this);
emit_arith(2, Operand(dst), Immediate(imm32));
}
void Assembler::adc(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x13);
emit_operand(dst, src);
}
void Assembler::add(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x03);
emit_operand(dst, src);
}
void Assembler::add(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x01);
emit_operand(src, dst);
}
void Assembler::add(const Operand& dst, const Immediate& x) {
DCHECK(reloc_info_writer.last_pc() != NULL);
EnsureSpace ensure_space(this);
emit_arith(0, dst, x);
}
void Assembler::and_(Register dst, int32_t imm32) {
and_(dst, Immediate(imm32));
}
void Assembler::and_(Register dst, const Immediate& x) {
EnsureSpace ensure_space(this);
emit_arith(4, Operand(dst), x);
}
void Assembler::and_(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x23);
emit_operand(dst, src);
}
void Assembler::and_(const Operand& dst, const Immediate& x) {
EnsureSpace ensure_space(this);
emit_arith(4, dst, x);
}
void Assembler::and_(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x21);
emit_operand(src, dst);
}
void Assembler::cmpb(const Operand& op, int8_t imm8) {
EnsureSpace ensure_space(this);
if (op.is_reg(eax)) {
EMIT(0x3C);
} else {
EMIT(0x80);
emit_operand(edi, op); // edi == 7
}
EMIT(imm8);
}
void Assembler::cmpb(const Operand& op, Register reg) {
CHECK(reg.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0x38);
emit_operand(reg, op);
}
void Assembler::cmpb(Register reg, const Operand& op) {
CHECK(reg.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0x3A);
emit_operand(reg, op);
}
void Assembler::cmpw(const Operand& op, Immediate imm16) {
DCHECK(imm16.is_int16());
EnsureSpace ensure_space(this);
EMIT(0x66);
EMIT(0x81);
emit_operand(edi, op);
emit_w(imm16);
}
void Assembler::cmp(Register reg, int32_t imm32) {
EnsureSpace ensure_space(this);
emit_arith(7, Operand(reg), Immediate(imm32));
}
void Assembler::cmp(Register reg, Handle<Object> handle) {
EnsureSpace ensure_space(this);
emit_arith(7, Operand(reg), Immediate(handle));
}
void Assembler::cmp(Register reg, const Operand& op) {
EnsureSpace ensure_space(this);
EMIT(0x3B);
emit_operand(reg, op);
}
void Assembler::cmp(const Operand& op, const Immediate& imm) {
EnsureSpace ensure_space(this);
emit_arith(7, op, imm);
}
void Assembler::cmp(const Operand& op, Handle<Object> handle) {
EnsureSpace ensure_space(this);
emit_arith(7, op, Immediate(handle));
}
void Assembler::cmpb_al(const Operand& op) {
EnsureSpace ensure_space(this);
EMIT(0x38); // CMP r/m8, r8
emit_operand(eax, op); // eax has same code as register al.
}
void Assembler::cmpw_ax(const Operand& op) {
EnsureSpace ensure_space(this);
EMIT(0x66);
EMIT(0x39); // CMP r/m16, r16
emit_operand(eax, op); // eax has same code as register ax.
}
void Assembler::dec_b(Register dst) {
CHECK(dst.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0xFE);
EMIT(0xC8 | dst.code());
}
void Assembler::dec_b(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xFE);
emit_operand(ecx, dst);
}
void Assembler::dec(Register dst) {
EnsureSpace ensure_space(this);
EMIT(0x48 | dst.code());
}
void Assembler::dec(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xFF);
emit_operand(ecx, dst);
}
void Assembler::cdq() {
EnsureSpace ensure_space(this);
EMIT(0x99);
}
void Assembler::idiv(const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
emit_operand(edi, src);
}
void Assembler::div(const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
emit_operand(esi, src);
}
void Assembler::imul(Register reg) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
EMIT(0xE8 | reg.code());
}
void Assembler::imul(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xAF);
emit_operand(dst, src);
}
void Assembler::imul(Register dst, Register src, int32_t imm32) {
imul(dst, Operand(src), imm32);
}
void Assembler::imul(Register dst, const Operand& src, int32_t imm32) {
EnsureSpace ensure_space(this);
if (is_int8(imm32)) {
EMIT(0x6B);
emit_operand(dst, src);
EMIT(imm32);
} else {
EMIT(0x69);
emit_operand(dst, src);
emit(imm32);
}
}
void Assembler::inc(Register dst) {
EnsureSpace ensure_space(this);
EMIT(0x40 | dst.code());
}
void Assembler::inc(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xFF);
emit_operand(eax, dst);
}
void Assembler::lea(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x8D);
emit_operand(dst, src);
}
void Assembler::mul(Register src) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
EMIT(0xE0 | src.code());
}
void Assembler::neg(Register dst) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
EMIT(0xD8 | dst.code());
}
void Assembler::neg(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
emit_operand(ebx, dst);
}
void Assembler::not_(Register dst) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
EMIT(0xD0 | dst.code());
}
void Assembler::not_(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xF7);
emit_operand(edx, dst);
}
void Assembler::or_(Register dst, int32_t imm32) {
EnsureSpace ensure_space(this);
emit_arith(1, Operand(dst), Immediate(imm32));
}
void Assembler::or_(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0B);
emit_operand(dst, src);
}
void Assembler::or_(const Operand& dst, const Immediate& x) {
EnsureSpace ensure_space(this);
emit_arith(1, dst, x);
}
void Assembler::or_(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x09);
emit_operand(src, dst);
}
void Assembler::rcl(Register dst, uint8_t imm8) {
EnsureSpace ensure_space(this);
DCHECK(is_uint5(imm8)); // illegal shift count
if (imm8 == 1) {
EMIT(0xD1);
EMIT(0xD0 | dst.code());
} else {
EMIT(0xC1);
EMIT(0xD0 | dst.code());
EMIT(imm8);
}
}
void Assembler::rcr(Register dst, uint8_t imm8) {
EnsureSpace ensure_space(this);
DCHECK(is_uint5(imm8)); // illegal shift count
if (imm8 == 1) {
EMIT(0xD1);
EMIT(0xD8 | dst.code());
} else {
EMIT(0xC1);
EMIT(0xD8 | dst.code());
EMIT(imm8);
}
}
void Assembler::ror(const Operand& dst, uint8_t imm8) {
EnsureSpace ensure_space(this);
DCHECK(is_uint5(imm8)); // illegal shift count
if (imm8 == 1) {
EMIT(0xD1);
emit_operand(ecx, dst);
} else {
EMIT(0xC1);
emit_operand(ecx, dst);
EMIT(imm8);
}
}
void Assembler::ror_cl(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xD3);
emit_operand(ecx, dst);
}
void Assembler::sar(const Operand& dst, uint8_t imm8) {
EnsureSpace ensure_space(this);
DCHECK(is_uint5(imm8)); // illegal shift count
if (imm8 == 1) {
EMIT(0xD1);
emit_operand(edi, dst);
} else {
EMIT(0xC1);
emit_operand(edi, dst);
EMIT(imm8);
}
}
void Assembler::sar_cl(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xD3);
emit_operand(edi, dst);
}
void Assembler::sbb(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x1B);
emit_operand(dst, src);
}
void Assembler::shld(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xA5);
emit_operand(dst, src);
}
void Assembler::shl(const Operand& dst, uint8_t imm8) {
EnsureSpace ensure_space(this);
DCHECK(is_uint5(imm8)); // illegal shift count
if (imm8 == 1) {
EMIT(0xD1);
emit_operand(esp, dst);
} else {
EMIT(0xC1);
emit_operand(esp, dst);
EMIT(imm8);
}
}
void Assembler::shl_cl(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xD3);
emit_operand(esp, dst);
}
void Assembler::shrd(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xAD);
emit_operand(dst, src);
}
void Assembler::shr(const Operand& dst, uint8_t imm8) {
EnsureSpace ensure_space(this);
DCHECK(is_uint5(imm8)); // illegal shift count
if (imm8 == 1) {
EMIT(0xD1);
emit_operand(ebp, dst);
} else {
EMIT(0xC1);
emit_operand(ebp, dst);
EMIT(imm8);
}
}
void Assembler::shr_cl(const Operand& dst) {
EnsureSpace ensure_space(this);
EMIT(0xD3);
emit_operand(ebp, dst);
}
void Assembler::sub(const Operand& dst, const Immediate& x) {
EnsureSpace ensure_space(this);
emit_arith(5, dst, x);
}
void Assembler::sub(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x2B);
emit_operand(dst, src);
}
void Assembler::sub(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x29);
emit_operand(src, dst);
}
void Assembler::test(Register reg, const Immediate& imm) {
if (RelocInfo::IsNone(imm.rmode_) && is_uint8(imm.x_)) {
test_b(reg, imm.x_);
return;
}
EnsureSpace ensure_space(this);
// This is not using emit_arith because test doesn't support
// sign-extension of 8-bit operands.
if (reg.is(eax)) {
EMIT(0xA9);
} else {
EMIT(0xF7);
EMIT(0xC0 | reg.code());
}
emit(imm);
}
void Assembler::test(Register reg, const Operand& op) {
EnsureSpace ensure_space(this);
EMIT(0x85);
emit_operand(reg, op);
}
void Assembler::test_b(Register reg, const Operand& op) {
CHECK(reg.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0x84);
emit_operand(reg, op);
}
void Assembler::test(const Operand& op, const Immediate& imm) {
if (op.is_reg_only()) {
test(op.reg(), imm);
return;
}
if (RelocInfo::IsNone(imm.rmode_) && is_uint8(imm.x_)) {
return test_b(op, imm.x_);
}
EnsureSpace ensure_space(this);
EMIT(0xF7);
emit_operand(eax, op);
emit(imm);
}
void Assembler::test_b(Register reg, uint8_t imm8) {
EnsureSpace ensure_space(this);
// Only use test against byte for registers that have a byte
// variant: eax, ebx, ecx, and edx.
if (reg.is(eax)) {
EMIT(0xA8);
EMIT(imm8);
} else if (reg.is_byte_register()) {
emit_arith_b(0xF6, 0xC0, reg, imm8);
} else {
EMIT(0xF7);
EMIT(0xC0 | reg.code());
emit(imm8);
}
}
void Assembler::test_b(const Operand& op, uint8_t imm8) {
if (op.is_reg_only()) {
test_b(op.reg(), imm8);
return;
}
EnsureSpace ensure_space(this);
EMIT(0xF6);
emit_operand(eax, op);
EMIT(imm8);
}
void Assembler::xor_(Register dst, int32_t imm32) {
EnsureSpace ensure_space(this);
emit_arith(6, Operand(dst), Immediate(imm32));
}
void Assembler::xor_(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x33);
emit_operand(dst, src);
}
void Assembler::xor_(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x31);
emit_operand(src, dst);
}
void Assembler::xor_(const Operand& dst, const Immediate& x) {
EnsureSpace ensure_space(this);
emit_arith(6, dst, x);
}
void Assembler::bt(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xA3);
emit_operand(src, dst);
}
void Assembler::bts(const Operand& dst, Register src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xAB);
emit_operand(src, dst);
}
void Assembler::bsr(Register dst, const Operand& src) {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0xBD);
emit_operand(dst, src);
}
void Assembler::hlt() {
EnsureSpace ensure_space(this);
EMIT(0xF4);
}
void Assembler::int3() {
EnsureSpace ensure_space(this);
EMIT(0xCC);
}
void Assembler::nop() {
EnsureSpace ensure_space(this);
EMIT(0x90);
}
void Assembler::ret(int imm16) {
EnsureSpace ensure_space(this);
DCHECK(is_uint16(imm16));
if (imm16 == 0) {
EMIT(0xC3);
} else {
EMIT(0xC2);
EMIT(imm16 & 0xFF);
EMIT((imm16 >> 8) & 0xFF);
}
}
void Assembler::ud2() {
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0x0B);
}
// Labels refer to positions in the (to be) generated code.
// There are bound, linked, and unused labels.
//
// Bound labels refer to known positions in the already
// generated code. pos() is the position the label refers to.
//
// Linked labels refer to unknown positions in the code
// to be generated; pos() is the position of the 32bit
// Displacement of the last instruction using the label.
void Assembler::print(Label* L) {
if (L->is_unused()) {
PrintF("unused label\n");
} else if (L->is_bound()) {
PrintF("bound label to %d\n", L->pos());
} else if (L->is_linked()) {
Label l = *L;
PrintF("unbound label");
while (l.is_linked()) {
Displacement disp = disp_at(&l);
PrintF("@ %d ", l.pos());
disp.print();
PrintF("\n");
disp.next(&l);
}
} else {
PrintF("label in inconsistent state (pos = %d)\n", L->pos_);
}
}
void Assembler::bind_to(Label* L, int pos) {
EnsureSpace ensure_space(this);
DCHECK(0 <= pos && pos <= pc_offset()); // must have a valid binding position
while (L->is_linked()) {
Displacement disp = disp_at(L);
int fixup_pos = L->pos();
if (disp.type() == Displacement::CODE_ABSOLUTE) {
long_at_put(fixup_pos, reinterpret_cast<int>(buffer_ + pos));
internal_reference_positions_.push_back(fixup_pos);
} else if (disp.type() == Displacement::CODE_RELATIVE) {
// Relative to Code* heap object pointer.
long_at_put(fixup_pos, pos + Code::kHeaderSize - kHeapObjectTag);
} else {
if (disp.type() == Displacement::UNCONDITIONAL_JUMP) {
DCHECK(byte_at(fixup_pos - 1) == 0xE9); // jmp expected
}
// Relative address, relative to point after address.
int imm32 = pos - (fixup_pos + sizeof(int32_t));
long_at_put(fixup_pos, imm32);
}
disp.next(L);
}
while (L->is_near_linked()) {
int fixup_pos = L->near_link_pos();
int offset_to_next =
static_cast<int>(*reinterpret_cast<int8_t*>(addr_at(fixup_pos)));
DCHECK(offset_to_next <= 0);
// Relative address, relative to point after address.
int disp = pos - fixup_pos - sizeof(int8_t);
CHECK(0 <= disp && disp <= 127);
set_byte_at(fixup_pos, disp);
if (offset_to_next < 0) {
L->link_to(fixup_pos + offset_to_next, Label::kNear);
} else {
L->UnuseNear();
}
}
L->bind_to(pos);
}
void Assembler::bind(Label* L) {
EnsureSpace ensure_space(this);
DCHECK(!L->is_bound()); // label can only be bound once
bind_to(L, pc_offset());
}
void Assembler::call(Label* L) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
if (L->is_bound()) {
const int long_size = 5;
int offs = L->pos() - pc_offset();
DCHECK(offs <= 0);
// 1110 1000 #32-bit disp.
EMIT(0xE8);
emit(offs - long_size);
} else {
// 1110 1000 #32-bit disp.
EMIT(0xE8);
emit_disp(L, Displacement::OTHER);
}
}
void Assembler::call(byte* entry, RelocInfo::Mode rmode) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
DCHECK(!RelocInfo::IsCodeTarget(rmode));
EMIT(0xE8);
if (RelocInfo::IsRuntimeEntry(rmode)) {
emit(reinterpret_cast<uint32_t>(entry), rmode);
} else {
emit(entry - (pc_ + sizeof(int32_t)), rmode);
}
}
int Assembler::CallSize(const Operand& adr) {
// Call size is 1 (opcode) + adr.len_ (operand).
return 1 + adr.len_;
}
void Assembler::call(const Operand& adr) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
EMIT(0xFF);
emit_operand(edx, adr);
}
int Assembler::CallSize(Handle<Code> code, RelocInfo::Mode rmode) {
return 1 /* EMIT */ + sizeof(uint32_t) /* emit */;
}
void Assembler::call(Handle<Code> code,
RelocInfo::Mode rmode,
TypeFeedbackId ast_id) {
positions_recorder()->WriteRecordedPositions();
EnsureSpace ensure_space(this);
DCHECK(RelocInfo::IsCodeTarget(rmode)
|| rmode == RelocInfo::CODE_AGE_SEQUENCE);
EMIT(0xE8);
emit(code, rmode, ast_id);
}
void Assembler::jmp(Label* L, Label::Distance distance) {
EnsureSpace ensure_space(this);
if (L->is_bound()) {
const int short_size = 2;
const int long_size = 5;
int offs = L->pos() - pc_offset();
DCHECK(offs <= 0);
if (is_int8(offs - short_size)) {
// 1110 1011 #8-bit disp.
EMIT(0xEB);
EMIT((offs - short_size) & 0xFF);
} else {
// 1110 1001 #32-bit disp.
EMIT(0xE9);
emit(offs - long_size);
}
} else if (distance == Label::kNear) {
EMIT(0xEB);
emit_near_disp(L);
} else {
// 1110 1001 #32-bit disp.
EMIT(0xE9);
emit_disp(L, Displacement::UNCONDITIONAL_JUMP);
}
}
void Assembler::jmp(byte* entry, RelocInfo::Mode rmode) {
EnsureSpace ensure_space(this);
DCHECK(!RelocInfo::IsCodeTarget(rmode));
EMIT(0xE9);
if (RelocInfo::IsRuntimeEntry(rmode)) {
emit(reinterpret_cast<uint32_t>(entry), rmode);
} else {
emit(entry - (pc_ + sizeof(int32_t)), rmode);
}
}
void Assembler::jmp(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xFF);
emit_operand(esp, adr);
}
void Assembler::jmp(Handle<Code> code, RelocInfo::Mode rmode) {
EnsureSpace ensure_space(this);
DCHECK(RelocInfo::IsCodeTarget(rmode));
EMIT(0xE9);
emit(code, rmode);
}
void Assembler::j(Condition cc, Label* L, Label::Distance distance) {
EnsureSpace ensure_space(this);
DCHECK(0 <= cc && static_cast<int>(cc) < 16);
if (L->is_bound()) {
const int short_size = 2;
const int long_size = 6;
int offs = L->pos() - pc_offset();
DCHECK(offs <= 0);
if (is_int8(offs - short_size)) {
// 0111 tttn #8-bit disp
EMIT(0x70 | cc);
EMIT((offs - short_size) & 0xFF);
} else {
// 0000 1111 1000 tttn #32-bit disp
EMIT(0x0F);
EMIT(0x80 | cc);
emit(offs - long_size);
}
} else if (distance == Label::kNear) {
EMIT(0x70 | cc);
emit_near_disp(L);
} else {
// 0000 1111 1000 tttn #32-bit disp
// Note: could eliminate cond. jumps to this jump if condition
// is the same however, seems to be rather unlikely case.
EMIT(0x0F);
EMIT(0x80 | cc);
emit_disp(L, Displacement::OTHER);
}
}
void Assembler::j(Condition cc, byte* entry, RelocInfo::Mode rmode) {
EnsureSpace ensure_space(this);
DCHECK((0 <= cc) && (static_cast<int>(cc) < 16));
// 0000 1111 1000 tttn #32-bit disp.
EMIT(0x0F);
EMIT(0x80 | cc);
if (RelocInfo::IsRuntimeEntry(rmode)) {
emit(reinterpret_cast<uint32_t>(entry), rmode);
} else {
emit(entry - (pc_ + sizeof(int32_t)), rmode);
}
}
void Assembler::j(Condition cc, Handle<Code> code) {
EnsureSpace ensure_space(this);
// 0000 1111 1000 tttn #32-bit disp
EMIT(0x0F);
EMIT(0x80 | cc);
emit(code, RelocInfo::CODE_TARGET);
}
// FPU instructions.
void Assembler::fld(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD9, 0xC0, i);
}
void Assembler::fstp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDD, 0xD8, i);
}
void Assembler::fld1() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xE8);
}
void Assembler::fldpi() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xEB);
}
void Assembler::fldz() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xEE);
}
void Assembler::fldln2() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xED);
}
void Assembler::fld_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xD9);
emit_operand(eax, adr);
}
void Assembler::fld_d(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDD);
emit_operand(eax, adr);
}
void Assembler::fstp_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xD9);
emit_operand(ebx, adr);
}
void Assembler::fst_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xD9);
emit_operand(edx, adr);
}
void Assembler::fldcw(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xD9);
emit_operand(ebp, adr);
}
void Assembler::fnstcw(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xD9);
emit_operand(edi, adr);
}
void Assembler::fstp_d(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDD);
emit_operand(ebx, adr);
}
void Assembler::fst_d(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDD);
emit_operand(edx, adr);
}
void Assembler::fild_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDB);
emit_operand(eax, adr);
}
void Assembler::fild_d(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDF);
emit_operand(ebp, adr);
}
void Assembler::fistp_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDB);
emit_operand(ebx, adr);
}
void Assembler::fisttp_s(const Operand& adr) {
DCHECK(IsEnabled(SSE3));
EnsureSpace ensure_space(this);
EMIT(0xDB);
emit_operand(ecx, adr);
}
void Assembler::fisttp_d(const Operand& adr) {
DCHECK(IsEnabled(SSE3));
EnsureSpace ensure_space(this);
EMIT(0xDD);
emit_operand(ecx, adr);
}
void Assembler::fist_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDB);
emit_operand(edx, adr);
}
void Assembler::fistp_d(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDF);
emit_operand(edi, adr);
}
void Assembler::fabs() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xE1);
}
void Assembler::fchs() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xE0);
}
void Assembler::fsqrt() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xFA);
}
void Assembler::fcos() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xFF);
}
void Assembler::fsin() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xFE);
}
void Assembler::fptan() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xF2);
}
void Assembler::fyl2x() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xF1);
}
void Assembler::f2xm1() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xF0);
}
void Assembler::fscale() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xFD);
}
void Assembler::fninit() {
EnsureSpace ensure_space(this);
EMIT(0xDB);
EMIT(0xE3);
}
void Assembler::fadd(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xC0, i);
}
void Assembler::fadd_i(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD8, 0xC0, i);
}
void Assembler::fadd_d(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDC);
emit_operand(eax, adr);
}
void Assembler::fsub(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xE8, i);
}
void Assembler::fsub_i(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD8, 0xE0, i);
}
void Assembler::fisub_s(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDA);
emit_operand(esp, adr);
}
void Assembler::fmul_i(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD8, 0xC8, i);
}
void Assembler::fmul(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xC8, i);
}
void Assembler::fdiv(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDC, 0xF8, i);
}
void Assembler::fdiv_i(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD8, 0xF0, i);
}
void Assembler::faddp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xC0, i);
}
void Assembler::fsubp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xE8, i);
}
void Assembler::fsubrp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xE0, i);
}
void Assembler::fmulp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xC8, i);
}
void Assembler::fdivp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDE, 0xF8, i);
}
void Assembler::fprem() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xF8);
}
void Assembler::fprem1() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xF5);
}
void Assembler::fxch(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xD9, 0xC8, i);
}
void Assembler::fincstp() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xF7);
}
void Assembler::ffree(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDD, 0xC0, i);
}
void Assembler::ftst() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xE4);
}
void Assembler::fxam() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xE5);
}
void Assembler::fucomp(int i) {
EnsureSpace ensure_space(this);
emit_farith(0xDD, 0xE8, i);
}
void Assembler::fucompp() {
EnsureSpace ensure_space(this);
EMIT(0xDA);
EMIT(0xE9);
}
void Assembler::fucomi(int i) {
EnsureSpace ensure_space(this);
EMIT(0xDB);
EMIT(0xE8 + i);
}
void Assembler::fucomip() {
EnsureSpace ensure_space(this);
EMIT(0xDF);
EMIT(0xE9);
}
void Assembler::fcompp() {
EnsureSpace ensure_space(this);
EMIT(0xDE);
EMIT(0xD9);
}
void Assembler::fnstsw_ax() {
EnsureSpace ensure_space(this);
EMIT(0xDF);
EMIT(0xE0);
}
void Assembler::fwait() {
EnsureSpace ensure_space(this);
EMIT(0x9B);
}
void Assembler::frndint() {
EnsureSpace ensure_space(this);
EMIT(0xD9);
EMIT(0xFC);
}
void Assembler::fnclex() {
EnsureSpace ensure_space(this);
EMIT(0xDB);
EMIT(0xE2);
}
void Assembler::fnsave(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDD);
emit_operand(esi, adr);
}
void Assembler::frstor(const Operand& adr) {
EnsureSpace ensure_space(this);
EMIT(0xDD);
emit_operand(esp, adr);
}
void Assembler::sahf() {
EnsureSpace ensure_space(this);
EMIT(0x9E);
}
void Assembler::setcc(Condition cc, Register reg) {
DCHECK(reg.is_byte_register());
EnsureSpace ensure_space(this);
EMIT(0x0F);
EMIT(0x90 | cc);
EMIT(0xC0 | reg.code());
}
void Assembler::GrowBuffer() {
DCHECK(buffer_overflow());
if (!own_buffer_) FATAL("external code buffer is too small");
// Compute new buffer size.
CodeDesc desc; // the new buffer
desc.buffer_size = 2 * buffer_size_;
// Some internal data structures overflow for very large buffers,
// they must ensure that kMaximalBufferSize is not too large.
if ((desc.buffer_size > kMaximalBufferSize) ||
(desc.buffer_size > isolate()->heap()->MaxOldGenerationSize())) {
V8::FatalProcessOutOfMemory("Assembler::GrowBuffer");
}
// Set up new buffer.
desc.buffer = NewArray<byte>(desc.buffer_size);
desc.instr_size = pc_offset();
desc.reloc_size = (buffer_ + buffer_size_) - (reloc_info_writer.pos());
// Clear the buffer in debug mode. Use 'int3' instructions to make
// sure to get into problems if we ever run uninitialized code.
#ifdef DEBUG
memset(desc.buffer, 0xCC, desc.buffer_size);
#endif
// Copy the data.
int pc_delta = desc.buffer - buffer_;
int rc_delta = (desc.buffer + desc.buffer_size) - (buffer_ + buffer_size_);
MemMove(desc.buffer, buffer_, desc.instr_size);
MemMove(rc_delta + reloc_info_writer.pos(), reloc_info_writer.pos(),
desc.reloc_size);
DeleteArray(buffer_);
buffer_ = desc.buffer;
buffer_size_ = desc.buffer_size;
pc_ += pc_delta;
reloc_info_writer.Reposition(reloc_info_writer.pos() + rc_delta,
reloc_info_writer.last_pc() + pc_delta);
// Relocate internal references.
for (auto pos : internal_reference_positions_) {
int32_t* p = reinterpret_cast<int32_t*>(buffer_ + pos);
*p += pc_delta;
}
DCHECK(!buffer_overflow());
}
void Assembler::emit_arith_b(int op1, int op2, Register dst, int imm8) {
DCHECK(is_uint8(op1) && is_uint8(op2)); // wrong opcode
DCHECK(is_uint8(imm8));
DCHECK((op1 & 0x01) == 0); // should be 8bit operation
EMIT(op1);
EMIT(op2 | dst.code());
EMIT(imm8);
}
void Assembler::emit_arith(int sel, Operand dst, const Immediate& x) {
DCHECK((0 <= sel) && (sel <= 7));
Register ireg = { sel };
if (x.is_int8()) {
EMIT(0x83); // using a sign-extended 8-bit immediate.
emit_operand(ireg, dst);
EMIT(x.x_ & 0xFF);
} else if (dst.is_reg(eax)) {
EMIT((sel << 3) | 0x05); // short form if the destination is eax.
emit(x);
} else {
EMIT(0x81); // using a literal 32-bit immediate.
emit_operand(ireg, dst);
emit(x);
}
}
void Assembler::emit_operand(Register reg, const Operand& adr) {
const unsigned length = adr.len_;
DCHECK(length > 0);
// Emit updated ModRM byte containing the given register.
pc_[0] = (adr.buf_[0] & ~0x38) | (reg.code() << 3);
// Emit the rest of the encoded operand.
for (unsigned i = 1; i < length; i++) pc_[i] = adr.buf_[i];
pc_ += length;
// Emit relocation information if necessary.
if (length >= sizeof(int32_t) && !RelocInfo::IsNone(adr.rmode_)) {
pc_ -= sizeof(int32_t); // pc_ must be *at* disp32
RecordRelocInfo(adr.rmode_);
if (adr.rmode_ == RelocInfo::INTERNAL_REFERENCE) { // Fixup for labels
emit_label(*reinterpret_cast<Label**>(pc_));
} else {
pc_ += sizeof(int32_t);
}
}
}
void Assembler::emit_label(Label* label) {
if (label->is_bound()) {
internal_reference_positions_.push_back(pc_offset());
emit(reinterpret_cast<uint32_t>(buffer_ + label->pos()));
} else {
emit_disp(label, Displacement::CODE_ABSOLUTE);
}
}
void Assembler::emit_farith(int b1, int b2, int i) {
DCHECK(is_uint8(b1) && is_uint8(b2)); // wrong opcode
DCHECK(0 <= i && i < 8); // illegal stack offset
EMIT(b1);
EMIT(b2 + i);
}
void Assembler::db(uint8_t data) {
EnsureSpace ensure_space(this);
EMIT(data);
}
void Assembler::dd(uint32_t data) {
EnsureSpace ensure_space(this);
emit(data);
}
void Assembler::dd(Label* label) {
EnsureSpace ensure_space(this);
RecordRelocInfo(RelocInfo::INTERNAL_REFERENCE);
emit_label(label);
}
void Assembler::RecordRelocInfo(RelocInfo::Mode rmode, intptr_t data) {
DCHECK(!RelocInfo::IsNone(rmode));
// Don't record external references unless the heap will be serialized.
if (rmode == RelocInfo::EXTERNAL_REFERENCE &&
!serializer_enabled() && !emit_debug_code()) {
return;
}
RelocInfo rinfo(pc_, rmode, data, NULL);
reloc_info_writer.Write(&rinfo);
}
Handle<ConstantPoolArray> Assembler::NewConstantPool(Isolate* isolate) {
// No out-of-line constant pool support.
DCHECK(!FLAG_enable_ool_constant_pool);
return isolate->factory()->empty_constant_pool_array();
}
void Assembler::PopulateConstantPool(ConstantPoolArray* constant_pool) {
// No out-of-line constant pool support.
DCHECK(!FLAG_enable_ool_constant_pool);
return;
}
#ifdef GENERATED_CODE_COVERAGE
static FILE* coverage_log = NULL;
static void InitCoverageLog() {
char* file_name = getenv("V8_GENERATED_CODE_COVERAGE_LOG");
if (file_name != NULL) {
coverage_log = fopen(file_name, "aw+");
}
}
void LogGeneratedCodeCoverage(const char* file_line) {
const char* return_address = (&file_line)[-1];
char* push_insn = const_cast<char*>(return_address - 12);
push_insn[0] = 0xeb; // Relative branch insn.
push_insn[1] = 13; // Skip over coverage insns.
if (coverage_log != NULL) {
fprintf(coverage_log, "%s\n", file_line);
fflush(coverage_log);
}
}
#endif
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_X87
#endif // V8_TARGET_ARCH_X87
|
zhangf911/fibjs
|
vender/v8/src/x87/assembler-x87.cc
|
C++
|
gpl-3.0
| 45,133
|
{% load i18n %}
{% load geonode_auth %}
<p><b>{% trans "Abstract:" %}</b>
{% if rec.identification.abstract %}
{{rec.identification.abstract}}
{% else %}
<em>{% trans "No abstract is provided for this layer." %}</em>
{% endif %}
</p>
<p><b>{% trans "Provided by:" %}</b>
{% if rec.contact.name %} {# and rec.attribution.href %} #}
{% if rec.contact.onlineresource %}
<a href="{{ rec.contact.onlineresource.url }}">{{ rec.contact.name }}</a>
{% else %}
{{ rec.contact.name }}
{% endif %}
{% else %}
<em>{% trans "No attribution information is provided for this layer." %}</em>
{% endif %}
</p>
<p><b>{% trans "Metadata Links:" %}</b>
{% for link in rec.metadata_links %}
<a href="{{link.2}}">{{link.1}}</a>
{% empty %}
<em>{% trans "No metadata URLs are defined for this layer." %}</em>
{% endfor %}
</p>
<p><b>{% trans "Keywords:" %}</b>
{% for kw in rec.identification.keywords.list %}
{{kw}}{% if not forloop.last %}, {% endif %}
{% empty %}
<em>{% trans "No keywords are listed for this layer." %}</em>
{% endfor %}
</p>
{% if layer_is_remote %}
<p><b>{% trans "Download:" %}</b>
{% for link in extra_links.download %}
<a href="{{link.2}}" class="download {{link.0}}">{{link.1}}</a>
{% empty %}
<em>{% trans "No download URLs are defined for this layer." %}</em>
{% endfor %}
</p>
{% if rec.distribution.onlineresource.url %}
<p><a href="{{ rec.distribution.onlineresource.url }}">
{% trans "Visit originating site for more information about this layer." %}
</a></p>
{% endif %}
{% else %}
{% has_obj_perm user layer "maps.view_layer" as can_view %}
{% if can_view %}
<p><b>{% trans "Download:" %}</b>
{% for link in extra_links.download %}
<a href="{{link.2}}" class="download {{link.0}}">{{link.1}}</a>
{% empty %}
<em>{% trans "No download URLs are defined for this layer." %}</em>
{% endfor %}
</p>
{% if rec.distribution.onlineresource.url %}
<p><a href="{{ rec.distribution.onlineresource.url }}">
{% trans "Click here for more information about this layer." %}
</a></p>
{% endif %}
{% else %}
<p>{% trans "You do not have permission to view or download this layer" %}</p>
{% endif %}
{% endif %}
|
makinacorpus/geonode
|
src/GeoNodePy/geonode/templates/maps/search_result_snippet.html
|
HTML
|
gpl-3.0
| 2,238
|
/*
This file is part of Helio Workstation.
Helio 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.
Helio 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 Helio. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
class CommandPaletteAction final : public ReferenceCountedObject
{
public:
using Callback = Function<bool(TextEditor &ed)>;
using Ptr = ReferenceCountedObjectPtr<CommandPaletteAction>;
static CommandPaletteAction::Ptr action(String text, String hint, float order);
CommandPaletteAction::Ptr withCallback(Callback callback);
CommandPaletteAction::Ptr withColour(const Colour &colour);
CommandPaletteAction::Ptr unfiltered();
const String &getName() const noexcept;
const String &getHint() const noexcept;
const Colour &getColor() const noexcept;
const Callback getCallback() const noexcept;
const bool isUnfiltered() const noexcept;
void setMatch(int score, const uint8 *matches);
int getMatchScore() const noexcept;
float getOrder() const noexcept;
const GlyphArrangement &getGlyphArrangement() const noexcept;
private:
CommandPaletteAction() = delete;
CommandPaletteAction(String text, String hint, float order);
String name;
String hint;
Colour colour = Colours::grey;
Callback callback;
int commandId = 0;
bool shouldClosePalette = true;
bool required = false;
GlyphArrangement highlightedMatch;
int matchScore = 0;
// actions will be sorted by match, as user is entering the search text,
// but we may also need ordering for the full list or items with the same match;
// the context for this variable should be defined by action provider,
// for example, timeline events will be ordered by position at the timeline
// (see CommandPaletteActionSortByMatch)
float order = 0.f;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CommandPaletteAction)
};
class CommandPaletteActionsProvider
{
public:
CommandPaletteActionsProvider() = default;
virtual ~CommandPaletteActionsProvider() = default;
using Prefix = juce_wchar;
virtual bool usesPrefix(const Prefix prefix) const = 0;
using Actions = ReferenceCountedArray<CommandPaletteAction>;
const Actions &getFilteredActions() const
{
return this->filteredActions;
}
virtual void updateFilter(const String &pattern, bool skipPrefix);
virtual void clearFilter();
protected:
virtual const Actions &getActions() const = 0;
private:
Actions filteredActions;
JUCE_DECLARE_WEAK_REFERENCEABLE(CommandPaletteActionsProvider)
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(CommandPaletteActionsProvider)
};
|
peterrudenko/helio-workstation
|
Source/Core/CommandPalette/CommandPaletteActionsProvider.h
|
C
|
gpl-3.0
| 3,152
|
package fi.internetix.edelphi.jsons.resources;
import java.util.Locale;
import fi.internetix.edelphi.DelfoiActionName;
import fi.internetix.edelphi.EdelfoiStatusCode;
import fi.internetix.edelphi.dao.resources.ResourceDAO;
import fi.internetix.edelphi.dao.resources.ResourceLockDAO;
import fi.internetix.edelphi.dao.users.UserDAO;
import fi.internetix.edelphi.domainmodel.base.Delfoi;
import fi.internetix.edelphi.domainmodel.panels.Panel;
import fi.internetix.edelphi.domainmodel.resources.Resource;
import fi.internetix.edelphi.domainmodel.resources.ResourceLock;
import fi.internetix.edelphi.domainmodel.users.User;
import fi.internetix.edelphi.i18n.Messages;
import fi.internetix.edelphi.jsons.JSONController;
import fi.internetix.edelphi.utils.ResourceLockUtils;
import fi.internetix.edelphi.utils.ResourceUtils;
import fi.internetix.smvc.AccessDeniedException;
import fi.internetix.smvc.LoginRequiredException;
import fi.internetix.smvc.SmvcRuntimeException;
import fi.internetix.smvc.controllers.JSONRequestContext;
import fi.internetix.smvc.controllers.RequestContext;
public class TouchResourceLockJSONRequestController extends JSONController {
@Override
public void authorize(RequestContext requestContext) throws LoginRequiredException, AccessDeniedException {
ResourceDAO resourceDAO = new ResourceDAO();
Long resourceId = requestContext.getLong("resourceId");
if (resourceId != null) {
Resource resource = resourceDAO.findById(resourceId);
Panel resourcePanel = ResourceUtils.getResourcePanel(resource);
if (resourcePanel != null) {
authorizePanel(requestContext, resourcePanel, DelfoiActionName.MANAGE_PANEL_MATERIALS.toString());
}
else {
Delfoi resourceDelfoi = ResourceUtils.getResourceDelfoi(resource);
authorizeDelfoi(requestContext, resourceDelfoi, DelfoiActionName.MANAGE_DELFOI_MATERIALS.toString());
}
}
}
@Override
public void process(JSONRequestContext jsonRequestContext) {
UserDAO userDAO = new UserDAO();
ResourceDAO resourceDAO = new ResourceDAO();
ResourceLockDAO resourceLockDAO = new ResourceLockDAO();
Long resourceId = jsonRequestContext.getLong("resourceId");
User loggedUser = userDAO.findById(jsonRequestContext.getLoggedUserId());
if (resourceId != null) {
Locale locale = jsonRequestContext.getRequest().getLocale();
Resource resource = resourceDAO.findById(resourceId);
ResourceLock resourceLock = resourceLockDAO.findByResource(resource);
if (resourceLock == null) {
Messages messages = Messages.getInstance();
throw new SmvcRuntimeException(EdelfoiStatusCode.RESOURCE_LOCK_NOT_FOUND, messages.getText(locale, "exception.1022.resourceLockNotFound"));
}
else {
if (!resourceLock.getCreator().getId().equals(loggedUser.getId()))
throw new AccessDeniedException(locale);
ResourceLockUtils.touchResourceLock(resource);
}
}
}
}
|
otavanopisto/edelphi
|
edelphi/src/main/java/fi/internetix/edelphi/jsons/resources/TouchResourceLockJSONRequestController.java
|
Java
|
gpl-3.0
| 2,991
|
<?php
class ControllerPaymentWorldPay extends Controller {
public function index() {
$data['button_confirm'] = $this->language->get('button_confirm');
$this->load->model('checkout/order');
$order_info = $this->model_checkout_order->getOrder($this->session->data['order_id']);
if (!$this->config->get('worldpay_test')) {
$data['action'] = 'https://secure.worldpay.com/wcc/purchase';
} else {
$data['action'] = 'https://secure-test.worldpay.com/wcc/purchase';
}
$data['merchant'] = $this->config->get('worldpay_merchant');
$data['order_id'] = $order_info['order_id'];
$data['amount'] = $this->currency->format($order_info['total'], $order_info['currency_code'], $order_info['currency_value'], false);
$data['currency'] = $order_info['currency_code'];
$data['description'] = $this->config->get('config_name') . ' - #' . $order_info['order_id'];
$data['name'] = $order_info['payment_firstname'] . ' ' . $order_info['payment_lastname'];
if (!$order_info['payment_address_2']) {
$data['address'] = $order_info['payment_address_1'] . ', ' . $order_info['payment_city'] . ', ' . $order_info['payment_zone'];
} else {
$data['address'] = $order_info['payment_address_1'] . ', ' . $order_info['payment_address_2'] . ', ' . $order_info['payment_city'] . ', ' . $order_info['payment_zone'];
}
$data['postcode'] = $order_info['payment_postcode'];
$data['country'] = $order_info['payment_iso_code_2'];
$data['telephone'] = $order_info['telephone'];
$data['email'] = $order_info['email'];
$data['test'] = $this->config->get('worldpay_test');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/worldpay.tpl')) {
return $this->load->view($this->config->get('config_template') . '/template/payment/worldpay.tpl', $data);
} else {
return $this->load->view('default/template/payment/worldpay.tpl', $data);
}
}
public function callback() {
$this->load->language('payment/worldpay');
$data['title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_name'));
if (!$this->request->server['HTTPS']) {
$data['base'] = $this->config->get('config_url');
} else {
$data['base'] = $this->config->get('config_ssl');
}
$data['language'] = $this->language->get('code');
$data['direction'] = $this->language->get('direction');
$data['heading_title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_name'));
$data['text_response'] = $this->language->get('text_response');
$data['text_success'] = $this->language->get('text_success');
$data['text_success_wait'] = sprintf($this->language->get('text_success_wait'), $this->url->link('checkout/success'));
$data['text_failure'] = $this->language->get('text_failure');
$data['text_failure_wait'] = sprintf($this->language->get('text_failure_wait'), $this->url->link('checkout/checkout', '', 'SSL'));
if (isset($this->request->post['transStatus']) && $this->request->post['transStatus'] == 'Y') {
$message = '';
if (isset($this->request->post['transId'])) {
$message .= 'transId: ' . $this->request->post['transId'] . "\n";
}
if (isset($this->request->post['transStatus'])) {
$message .= 'transStatus: ' . $this->request->post['transStatus'] . "\n";
}
if (isset($this->request->post['countryMatch'])) {
$message .= 'countryMatch: ' . $this->request->post['countryMatch'] . "\n";
}
if (isset($this->request->post['AVS'])) {
$message .= 'AVS: ' . $this->request->post['AVS'] . "\n";
}
if (isset($this->request->post['rawAuthCode'])) {
$message .= 'rawAuthCode: ' . $this->request->post['rawAuthCode'] . "\n";
}
if (isset($this->request->post['authMode'])) {
$message .= 'authMode: ' . $this->request->post['authMode'] . "\n";
}
if (isset($this->request->post['rawAuthMessage'])) {
$message .= 'rawAuthMessage: ' . $this->request->post['rawAuthMessage'] . "\n";
}
if (isset($this->request->post['wafMerchMessage'])) {
$message .= 'wafMerchMessage: ' . $this->request->post['wafMerchMessage'] . "\n";
}
$this->load->model('checkout/order');
// If returned successful but callbackPW doesn't match, set order to pendind and record reason
if (isset($this->request->post['callbackPW']) && ($this->request->post['callbackPW'] == $this->config->get('worldpay_password'))) {
$this->model_checkout_order->addOrderHistory($this->request->post['cartId'], $this->config->get('worldpay_order_status_id'), $message, false);
} else {
$this->model_checkout_order->addOrderHistory($this->request->post['cartId'], $this->config->get('config_order_status_id'), $this->language->get('text_pw_mismatch'));
}
$data['continue'] = $this->url->link('checkout/success');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/worldpay_success.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/payment/worldpay_success.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/payment/worldpay_success.tpl', $data));
}
} else {
$data['continue'] = $this->url->link('checkout/cart');
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/payment/worldpay_failure.tpl')) {
$this->response->setOutput($this->load->view($this->config->get('config_template') . '/template/payment/worldpay_failure.tpl', $data));
} else {
$this->response->setOutput($this->load->view('default/template/payment/worldpay_failure.tpl', $data));
}
}
}
}
|
opencart-rewrite/opencart-rewrite
|
upload/catalog/controller/payment/worldpay.php
|
PHP
|
gpl-3.0
| 6,380
|
// Copyright ©2016 The gonum 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 testlapack
import (
"fmt"
"math"
"math/rand"
"testing"
"gonum.org/v1/gonum/blas"
"gonum.org/v1/gonum/blas/blas64"
)
type Dlatrder interface {
Dlatrd(uplo blas.Uplo, n, nb int, a []float64, lda int, e, tau, w []float64, ldw int)
}
func DlatrdTest(t *testing.T, impl Dlatrder) {
rnd := rand.New(rand.NewSource(1))
for _, uplo := range []blas.Uplo{blas.Upper, blas.Lower} {
for _, test := range []struct {
n, nb, lda, ldw int
}{
{5, 2, 0, 0},
{5, 5, 0, 0},
{5, 3, 10, 11},
{5, 5, 10, 11},
} {
n := test.n
nb := test.nb
lda := test.lda
if lda == 0 {
lda = n
}
ldw := test.ldw
if ldw == 0 {
ldw = nb
}
a := make([]float64, n*lda)
for i := range a {
a[i] = rnd.NormFloat64()
}
e := make([]float64, n-1)
for i := range e {
e[i] = math.NaN()
}
tau := make([]float64, n-1)
for i := range tau {
tau[i] = math.NaN()
}
w := make([]float64, n*ldw)
for i := range w {
w[i] = math.NaN()
}
aCopy := make([]float64, len(a))
copy(aCopy, a)
impl.Dlatrd(uplo, n, nb, a, lda, e, tau, w, ldw)
// Construct Q.
ldq := n
q := blas64.General{
Rows: n,
Cols: n,
Stride: ldq,
Data: make([]float64, n*ldq),
}
for i := 0; i < n; i++ {
q.Data[i*ldq+i] = 1
}
if uplo == blas.Upper {
for i := n - 1; i >= n-nb; i-- {
if i == 0 {
continue
}
h := blas64.General{
Rows: n, Cols: n, Stride: n, Data: make([]float64, n*n),
}
for j := 0; j < n; j++ {
h.Data[j*n+j] = 1
}
v := blas64.Vector{
Inc: 1,
Data: make([]float64, n),
}
for j := 0; j < i-1; j++ {
v.Data[j] = a[j*lda+i]
}
v.Data[i-1] = 1
blas64.Ger(-tau[i-1], v, v, h)
qTmp := blas64.General{
Rows: n, Cols: n, Stride: n, Data: make([]float64, n*n),
}
copy(qTmp.Data, q.Data)
blas64.Gemm(blas.NoTrans, blas.NoTrans, 1, qTmp, h, 0, q)
}
} else {
for i := 0; i < nb; i++ {
if i == n-1 {
continue
}
h := blas64.General{
Rows: n, Cols: n, Stride: n, Data: make([]float64, n*n),
}
for j := 0; j < n; j++ {
h.Data[j*n+j] = 1
}
v := blas64.Vector{
Inc: 1,
Data: make([]float64, n),
}
v.Data[i+1] = 1
for j := i + 2; j < n; j++ {
v.Data[j] = a[j*lda+i]
}
blas64.Ger(-tau[i], v, v, h)
qTmp := blas64.General{
Rows: n, Cols: n, Stride: n, Data: make([]float64, n*n),
}
copy(qTmp.Data, q.Data)
blas64.Gemm(blas.NoTrans, blas.NoTrans, 1, qTmp, h, 0, q)
}
}
errStr := fmt.Sprintf("isUpper = %v, n = %v, nb = %v", uplo == blas.Upper, n, nb)
if !isOrthonormal(q) {
t.Errorf("Q not orthonormal. %s", errStr)
}
aGen := genFromSym(blas64.Symmetric{N: n, Stride: lda, Uplo: uplo, Data: aCopy})
if !dlatrdCheckDecomposition(t, uplo, n, nb, e, tau, a, lda, aGen, q) {
t.Errorf("Decomposition mismatch. %s", errStr)
}
}
}
}
// dlatrdCheckDecomposition checks that the first nb rows have been successfully
// reduced.
func dlatrdCheckDecomposition(t *testing.T, uplo blas.Uplo, n, nb int, e, tau, a []float64, lda int, aGen, q blas64.General) bool {
// Compute Q^T * A * Q.
tmp := blas64.General{
Rows: n,
Cols: n,
Stride: n,
Data: make([]float64, n*n),
}
ans := blas64.General{
Rows: n,
Cols: n,
Stride: n,
Data: make([]float64, n*n),
}
blas64.Gemm(blas.Trans, blas.NoTrans, 1, q, aGen, 0, tmp)
blas64.Gemm(blas.NoTrans, blas.NoTrans, 1, tmp, q, 0, ans)
// Compare with T.
if uplo == blas.Upper {
for i := n - 1; i >= n-nb; i-- {
for j := 0; j < n; j++ {
v := ans.Data[i*ans.Stride+j]
switch {
case i == j:
if math.Abs(v-a[i*lda+j]) > 1e-10 {
return false
}
case i == j-1:
if math.Abs(a[i*lda+j]-1) > 1e-10 {
return false
}
if math.Abs(v-e[i]) > 1e-10 {
return false
}
case i == j+1:
default:
if math.Abs(v) > 1e-10 {
return false
}
}
}
}
} else {
for i := 0; i < nb; i++ {
for j := 0; j < n; j++ {
v := ans.Data[i*ans.Stride+j]
switch {
case i == j:
if math.Abs(v-a[i*lda+j]) > 1e-10 {
return false
}
case i == j-1:
case i == j+1:
if math.Abs(a[i*lda+j]-1) > 1e-10 {
return false
}
if math.Abs(v-e[i-1]) > 1e-10 {
return false
}
default:
if math.Abs(v) > 1e-10 {
return false
}
}
}
}
}
return true
}
// genFromSym constructs a (symmetric) general matrix from the data in the
// symmetric.
// TODO(btracey): Replace other constructions of this with a call to this function.
func genFromSym(a blas64.Symmetric) blas64.General {
n := a.N
lda := a.Stride
uplo := a.Uplo
b := blas64.General{
Rows: n,
Cols: n,
Stride: n,
Data: make([]float64, n*n),
}
for i := 0; i < n; i++ {
for j := i; j < n; j++ {
v := a.Data[i*lda+j]
if uplo == blas.Lower {
v = a.Data[j*lda+i]
}
b.Data[i*n+j] = v
b.Data[j*n+i] = v
}
}
return b
}
|
pts-eduardoacuna/pachy-learning
|
vendor/gonum.org/v1/gonum/lapack/testlapack/dlatrd.go
|
GO
|
gpl-3.0
| 5,259
|
#import <objc/objc.h>
#import "UIKit/UIKit.h"
//
typedef NS_ENUM(NSInteger, ToastViewType)
{
ToastViewDefault,
ToastViewInfo = ToastViewDefault,
ToastViewError,
ToastViewCancel = ToastViewError,
ToastViewSuccess,
ToastViewLoading,
};
//
@interface ToastView : UIView
{
}
- (id)initWithTitle:(NSString *)title type:(ToastViewType)type;
+ (ToastView *)toastWithTitle:(NSString *)title type:(ToastViewType)type;
+ (ToastView *)toastWithTitle:(NSString *)title;
+ (ToastView *)toastWithInfo:(NSString *)info;
+ (ToastView *)toastWithError:(NSString *)error;
+ (ToastView *)toastWithCancel:(NSString *)cancel;
+ (ToastView *)toastWithSuccess:(NSString *)success;
+ (ToastView *)toastWithLoading:(NSString *)loading;
+ (ToastView *)toastWithLoading;
+ (void)dismissToast;
@end
//
@interface UIView (ToastView)
- (ToastView *)toastWithTitle:(NSString *)title type:(ToastViewType)type;
- (ToastView *)toastWithTitle:(NSString *)title;
- (ToastView *)toastWithInfo:(NSString *)info;
- (ToastView *)toastWithError:(NSString *)error;
- (ToastView *)toastWithCancel:(NSString *)cancel;
- (ToastView *)toastWithSuccess:(NSString *)success;
- (ToastView *)toastWithLoading:(NSString *)loading;
- (ToastView *)toastWithLoading;
- (void)dismissToast;
@end
|
qii/AirBooru
|
AirBooru/Sources/Support/Library/ToastView.h
|
C
|
gpl-3.0
| 1,251
|
package leetcode;
import java.util.Hashtable;
/**
* Created by Yulin on 6/09/2017.
*/
public class TwoSum {
public int[] twoSum(int[] nums, int target){
Hashtable<Integer, Integer> map = new Hashtable<Integer, Integer>();
for (int i = 0; i < nums.length; i++){
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++){
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i){
return new int[] {i, map.get(complement)};
}
}
throw new IllegalArgumentException("No two sum solution");
}
public static void main(String[] args){
int[] input = new int[] {1, 2, 3};
int target = 5;
int[] result = new TwoSum().twoSum(input, target);
for (int i : result){
System.out.println(i);
}
}
}
|
Nirvana-Y/leetcode
|
src/leetcode/TwoSum.java
|
Java
|
gpl-3.0
| 912
|
import userHelper
import serverPackets
import exceptions
import glob
import consoleHelper
import bcolors
import locationHelper
import countryHelper
import time
import generalFunctions
import channelJoinEvent
def handle(flaskRequest):
# Data to return
responseTokenString = "ayy"
responseData = bytes()
# The IP for your private network, to get the right location you should use your
# public IP (e.g http://ping.eu)
localIP = "172.20.7.107" # The ip you log in with
publicIP = "8.8.8.8" # google lul
# Get IP from flask request
requestIP = flaskRequest.headers.get("X-Forwarded-For")
if requestIP == localIP:
requestIP = publicIP
# Console output
print("> Accepting connection from {}...".format(requestIP))
# Split POST body so we can get username/password/hardware data
# 2:-3 thing is because requestData has some escape stuff that we don't need
loginData = str(flaskRequest.data)[2:-3].split("\\n")
# Process login
print("> Processing login request for {}...".format(loginData[0]))
try:
# If true, print error to console
err = False
# Try to get the ID from username
userID = userHelper.getID(str(loginData[0]))
if userID == False:
# Invalid username
raise exceptions.loginFailedException()
if userHelper.checkLogin(userID, loginData[1]) == False:
# Invalid password
raise exceptions.loginFailedException()
# Make sure we are not banned
userAllowed = userHelper.getAllowed(userID)
if userAllowed == 0:
# Banned
raise exceptions.loginBannedException()
# Activate user (obviously not the banned.-.)
# But those who created an account without logging in through bancho yet
if userAllowed == 2:
# Not activated yet
userHelper.Activate(userID)
# No login errors!
# Delete old tokens for that user and generate a new one
glob.tokens.deleteOldTokens(userID)
responseToken = glob.tokens.addToken(userID)
responseTokenString = responseToken.token
# Get silence end
userSilenceEnd = max(0, userHelper.getSilenceEnd(userID)-int(time.time()))
# Get supporter/GMT
userRank = userHelper.getRankPrivileges(userID)
userGMT = False
userSupporter = True
if userRank >= 3:
userGMT = True
# Server restarting check
if glob.restarting == True:
raise exceptions.banchoRestartingException()
# Maintenance check
if glob.banchoConf.config["banchoMaintenance"] == True:
if userGMT == False:
# We are not mod/admin, delete token, send notification and logout
glob.tokens.deleteToken(responseTokenString)
raise exceptions.banchoMaintenanceException()
else:
# We are mod/admin, send warning notification and continue
responseToken.enqueue(serverPackets.notification("Bancho is in maintenance mode. Only mods/admins have full access to the server.\nType !system maintenance off in chat to turn off maintenance mode."))
# Send all needed login packets
responseToken.enqueue(serverPackets.silenceEndTime(userSilenceEnd))
responseToken.enqueue(serverPackets.userID(userID))
responseToken.enqueue(serverPackets.protocolVersion())
responseToken.enqueue(serverPackets.userSupporterGMT(userSupporter, userGMT))
responseToken.enqueue(serverPackets.userPanel(userID))
responseToken.enqueue(serverPackets.userStats(userID))
# Channel info end (before starting!?! wtf bancho?)
responseToken.enqueue(serverPackets.channelInfoEnd())
# Default opened channels
# TODO: Configurable default channels
channelJoinEvent.joinChannel(responseToken, "#osu")
channelJoinEvent.joinChannel(responseToken, "#announce")
if userRank >= 3:
# Join admin chanenl if we are mod/admin
# TODO: Separate channels for mods and admins
channelJoinEvent.joinChannel(responseToken, "#admin")
# Output channels info
for key, value in glob.channels.channels.items():
if value.publicRead == True:
responseToken.enqueue(serverPackets.channelInfo(key))
responseToken.enqueue(serverPackets.friendList(userID))
# Send main menu icon and login notification if needed
if glob.banchoConf.config["menuIcon"] != "":
responseToken.enqueue(serverPackets.mainMenuIcon(glob.banchoConf.config["menuIcon"]))
if glob.banchoConf.config["loginNotification"] != "":
responseToken.enqueue(serverPackets.notification(glob.banchoConf.config["loginNotification"]))
# Get everyone else userpanel
# TODO: Better online users handling
for key, value in glob.tokens.tokens.items():
responseToken.enqueue(serverPackets.userPanel(value.userID))
responseToken.enqueue(serverPackets.userStats(value.userID))
# Send online users IDs array
responseToken.enqueue(serverPackets.onlineUsers())
if requestIP == None:
# Get Last 'usual' IP from user (default 8.8.8.8 / USA / Google)
requestIP = userHelper.logInIP(userID)
# Get location and country from ip.zxq.co or database
if generalFunctions.stringToBool(glob.conf.config["server"]["localizeusers"]):
# Get location and country from IP
location = locationHelper.getLocation(requestIP)
country = countryHelper.getCountryID(locationHelper.getCountry(requestIP))
else:
# Set location to 0,0 and get country from db
print("[!] Location skipped")
location = [0,0]
country = countryHelper.getCountryID(userHelper.getCountry(userID))
# Set location and country
responseToken.setLocation(location)
responseToken.setCountry(country)
# Send to everyone our userpanel and userStats (so they now we have logged in)
glob.tokens.enqueueAll(serverPackets.userPanel(userID))
glob.tokens.enqueueAll(serverPackets.userStats(userID))
# Set reponse data to right value and reset our queue
responseData = responseToken.queue
responseToken.resetQueue()
# Some things about IP
logInIP = userHelper.logInIP(userID)
logInIP = logInIP['ip']
print("[!] First IP: "+format(logInIP))
if logInIP != requestIP:
# We'll inform...
message = "This is not your usual IP! Remember we don't like multiaccounting! (ignore if you did not)"
responseToken.enqueue(serverPackets.notification(message))
# Print logged in message
consoleHelper.printColored("> {} logged in ({})".format(loginData[0], responseToken.token), bcolors.GREEN)
except exceptions.loginFailedException:
# Login failed error packet
# (we don't use enqueue because we don't have a token since login has failed)
err = True
responseData += serverPackets.loginFailed()
except exceptions.loginBannedException:
# Login banned error packet
err = True
responseData += serverPackets.loginBanned()
except exceptions.banchoMaintenanceException:
# Bancho is in maintenance mode
responseData += serverPackets.notification("Our bancho server is in maintenance mode. Please try to login again later.")
responseData += serverPackets.loginError()
except exceptions.banchoRestartingException:
# Bancho is restarting
responseData += serverPackets.notification("Bancho is restarting. Try again in a few minutes.")
responseData += serverPackets.loginError()
finally:
# Print login failed message to console if needed
if err == True:
consoleHelper.printColored("> {}'s login failed".format(loginData[0]), bcolors.YELLOW)
return (responseTokenString, responseData)
|
RlSEN/bannedcho
|
c.ppy.sh/loginEvent.py
|
Python
|
gpl-3.0
| 7,180
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.