code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
<?php
/**
* Description of Resume
*
* @author greg
* @package
*/
class Wpjb_Form_Abstract_Resume extends Daq_Form_ObjectAbstract
{
protected $_custom = "wpjb_form_resume";
protected $_key = "resume";
protected $_model = "Wpjb_Model_Resume";
public function _exclude()
{
if($this->_object->getId()) {
return array("id" => $this->_object->getId());
} else {
return array();
}
}
public function init()
{
$this->_upload = array(
"path" => wpjb_upload_dir("{object}", "{field}", "{id}", "basedir"),
"object" => "resume",
"field" => null,
"id" => wpjb_upload_id($this->getId())
);
$this->addGroup("_internal", "");
$this->addGroup("default", __("Account Information", "wpjobboard"));
$this->addGroup("location", __("Address", "wpjobboard"));
$this->addGroup("resume", __("Resume", "wpjobboard"));
$this->addGroup("experience", __("Experience", "wpjobboard"));
$this->addGroup("education", __("Education", "wpjobboard"));
$this->_group["experience"]->setAlwaysVisible(true);
$this->_group["education"]->setAlwaysVisible(true);
$user = new WP_User($this->getObject()->user_id);
$e = $this->create("first_name");
$e->setLabel(__("First Name", "wpjobboard"));
$e->setRequired(true);
$e->setValue($user->first_name);
$this->addElement($e, "default");
$e = $this->create("last_name");
$e->setLabel(__("Last Name", "wpjobboard"));
$e->setRequired(true);
$e->setValue($user->last_name);
$this->addElement($e, "default");
$def = wpjb_locale();
$e = $this->create("candidate_country", "select");
$e->setLabel(__("Country", "wpjobboard"));
$e->setValue(($this->_object->candidate_country) ? $this->_object->candidate_country : $def);
$e->addOptions(wpjb_form_get_countries());
$e->addClass("wpjb-location-country");
$this->addElement($e, "location");
$e = $this->create("candidate_state");
$e->setLabel(__("State", "wpjobboard"));
$e->setValue($this->_object->candidate_state);
$e->addClass("wpjb-location-state");
$this->addElement($e, "location");
$e = $this->create("candidate_zip_code");
$e->setLabel(__("Zip-Code", "wpjobboard"));
$e->addValidator(new Daq_Validate_StringLength(null, 20));
$e->setValue($this->_object->candidate_zip_code);
$this->addElement($e, "location");
$e = $this->create("candidate_location");
$e->setValue($this->_object->candidate_location);
$e->setRequired(true);
$e->setLabel(__("City", "wpjobboard"));
$e->setHint(__('For example: "Chicago", "London", "Anywhere" or "Telecommute".', "wpjobboard"));
$e->addValidator(new Daq_Validate_StringLength(null, 120));
$e->addClass("wpjb-location-city");
$this->addElement($e, "location");
$e = $this->create("user_email");
$e->setRequired(true);
$e->setLabel(__("Email Address", "wpjobboard"));
$e->setHint(__('This field will be shown only to registered employers.', "wpjobboard"));
$e->addValidator(new Daq_Validate_Email(array("exclude"=>$user->ID)));
$e->setValue($user->user_email);
$this->addElement($e, "default");
$e = $this->create("phone");
$e->setLabel(__("Phone Number", "wpjobboard"));
$e->setHint(__('This field will be shown only to registered employers.', "wpjobboard"));
$e->setValue($this->_object->phone);
$this->addElement($e, "default");
$e = $this->create("user_url");
$e->setLabel(__("Website", "wpjobboard"));
$e->setHint(__('This field will be shown only to registered employers.', "wpjobboard"));
$e->addFilter(new Daq_Filter_WP_Url());
$e->addValidator(new Daq_Validate_Url());
$e->setValue($user->user_url);
$this->addElement($e, "default");
$e = $this->create("is_public", "checkbox");
$e->setLabel(__("Privacy", "wpjobboard"));
$e->addOption(1, 1, __("Show my resume in search results.", "wpjobboard"));
$e->setValue($this->_object->is_public);
$e->addFilter(new Daq_Filter_Int());
$this->addElement($e, "default");
$e = $this->create("is_active", "checkbox");
$e->setValue($this->_object->is_active);
$e->setLabel(__("Status", "wpjobboard"));
$e->addOption(1, 1, __("Resume is approved.", "wpjobboard"));
$this->addElement($e, "_internal");
$e = $this->create("modified_at", "text_date");
$e->setDateFormat(wpjb_date_format());
$e->setValue($this->ifNew(date("Y-m-d"), $this->_object->modified_at));
$this->addElement($e, "_internal");
$e = $this->create("created_at", "text_date");
$e->setDateFormat(wpjb_date_format());
$e->setValue($this->ifNew(date("Y-m-d"), $this->_object->created_at));
$this->addElement($e, "_internal");
$e = $this->create("image", "file");
$e->setLabel(__("Your Photo", "wpjobboard"));;
$e->addValidator(new Daq_Validate_File_Default());
$e->addValidator(new Daq_Validate_File_Ext("jpg,jpeg,gif,png"));
$e->addValidator(new Daq_Validate_File_Size(300000));
$e->setUploadPath($this->_upload);
$e->setRenderer("wpjb_form_field_upload");
$this->addElement($e, "default");
$e = $this->create("category", "select");
$e->setLabel(__("Category", "wpjobboard"));
$e->setValue($this->_object->getTagIds("category"));
$e->addOptions(wpjb_form_get_categories());
$this->addElement($e, "resume");
$this->addTag($e);
$e = $this->create("headline");
$e->setLabel(__("Professional Headline", "wpjobboard"));
$e->setHint(__("Describe yourself in few words, for example: Experienced Web Developer", "wpjobboard"));
$e->addValidator(new Daq_Validate_StringLength(1, 120));
$e->setValue($this->_object->headline);
$this->addElement($e, "resume");
$e = $this->create("description", "textarea");
$e->setLabel(__("Profile Summary", "wpjobboard"));
$e->setHint(__("Use this field to list your skills, specialities, experience or goals", "wpjobboard"));
$e->setValue($this->_object->description);
$e->setEditor(Daq_Form_Element_Textarea::EDITOR_TINY);
$this->addElement($e, "resume");
}
public function save($append = array())
{
parent::save($append);
$user = $this->getObject()->getUser(true);
$names = array_merge($user->getFieldNames(), array("first_name", "last_name"));
$userdata = array("ID"=>$user->ID);
$user = new WP_User($this->getObject(true)->ID);
$update = false;
foreach($names as $key) {
if($this->hasElement($key) && !in_array($key, array("user_login", "user_pass"))) {
$userdata[$key] = $this->value($key);
$update = true;
}
}
if($update) {
wp_update_user($userdata);
}
$temp = wpjb_upload_dir("resume", "", null, "basedir");
$finl = dirname($temp)."/".$this->getId();
wpjb_rename_dir($temp, $finl);
}
public function dump()
{
$dump = parent::dump();
$count = count($dump);
for($i=0; $i<$count; $i++) {
if(in_array($dump[$i]->name, array("experience", "education"))) {
$dump[$i]->editable = false;
}
}
return $dump;
}
}
?> | Sparxoo/chime | wp-content/plugins/wpjobboard/application/libraries/Form/Abstract/Resume.php | PHP | gpl-2.0 | 7,924 |
/*
* This file is part of PowerDNS or dnsdist.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "utility.hh"
#include "packetcache.hh"
#include "logger.hh"
#include "arguments.hh"
#include "statbag.hh"
#include <map>
#include <boost/algorithm/string.hpp>
extern StatBag S;
PacketCache::PacketCache()
{
d_ops=0;
d_maps.resize(1024);
for(auto& mc : d_maps) {
pthread_rwlock_init(&mc.d_mut, 0);
}
d_ttl=-1;
d_recursivettl=-1;
S.declare("packetcache-hit");
S.declare("packetcache-miss");
S.declare("packetcache-size");
d_statnumhit=S.getPointer("packetcache-hit");
d_statnummiss=S.getPointer("packetcache-miss");
d_statnumentries=S.getPointer("packetcache-size");
d_doRecursion=false;
}
PacketCache::~PacketCache()
{
// WriteLock l(&d_mut);
vector<WriteLock*> locks;
for(auto& mc : d_maps) {
locks.push_back(new WriteLock(&mc.d_mut));
}
for(auto wl : locks) {
delete wl;
}
}
int PacketCache::get(DNSPacket *p, DNSPacket *cached, bool recursive)
{
extern StatBag S;
if(d_ttl<0)
getTTLS();
cleanupIfNeeded();
if(d_doRecursion && p->d.rd) { // wants recursion
if(!d_recursivettl) {
(*d_statnummiss)++;
return 0;
}
}
else { // does not
if(!d_ttl) {
(*d_statnummiss)++;
return 0;
}
}
if(ntohs(p->d.qdcount)!=1) // we get confused by packets with more than one question
return 0;
unsigned int age=0;
string value;
bool haveSomething;
{
auto& mc=getMap(p->qdomain);
TryReadLock l(&mc.d_mut); // take a readlock here
if(!l.gotIt()) {
S.inc("deferred-cache-lookup");
return 0;
}
uint16_t maxReplyLen = p->d_tcp ? 0xffff : p->getMaxReplyLen();
haveSomething=getEntryLocked(p->qdomain, p->qtype, PacketCache::PACKETCACHE, value, -1, recursive, maxReplyLen, p->d_dnssecOk, p->hasEDNS(), &age);
}
if(haveSomething) {
(*d_statnumhit)++;
if (recursive)
ageDNSPacket(value, age);
if(cached->noparse(value.c_str(), value.size()) < 0)
return 0;
cached->spoofQuestion(p); // for correct case
cached->qdomain=p->qdomain;
cached->qtype=p->qtype;
return 1;
}
// cerr<<"Packet cache miss for '"<<p->qdomain<<"', merits: "<<packetMeritsRecursion<<endl;
(*d_statnummiss)++;
return 0; // bummer
}
void PacketCache::getTTLS()
{
d_ttl=::arg().asNum("cache-ttl");
d_recursivettl=::arg().asNum("recursive-cache-ttl");
d_doRecursion=::arg().mustDo("recursor");
}
void PacketCache::insert(DNSPacket *q, DNSPacket *r, bool recursive, unsigned int maxttl)
{
if(d_ttl < 0)
getTTLS();
if(ntohs(q->d.qdcount)!=1) {
return; // do not try to cache packets with multiple questions
}
if(q->qclass != QClass::IN) // we only cache the INternet
return;
uint16_t maxReplyLen = q->d_tcp ? 0xffff : q->getMaxReplyLen();
unsigned int ourttl = recursive ? d_recursivettl : d_ttl;
if(!recursive) {
if(maxttl<ourttl)
ourttl=maxttl;
} else {
unsigned int minttl = r->getMinTTL();
if(minttl<ourttl)
ourttl=minttl;
}
insert(q->qdomain, q->qtype, PacketCache::PACKETCACHE, r->getString(), ourttl, -1, recursive,
maxReplyLen, q->d_dnssecOk, q->hasEDNS());
}
// universal key appears to be: qname, qtype, kind (packet, query cache), optionally zoneid, meritsRecursion
void PacketCache::insert(const DNSName &qname, const QType& qtype, CacheEntryType cet, const string& value, unsigned int ttl, int zoneID,
bool meritsRecursion, unsigned int maxReplyLen, bool dnssecOk, bool EDNS)
{
cleanupIfNeeded();
if(!ttl)
return;
//cerr<<"Inserting qname '"<<qname<<"', cet: "<<(int)cet<<", qtype: "<<qtype.getName()<<", ttl: "<<ttl<<", maxreplylen: "<<maxReplyLen<<", hasEDNS: "<<EDNS<<endl;
CacheEntry val;
val.created=time(0);
val.ttd=val.created+ttl;
val.qname=qname;
val.qtype=qtype.getCode();
val.value=value;
val.ctype=cet;
val.meritsRecursion=meritsRecursion;
val.maxReplyLen = maxReplyLen;
val.dnssecOk = dnssecOk;
val.zoneID = zoneID;
val.hasEDNS = EDNS;
auto& mc = getMap(val.qname);
TryWriteLock l(&mc.d_mut);
if(l.gotIt()) {
bool success;
cmap_t::iterator place;
tie(place, success)=mc.d_map.insert(val);
if(!success)
mc.d_map.replace(place, val);
}
else
S.inc("deferred-cache-inserts");
}
void PacketCache::insert(const DNSName &qname, const QType& qtype, CacheEntryType cet, const vector<DNSZoneRecord>& value, unsigned int ttl, int zoneID)
{
cleanupIfNeeded();
if(!ttl)
return;
//cerr<<"Inserting qname '"<<qname<<"', cet: "<<(int)cet<<", qtype: "<<qtype.getName()<<", ttl: "<<ttl<<", maxreplylen: "<<maxReplyLen<<", hasEDNS: "<<EDNS<<endl;
CacheEntry val;
val.created=time(0);
val.ttd=val.created+ttl;
val.qname=qname;
val.qtype=qtype.getCode();
val.drs=value;
val.ctype=cet;
val.meritsRecursion=false;
val.maxReplyLen = 0;
val.dnssecOk = false;
val.zoneID = zoneID;
val.hasEDNS = false;
auto& mc = getMap(val.qname);
TryWriteLock l(&mc.d_mut);
if(l.gotIt()) {
bool success;
cmap_t::iterator place;
tie(place, success)=mc.d_map.insert(val);
if(!success)
mc.d_map.replace(place, val);
}
else
S.inc("deferred-cache-inserts");
}
/* clears the entire packetcache. */
int PacketCache::purge()
{
int delcount=0;
for(auto& mc : d_maps) {
WriteLock l(&mc.d_mut);
delcount+=mc.d_map.size();
mc.d_map.clear();
}
d_statnumentries->store(0);
return delcount;
}
int PacketCache::purgeExact(const DNSName& qname)
{
int delcount=0;
auto& mc = getMap(qname);
WriteLock l(&mc.d_mut);
auto range = mc.d_map.equal_range(tie(qname));
if(range.first != range.second) {
delcount+=distance(range.first, range.second);
mc.d_map.erase(range.first, range.second);
}
*d_statnumentries-=delcount; // XXX FIXME NEEDS TO BE ADJUSTED (for packetcache shards)
return delcount;
}
/* purges entries from the packetcache. If match ends on a $, it is treated as a suffix */
int PacketCache::purge(const string &match)
{
if(ends_with(match, "$")) {
int delcount=0;
string prefix(match);
prefix.resize(prefix.size()-1);
DNSName dprefix(prefix);
for(auto& mc : d_maps) {
WriteLock l(&mc.d_mut);
cmap_t::const_iterator iter = mc.d_map.lower_bound(tie(dprefix));
auto start=iter;
for(; iter != mc.d_map.end(); ++iter) {
if(!iter->qname.isPartOf(dprefix)) {
break;
}
delcount++;
}
mc.d_map.erase(start, iter);
}
*d_statnumentries-=delcount; // XXX FIXME NEEDS TO BE ADJUSTED (for packetcache shards)
return delcount;
}
else {
return purgeExact(DNSName(match));
}
}
// called from ueberbackend
bool PacketCache::getEntry(const DNSName &qname, const QType& qtype, CacheEntryType cet, vector<DNSZoneRecord>& value, int zoneID)
{
if(d_ttl<0)
getTTLS();
cleanupIfNeeded();
auto& mc=getMap(qname);
TryReadLock l(&mc.d_mut); // take a readlock here
if(!l.gotIt()) {
S.inc( "deferred-cache-lookup");
return false;
}
return getEntryLocked(qname, qtype, cet, value, zoneID);
}
bool PacketCache::getEntryLocked(const DNSName &qname, const QType& qtype, CacheEntryType cet, string& value, int zoneID, bool meritsRecursion,
unsigned int maxReplyLen, bool dnssecOK, bool hasEDNS, unsigned int *age)
{
uint16_t qt = qtype.getCode();
//cerr<<"Lookup for maxReplyLen: "<<maxReplyLen<<endl;
auto& mc=getMap(qname);
// cmap_t::const_iterator i=mc.d_map.find(tie(qname, qt, cet, zoneID, meritsRecursion, maxReplyLen, dnssecOK, hasEDNS, *age));
auto& idx = boost::multi_index::get<UnorderedNameTag>(mc.d_map);
auto range=idx.equal_range(tie(qname, qt, cet, zoneID));
if(range.first == range.second)
return false;
time_t now=time(0);
for(auto iter = range.first ; iter != range.second; ++iter) {
if(meritsRecursion == iter->meritsRecursion && maxReplyLen == iter->maxReplyLen && dnssecOK == iter->dnssecOk && hasEDNS == iter->hasEDNS ) {
if(iter->ttd > now) {
if (age)
*age = now - iter->created;
value = iter->value;
return true;
}
}
}
return false;
}
bool PacketCache::getEntryLocked(const DNSName &qname, const QType& qtype, CacheEntryType cet, vector<DNSZoneRecord>& value, int zoneID)
{
uint16_t qt = qtype.getCode();
//cerr<<"Lookup for maxReplyLen: "<<maxReplyLen<<endl;
auto& mc=getMap(qname);
auto& idx = boost::multi_index::get<UnorderedNameTag>(mc.d_map);
auto i=idx.find(tie(qname, qt, cet, zoneID));
if(i==idx.end())
return false;
time_t now=time(0);
if(i->ttd > now) {
value = i->drs;
return true;
}
return false;
}
map<char,int> PacketCache::getCounts()
{
int recursivePackets=0, nonRecursivePackets=0, queryCacheEntries=0, negQueryCacheEntries=0;
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
for(cmap_t::const_iterator iter = mc.d_map.begin() ; iter != mc.d_map.end(); ++iter) {
if(iter->ctype == PACKETCACHE)
if(iter->meritsRecursion)
recursivePackets++;
else
nonRecursivePackets++;
else if(iter->ctype == QUERYCACHE) {
if(iter->value.empty())
negQueryCacheEntries++;
else
queryCacheEntries++;
}
}
}
map<char,int> ret;
ret['!']=negQueryCacheEntries;
ret['Q']=queryCacheEntries;
ret['n']=nonRecursivePackets;
ret['r']=recursivePackets;
return ret;
}
int PacketCache::size()
{
uint64_t ret=0;
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
ret+=mc.d_map.size();
}
return ret;
}
/** readlock for figuring out which iterators to delete, upgrade to writelock when actually cleaning */
void PacketCache::cleanup()
{
d_statnumentries->store(0);
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
*d_statnumentries+=mc.d_map.size();
}
unsigned int maxCached=::arg().asNum("max-cache-entries");
unsigned int toTrim=0;
unsigned long cacheSize=*d_statnumentries;
if(maxCached && cacheSize > maxCached) {
toTrim = cacheSize - maxCached;
}
unsigned int lookAt=0;
// two modes - if toTrim is 0, just look through 10% of the cache and nuke everything that is expired
// otherwise, scan first 5*toTrim records, and stop once we've nuked enough
if(toTrim)
lookAt=5*toTrim;
else
lookAt=cacheSize/10;
// cerr<<"cacheSize: "<<cacheSize<<", lookAt: "<<lookAt<<", toTrim: "<<toTrim<<endl;
time_t now=time(0);
DLOG(L<<"Starting cache clean"<<endl);
//unsigned int totErased=0;
for(auto& mc : d_maps) {
WriteLock wl(&mc.d_mut);
typedef cmap_t::nth_index<1>::type sequence_t;
sequence_t& sidx=mc.d_map.get<1>();
unsigned int erased=0, lookedAt=0;
for(sequence_t::iterator i=sidx.begin(); i != sidx.end(); lookedAt++) {
if(i->ttd < now) {
sidx.erase(i++);
erased++;
}
else {
++i;
}
if(toTrim && erased > toTrim / d_maps.size())
break;
if(lookedAt > lookAt / d_maps.size())
break;
}
//totErased += erased;
}
// if(totErased)
// cerr<<"erased: "<<totErased<<endl;
d_statnumentries->store(0);
for(auto& mc : d_maps) {
ReadLock l(&mc.d_mut);
*d_statnumentries+=mc.d_map.size();
}
DLOG(L<<"Done with cache clean"<<endl);
}
| grahamhayes/pdns | pdns/packetcache.cc | C++ | gpl-2.0 | 12,146 |
<?php
/**
* BackPress Styles Procedural API
*
* @since 2.6.0
*
* @package WordPress
* @subpackage BackPress
*/
/**
* Initialize $wp_styles if it has not been set.
*
* @global WP_Styles $wp_styles
*
* @since 4.2.0
*
* @return WP_Styles WP_Styles instance.
*/
function wp_styles() {
global $wp_styles;
if ( ! ( $wp_styles instanceof WP_Styles ) ) {
$wp_styles = new WP_Styles();
}
return $wp_styles;
}
/**
* Display styles that are in the $handles queue.
*
* Passing an empty array to $handles prints the queue,
* passing an array with one string prints that style,
* and passing an array of strings prints those styles.
*
* @global WP_Styles $wp_styles The WP_Styles object for printing styles.
*
* @since 2.6.0
*
* @param string|bool|array $handles Styles to be printed. Default 'false'.
* @return array On success, a processed array of WP_Dependencies items; otherwise, an empty array.
*/
function wp_print_styles( $handles = false ) {
if ( '' === $handles ) { // for wp_head
$handles = false;
}
/**
* Fires before styles in the $handles queue are printed.
*
* @since 2.6.0
*/
if ( ! $handles ) {
do_action( 'wp_print_styles' );
}
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
global $wp_styles;
if ( ! ( $wp_styles instanceof WP_Styles ) ) {
if ( ! $handles ) {
return array(); // No need to instantiate if nothing is there.
}
}
return wp_styles()->do_items( $handles );
}
/**
* Add extra CSS styles to a registered stylesheet.
*
* Styles will only be added if the stylesheet in already in the queue.
* Accepts a string $data containing the CSS. If two or more CSS code blocks
* are added to the same stylesheet $handle, they will be printed in the order
* they were added, i.e. the latter added styles can redeclare the previous.
*
* @see WP_Styles::add_inline_style()
*
* @since 3.3.0
*
* @param string $handle Name of the stylesheet to add the extra styles to. Must be lowercase.
* @param string $data String containing the CSS styles to be added.
* @return bool True on success, false on failure.
*/
function wp_add_inline_style( $handle, $data ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
if ( false !== stripos( $data, '</style>' ) ) {
_doing_it_wrong( __FUNCTION__, __( 'Do not pass style tags to wp_add_inline_style().' ), '3.7' );
$data = trim( preg_replace( '#<style[^>]*>(.*)</style>#is', '$1', $data ) );
}
return wp_styles()->add_inline_style( $handle, $data );
}
/**
* Register a CSS stylesheet.
*
* @see WP_Dependencies::add()
* @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types.
*
* @since 2.6.0
* @since 4.3.0 A return value was added.
*
* @param string $handle Name of the stylesheet.
* @param string|bool $src Path to the stylesheet from the WordPress root directory. Example: '/css/mystyle.css'.
* @param array $deps An array of registered style handles this stylesheet depends on. Default empty array.
* @param string|bool $ver String specifying the stylesheet version number. Used to ensure that the correct version
* is sent to the client regardless of caching. Default 'false'. Accepts 'false', 'null', or 'string'.
* @param string $media Optional. The media for which this stylesheet has been defined.
* Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print',
* 'screen', 'tty', or 'tv'.
* @return bool Whether the style has been registered. True on success, false on failure.
*/
function wp_register_style( $handle, $src, $deps = array(), $ver = false, $media = 'all' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
return wp_styles()->add( $handle, $src, $deps, $ver, $media );
}
/**
* Remove a registered stylesheet.
*
* @see WP_Dependencies::remove()
*
* @since 2.1.0
*
* @param string $handle Name of the stylesheet to be removed.
*/
function wp_deregister_style( $handle ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
wp_styles()->remove( $handle );
}
/**
* Enqueue a CSS stylesheet.
*
* Registers the style if source provided (does NOT overwrite) and enqueues.
*
* @see WP_Dependencies::add(), WP_Dependencies::enqueue()
* @link http://www.w3.org/TR/CSS2/media.html#media-types List of CSS media types.
*
* @since 2.6.0
*
* @param string $handle Name of the stylesheet.
* @param string|bool $src Path to the stylesheet from the root directory of WordPress. Example: '/css/mystyle.css'.
* @param array $deps An array of registered style handles this stylesheet depends on. Default empty array.
* @param string|bool $ver String specifying the stylesheet version number, if it has one. This parameter is used
* to ensure that the correct version is sent to the client regardless of caching, and so
* should be included if a version number is available and makes sense for the stylesheet.
* @param string $media Optional. The media for which this stylesheet has been defined.
* Default 'all'. Accepts 'all', 'aural', 'braille', 'handheld', 'projection', 'print',
* 'screen', 'tty', or 'tv'.
*/
function wp_enqueue_style( $handle, $src = false, $deps = array(), $ver = false, $media = 'all' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
$wp_styles = wp_styles();
if ( $src ) {
$_handle = explode('?', $handle);
$wp_styles->add( $_handle[0], $src, $deps, $ver, $media );
}
$wp_styles->enqueue( $handle );
}
/**
* Remove a previously enqueued CSS stylesheet.
*
* @see WP_Dependencies::dequeue()
*
* @since 3.1.0
*
* @param string $handle Name of the stylesheet to be removed.
*/
function wp_dequeue_style( $handle ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
wp_styles()->dequeue( $handle );
}
/**
* Check whether a CSS stylesheet has been added to the queue.
*
* @since 2.8.0
*
* @param string $handle Name of the stylesheet.
* @param string $list Optional. Status of the stylesheet to check. Default 'enqueued'.
* Accepts 'enqueued', 'registered', 'queue', 'to_do', and 'done'.
* @return bool Whether style is queued.
*/
function wp_style_is( $handle, $list = 'enqueued' ) {
_wp_scripts_maybe_doing_it_wrong( __FUNCTION__ );
return (bool) wp_styles()->query( $handle, $list );
}
/**
* Add metadata to a CSS stylesheet.
*
* Works only if the stylesheet has already been added.
*
* Possible values for $key and $value:
* 'conditional' string Comments for IE 6, lte IE 7 etc.
* 'rtl' bool|string To declare an RTL stylesheet.
* 'suffix' string Optional suffix, used in combination with RTL.
* 'alt' bool For rel="alternate stylesheet".
* 'title' string For preferred/alternate stylesheets.
*
* @see WP_Dependency::add_data()
*
* @since 3.6.0
*
* @param string $handle Name of the stylesheet.
* @param string $key Name of data point for which we're storing a value.
* Accepts 'conditional', 'rtl' and 'suffix', 'alt' and 'title'.
* @param mixed $value String containing the CSS data to be added.
* @return bool True on success, false on failure.
*/
function wp_style_add_data( $handle, $key, $value ) {
return wp_styles()->add_data( $handle, $key, $value );
}
| SKLCC/website | wp-includes/functions.wp-styles.php | PHP | gpl-2.0 | 7,435 |
// TransformPatternDlg.cpp : implementation file
#include <psycle/host/detail/project.private.hpp>
#include "TransformPatternDlg.hpp"
#include "Song.hpp"
#include "ChildView.hpp"
#include "MainFrm.hpp"
namespace psycle { namespace host {
static const char notes[12][3]={"C-","C#","D-","D#","E-","F-","F#","G-","G#","A-","A#","B-"};
static const char *empty ="Empty";
static const char *nonempty="Nonempty";
static const char *all="All";
static const char *same="Same";
static const char *off="off";
static const char *twk="twk";
static const char *tws="tws";
static const char *mcm="mcm";
// CTransformPatternDlg dialog
IMPLEMENT_DYNAMIC(CTransformPatternDlg, CDialog)
CTransformPatternDlg::CTransformPatternDlg(Song& _pSong, CChildView& _cview, CWnd* pParent /*=NULL*/)
: CDialog(CTransformPatternDlg::IDD, pParent)
, song(_pSong), cview(_cview), m_applyto(0)
{
}
CTransformPatternDlg::~CTransformPatternDlg()
{
}
void CTransformPatternDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_SEARCHNOTECOMB, m_searchnote);
DDX_Control(pDX, IDC_SEARCHINSTCOMB, m_searchinst);
DDX_Control(pDX, IDC_SEARCHMACHCOMB, m_searchmach);
DDX_Control(pDX, IDC_REPLNOTECOMB, m_replacenote);
DDX_Control(pDX, IDC_REPLINSTCOMB, m_replaceinst);
DDX_Control(pDX, IDC_REPLMACHCOMB, m_replacemach);
DDX_Control(pDX, IDC_REPLTWEAKCHECK, m_replacetweak);
DDX_Radio(pDX,IDC_APPLYTOSONG, m_applyto);
DDX_Control(pDX, IDC_CH_INCLUDEPAT, m_includePatNotInSeq);
}
BEGIN_MESSAGE_MAP(CTransformPatternDlg, CDialog)
ON_BN_CLICKED(IDD_SEARCH, &CTransformPatternDlg::OnBnClickedSearch)
ON_BN_CLICKED(IDD_REPLACE, &CTransformPatternDlg::OnBnClickedReplace)
END_MESSAGE_MAP()
BOOL CTransformPatternDlg::OnInitDialog()
{
CDialog::OnInitDialog();
//Note (search and replace)
m_searchnote.AddString(all); m_searchnote.SetItemData(0,1003);
m_searchnote.AddString(empty); m_searchnote.SetItemData(1,1001);
m_searchnote.AddString(nonempty); m_searchnote.SetItemData(2,1002);
m_replacenote.AddString(same); m_replacenote.SetItemData(0,1002);
m_replacenote.AddString(empty); m_replacenote.SetItemData(1,1001);
bool is440 = PsycleGlobal::conf().patView().showA440;
for (int i=notecommands::c0; i <= notecommands::b9;i++) {
std::ostringstream os;
os << notes[i%12];
if (is440) os << (i/12)-1;
else os << (i/12);
m_searchnote.AddString(os.str().c_str()); m_searchnote.SetItemData(3+i,i);
m_replacenote.AddString(os.str().c_str()); m_replacenote.SetItemData(2+i,i);
}
m_searchnote.AddString(off); m_searchnote.SetItemData(123,notecommands::release);
m_searchnote.AddString(twk); m_searchnote.SetItemData(124,notecommands::tweak);
m_searchnote.AddString(tws); m_searchnote.SetItemData(125,notecommands::tweakslide);
m_searchnote.AddString(mcm); m_searchnote.SetItemData(126,notecommands::midicc);
m_replacenote.AddString(off); m_replacenote.SetItemData(122,notecommands::release);
m_replacenote.AddString(twk); m_replacenote.SetItemData(123,notecommands::tweak);
m_replacenote.AddString(tws); m_replacenote.SetItemData(124,notecommands::tweakslide);
m_replacenote.AddString(mcm); m_replacenote.SetItemData(125,notecommands::midicc);
m_searchnote.SetCurSel(0);
m_replacenote.SetCurSel(0);
//Inst (search and replace)
m_searchinst.AddString(all); m_searchinst.SetItemData(0,1003);
m_searchinst.AddString(empty); m_searchinst.SetItemData(1,1001);
m_searchinst.AddString(nonempty); m_searchinst.SetItemData(2,1002);
m_replaceinst.AddString(same); m_replaceinst.SetItemData(0,1002);
m_replaceinst.AddString(empty); m_replaceinst.SetItemData(1,1001);
for (int i=0; i < 0xFF; i++) {
std::ostringstream os;
if (i < 16) os << "0";
os << std::uppercase << std::hex << i;
m_searchinst.AddString(os.str().c_str()); m_searchinst.SetItemData(3+i,i);
m_replaceinst.AddString(os.str().c_str()); m_replaceinst.SetItemData(2+i,i);
}
m_searchinst.SetCurSel(0);
m_replaceinst.SetCurSel(0);
//Mach (search and replace)
m_searchmach.AddString(all); m_searchmach.SetItemData(0,1003);
m_searchmach.AddString(empty); m_searchmach.SetItemData(1,1001);
m_searchmach.AddString(nonempty); m_searchmach.SetItemData(2,1002);
m_replacemach.AddString(same); m_replacemach.SetItemData(0,1002);
m_replacemach.AddString(empty); m_replacemach.SetItemData(1,1001);
for (int i=0; i < 0xFF; i++) {
std::ostringstream os;
if (i < 16) os << "0";
os << std::uppercase << std::hex << i;
m_searchmach.AddString(os.str().c_str()); m_searchmach.SetItemData(3+i,i);
m_replacemach.AddString(os.str().c_str()); m_replacemach.SetItemData(2+i,i);
}
m_searchmach.SetCurSel(0);
m_replacemach.SetCurSel(0);
if (cview.blockSelected) m_applyto = 2;
UpdateData(FALSE);
return true; // return true unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return false
}
// CTransformPatternDlg message handlers
void CTransformPatternDlg::OnBnClickedSearch()
{
CSearchReplaceMode mode = cview.SetupSearchReplaceMode(
m_searchnote.GetItemData(m_searchnote.GetCurSel()),
m_searchinst.GetItemData(m_searchinst.GetCurSel()),
m_searchmach.GetItemData(m_searchmach.GetCurSel()));
CCursor cursor;
cursor.line = -1;
int pattern = -1;
UpdateData (TRUE);
if (m_applyto == 0) {
bool includeOther = m_includePatNotInSeq.GetCheck() > 0;
int lastPatternUsed = (includeOther )? song.GetHighestPatternIndexInSequence() : MAX_PATTERNS;
for (int currentPattern = 0; currentPattern <= lastPatternUsed; currentPattern++)
{
if (song.IsPatternUsed(currentPattern, !includeOther))
{
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[currentPattern];
sel.end.track = MAX_TRACKS;
cursor = cview.SearchInPattern(currentPattern, sel , mode);
if (cursor.line != -1) {
pattern=currentPattern;
break;
}
}
}
}
else if (m_applyto == 1) {
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[cview._ps()];
sel.end.track = MAX_TRACKS;
cursor = cview.SearchInPattern(cview._ps(), sel , mode);
pattern = cview._ps();
}
else if (m_applyto == 2 && cview.blockSelected) {
cursor = cview.SearchInPattern(cview._ps(), cview.blockSel , mode);
pattern = cview._ps();
}
else {
MessageBox("No block selected for action","Search and replace",MB_ICONWARNING);
return;
}
if (cursor.line == -1) {
MessageBox("Nothing found that matches the selected options","Search and replace",MB_ICONINFORMATION);
}
else {
cview.editcur = cursor;
if (cview._ps() != pattern) {
int pos = -1;
for (int i=0; i < MAX_SONG_POSITIONS; i++) {
if (song.playOrder[i] == pattern) {
pos = i;
break;
}
}
if (pos == -1){
pos = song.playLength;
++song.playLength;
song.playOrder[pos]=pattern;
((CMainFrame*)cview.pParentFrame)->UpdateSequencer();
}
cview.editPosition = pos;
memset(song.playOrderSel,0,MAX_SONG_POSITIONS*sizeof(bool));
song.playOrderSel[cview.editPosition]=true;
((CMainFrame*)cview.pParentFrame)->UpdatePlayOrder(true);
cview.Repaint(draw_modes::pattern);
}
else {
cview.Repaint(draw_modes::cursor);
}
}
}
void CTransformPatternDlg::OnBnClickedReplace()
{
CSearchReplaceMode mode = cview.SetupSearchReplaceMode(
m_searchnote.GetItemData(m_searchnote.GetCurSel()),
m_searchinst.GetItemData(m_searchinst.GetCurSel()),
m_searchmach.GetItemData(m_searchmach.GetCurSel()),
m_replacenote.GetItemData(m_replacenote.GetCurSel()),
m_replaceinst.GetItemData(m_replaceinst.GetCurSel()),
m_replacemach.GetItemData(m_replacemach.GetCurSel()),
m_replacetweak.GetCheck());
bool replaced=false;
UpdateData (TRUE);
if (m_applyto == 0) {
bool includeOther = m_includePatNotInSeq.GetCheck() > 0;
int lastPatternUsed = (includeOther )? song.GetHighestPatternIndexInSequence() : MAX_PATTERNS;
for (int currentPattern = 0; currentPattern <= lastPatternUsed; currentPattern++)
{
if (song.IsPatternUsed(currentPattern, !includeOther))
{
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[currentPattern];
sel.end.track = MAX_TRACKS;
replaced=cview.SearchReplace(currentPattern, sel , mode);
}
}
}
else if (m_applyto == 1) {
CSelection sel;
sel.start.line = 0; sel.start.track = 0;
sel.end.line = song.patternLines[cview._ps()];
sel.end.track = MAX_TRACKS;
replaced=cview.SearchReplace(cview._ps(), sel, mode);
}
else if (m_applyto == 2 && cview.blockSelected) {
replaced=cview.SearchReplace(cview._ps(), cview.blockSel , mode);
}
else {
MessageBox("No block selected for action","Search and replace",MB_ICONWARNING);
return;
}
if (replaced) {
cview.Repaint(draw_modes::pattern);
}
else {
MessageBox("Nothing found that matches the selected options","Search and replace",MB_ICONINFORMATION);
}
}
} // namespace
} // namespace
| eriser/psycle | psycle/src/psycle/host/TransformPatternDlg.cpp | C++ | gpl-2.0 | 9,403 |
/* ========================================================================
* Bootstrap: alert.js v3.0.3
* http://getbootstrap.com/javascript/#alerts
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// TOOLTIP PUBLIC CLASS DEFINITION
// ===============================
var Tooltip = function(element, options) {
this.type =
this.options =
this.enabled =
this.timeout =
this.hoverState =
this.$element = null
this.init('tooltip', element, options)
}
Tooltip.DEFAULTS = {
animation: true
, placement: 'top'
, selector: false
, template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>'
, trigger: 'hover focus'
, title: ''
, delay: 0
, html: false
, container: false
}
Tooltip.prototype.init = function(type, element, options) {
this.enabled = true
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
var triggers = this.options.trigger.split(' ')
for (var i = triggers.length; i--; ) {
var trigger = triggers[i]
if (trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (trigger != 'manual') {
var eventIn = trigger == 'hover' ? 'mouseenter' : 'focus'
var eventOut = trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
}
this.options.selector ?
(this._options = $.extend({}, this.options, {trigger: 'manual', selector: ''})) :
this.fixTitle()
}
Tooltip.prototype.getDefaults = function() {
return Tooltip.DEFAULTS
}
Tooltip.prototype.getOptions = function(options) {
options = $.extend({}, this.getDefaults(), this.$element.data(), options)
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay
, hide: options.delay
}
}
return options
}
Tooltip.prototype.getDelegateOptions = function() {
var options = {}
var defaults = this.getDefaults()
this._options && $.each(this._options, function(key, value) {
if (defaults[key] != value)
options[key] = value
})
return options
}
Tooltip.prototype.enter = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'in'
if (!self.options.delay || !self.options.delay.show)
return self.show()
self.timeout = setTimeout(function() {
if (self.hoverState == 'in')
self.show()
}, self.options.delay.show)
}
Tooltip.prototype.leave = function(obj) {
var self = obj instanceof this.constructor ?
obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
clearTimeout(self.timeout)
self.hoverState = 'out'
if (!self.options.delay || !self.options.delay.hide)
return self.hide()
self.timeout = setTimeout(function() {
if (self.hoverState == 'out')
self.hide()
}, self.options.delay.hide)
}
Tooltip.prototype.show = function() {
var e = $.Event('show.bs.' + this.type)
if (this.hasContent() && this.enabled) {
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
var $tip = this.tip()
this.setContent()
if (this.options.animation)
$tip.addClass('fade')
var placement = typeof this.options.placement == 'function' ?
this.options.placement.call(this, $tip[0], this.$element[0]) :
this.options.placement
var autoToken = /\s?auto?\s?/i
var autoPlace = autoToken.test(placement)
if (autoPlace)
placement = placement.replace(autoToken, '') || 'top'
$tip
.detach()
.css({top: 0, left: 0, display: 'block'})
.addClass(placement)
this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)
var pos = this.getPosition()
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (autoPlace) {
var $parent = this.$element.parent()
var orgPlacement = placement
var docScroll = document.documentElement.scrollTop || document.body.scrollTop
var parentWidth = this.options.container == 'body' ? window.innerWidth : $parent.outerWidth()
var parentHeight = this.options.container == 'body' ? window.innerHeight : $parent.outerHeight()
var parentLeft = this.options.container == 'body' ? 0 : $parent.offset().left
placement = placement == 'bottom' && pos.top + pos.height + actualHeight - docScroll > parentHeight ? 'top' :
placement == 'top' && pos.top - docScroll - actualHeight < 0 ? 'bottom' :
placement == 'right' && pos.right + actualWidth > parentWidth ? 'left' :
placement == 'left' && pos.left - actualWidth < parentLeft ? 'right' :
placement
$tip
.removeClass(orgPlacement)
.addClass(placement)
}
var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)
this.applyPlacement(calculatedOffset, placement)
this.$element.trigger('shown.bs.' + this.type)
}
}
Tooltip.prototype.applyPlacement = function(offset, placement) {
var replace
var $tip = this.tip()
var width = $tip[0].offsetWidth
var height = $tip[0].offsetHeight
// manually read margins because getBoundingClientRect includes difference
var marginTop = parseInt($tip.css('margin-top'), 10)
var marginLeft = parseInt($tip.css('margin-left'), 10)
// we must check for NaN for ie 8/9
if (isNaN(marginTop))
marginTop = 0
if (isNaN(marginLeft))
marginLeft = 0
offset.top = offset.top + marginTop
offset.left = offset.left + marginLeft
$tip
.offset(offset)
.addClass('in')
// check to see if placing tip in new offset caused the tip to resize itself
var actualWidth = $tip[0].offsetWidth
var actualHeight = $tip[0].offsetHeight
if (placement == 'top' && actualHeight != height) {
replace = true
offset.top = offset.top + height - actualHeight
}
if (/bottom|top/.test(placement)) {
var delta = 0
if (offset.left < 0) {
delta = offset.left * -2
offset.left = 0
$tip.offset(offset)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
}
this.replaceArrow(delta - width + actualWidth, actualWidth, 'left')
} else {
this.replaceArrow(actualHeight - height, actualHeight, 'top')
}
if (replace)
$tip.offset(offset)
}
Tooltip.prototype.replaceArrow = function(delta, dimension, position) {
this.arrow().css(position, delta ? (50 * (1 - delta / dimension) + "%") : '')
}
Tooltip.prototype.setContent = function() {
var $tip = this.tip()
var title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
}
Tooltip.prototype.hide = function() {
var that = this
var $tip = this.tip()
var e = $.Event('hide.bs.' + this.type)
function complete() {
if (that.hoverState != 'in')
$tip.detach()
}
this.$element.trigger(e)
if (e.isDefaultPrevented())
return
$tip.removeClass('in')
$.support.transition && this.$tip.hasClass('fade') ?
$tip
.one($.support.transition.end, complete)
.emulateTransitionEnd(150) :
complete()
this.$element.trigger('hidden.bs.' + this.type)
return this
}
Tooltip.prototype.fixTitle = function() {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '').attr('title', '')
}
}
Tooltip.prototype.hasContent = function() {
return this.getTitle()
}
Tooltip.prototype.getPosition = function() {
var el = this.$element[0]
return $.extend({}, (typeof el.getBoundingClientRect == 'function') ? el.getBoundingClientRect() : {
width: el.offsetWidth
, height: el.offsetHeight
}, this.$element.offset())
}
Tooltip.prototype.getCalculatedOffset = function(placement, pos, actualWidth, actualHeight) {
return placement == 'bottom' ? {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2} :
placement == 'top' ? {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2} :
placement == 'left' ? {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth} :
/* placement == 'right' */ {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width}
}
Tooltip.prototype.getTitle = function() {
var title
var $e = this.$element
var o = this.options
title = $e.attr('data-original-title')
|| (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
}
Tooltip.prototype.tip = function() {
return this.$tip = this.$tip || $(this.options.template)
}
Tooltip.prototype.arrow = function() {
return this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')
}
Tooltip.prototype.validate = function() {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
}
Tooltip.prototype.enable = function() {
this.enabled = true
}
Tooltip.prototype.disable = function() {
this.enabled = false
}
Tooltip.prototype.toggleEnabled = function() {
this.enabled = !this.enabled
}
Tooltip.prototype.toggle = function(e) {
var self = e ? $(e.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type) : this
self.tip().hasClass('in') ? self.leave(self) : self.enter(self)
}
Tooltip.prototype.destroy = function() {
this.hide().$element.off('.' + this.type).removeData('bs.' + this.type)
}
// TOOLTIP PLUGIN DEFINITION
// =========================
var old = $.fn.tooltip
$.fn.tooltip = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tooltip')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
// TOOLTIP NO CONFLICT
// ===================
$.fn.tooltip.noConflict = function() {
$.fn.tooltip = old
return this
}
// ALERT CLASS DEFINITION
// ======================
var dismiss = '[data-dismiss="alert"]'
var Alert = function(el) {
$(el).on('click', dismiss, this.close)
}
Alert.prototype.close = function(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector)
if (e)
e.preventDefault()
if (!$parent.length) {
$parent = $this.hasClass('alert') ? $this : $this.parent()
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented())
return
$parent.removeClass('in')
function removeElement() {
$parent.trigger('closed.bs.alert').remove()
}
$.support.transition && $parent.hasClass('fade') ?
$parent
.one($.support.transition.end, removeElement)
.emulateTransitionEnd(150) :
removeElement()
}
// ALERT PLUGIN DEFINITION
// =======================
var old = $.fn.alert
$.fn.alert = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.alert')
if (!data)
$this.data('bs.alert', (data = new Alert(this)))
if (typeof option == 'string')
data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
// ALERT NO CONFLICT
// =================
$.fn.alert.noConflict = function() {
$.fn.alert = old
return this
}
// ALERT DATA-API
// ==============
$(document).on('click.bs.alert.data-api', dismiss, Alert.prototype.close)
}(jQuery);
/* ========================================================================
* Bootstrap: tab.js v3.0.3
* http://getbootstrap.com/javascript/#tabs
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// TAB CLASS DEFINITION
// ====================
var Tab = function(element) {
this.element = $(element)
}
Tab.prototype.show = function() {
var $this = this.element
var $ul = $this.closest('ul:not(.dropdown-menu)')
var selector = $this.data('target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
}
if ($this.parent('li').hasClass('active'))
return
var previous = $ul.find('.active:last a')[0]
var e = $.Event('show.bs.tab', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented())
return
var $target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function() {
$this.trigger({
type: 'shown.bs.tab'
, relatedTarget: previous
})
})
}
Tab.prototype.activate = function(element, container, callback) {
var $active = container.find('> .active')
var transition = callback
&& $.support.transition
&& $active.hasClass('fade')
function next() {
$active
.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth // reflow for transition
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown').addClass('active')
}
callback && callback()
}
transition ?
$active
.one($.support.transition.end, next)
.emulateTransitionEnd(150) :
next()
$active.removeClass('in')
}
// TAB PLUGIN DEFINITION
// =====================
var old = $.fn.tab
$.fn.tab = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.tab')
if (!data)
$this.data('bs.tab', (data = new Tab(this)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.tab.Constructor = Tab
// TAB NO CONFLICT
// ===============
$.fn.tab.noConflict = function() {
$.fn.tab = old
return this
}
// TAB DATA-API
// ============
$(document).on('click.bs.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function(e) {
e.preventDefault()
$(this).tab('show')
})
}(jQuery);
/* ========================================================================
* Bootstrap: affix.js v3.0.3
* http://getbootstrap.com/javascript/#affix
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// AFFIX CLASS DEFINITION
// ======================
var Affix = function(element, options) {
this.options = $.extend({}, Affix.DEFAULTS, options)
this.$window = $(window)
.on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.bs.affix.data-api', $.proxy(this.checkPositionWithEventLoop, this))
this.$element = $(element)
this.affixed =
this.unpin = null
this.checkPosition()
}
Affix.RESET = 'affix affix-top affix-bottom'
Affix.DEFAULTS = {
offset: 0
}
Affix.prototype.checkPositionWithEventLoop = function() {
setTimeout($.proxy(this.checkPosition, this), 1)
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible'))
return
var scrollHeight = $(document).height()
var scrollTop = this.$window.scrollTop()
var position = this.$element.offset()
var offset = this.options.offset
var offsetTop = offset.top
var offsetBottom = offset.bottom
if (typeof offset != 'object')
offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function')
offsetTop = offset.top()
if (typeof offsetBottom == 'function')
offsetBottom = offset.bottom()
var affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false :
offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
offsetTop != null && (scrollTop <= offsetTop) ? 'top' : false
if (this.affixed === affix)
return
if (this.unpin)
this.$element.css('top', '')
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))
if (affix == 'bottom') {
this.$element.offset({top: document.body.offsetHeight - offsetBottom - this.$element.height()})
}
}
// AFFIX PLUGIN DEFINITION
// =======================
var old = $.fn.affix
$.fn.affix = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.affix')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.affix', (data = new Affix(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.affix.Constructor = Affix
// AFFIX NO CONFLICT
// =================
$.fn.affix.noConflict = function() {
$.fn.affix = old
return this
}
// AFFIX DATA-API
// ==============
$(window).on('load', function() {
$('[data-spy="affix"]').each(function() {
var $spy = $(this)
var data = $spy.data()
data.offset = data.offset || {}
if (data.offsetBottom)
data.offset.bottom = data.offsetBottom
if (data.offsetTop)
data.offset.top = data.offsetTop
$spy.affix(data)
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: collapse.js v3.0.3
* http://getbootstrap.com/javascript/#collapse
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// COLLAPSE PUBLIC CLASS DEFINITION
// ================================
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, Collapse.DEFAULTS, options)
this.transitioning = null
if (this.options.parent)
this.$parent = $(this.options.parent)
if (this.options.toggle)
this.toggle()
}
Collapse.DEFAULTS = {
toggle: true
}
Collapse.prototype.dimension = function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
}
Collapse.prototype.show = function() {
if (this.transitioning || this.$element.hasClass('in'))
return
var startEvent = $.Event('show.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented())
return
var actives = this.$parent && this.$parent.find('> .panel > .in')
if (actives && actives.length) {
var hasData = actives.data('bs.collapse')
if (hasData && hasData.transitioning)
return
actives.collapse('hide')
hasData || actives.data('bs.collapse', null)
}
var dimension = this.dimension()
this.$element
.removeClass('collapse')
.addClass('collapsing')
[dimension](0)
this.transitioning = 1
var complete = function() {
this.$element
.removeClass('collapsing')
.addClass('in')
[dimension]('auto')
this.transitioning = 0
this.$element.trigger('shown.bs.collapse')
}
if (!$.support.transition)
return complete.call(this)
var scrollSize = $.camelCase(['scroll', dimension].join('-'))
this.$element
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
[dimension](this.$element[0][scrollSize])
}
Collapse.prototype.hide = function() {
if (this.transitioning || !this.$element.hasClass('in'))
return
var startEvent = $.Event('hide.bs.collapse')
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented())
return
var dimension = this.dimension()
this.$element
[dimension](this.$element[dimension]())
[0].offsetHeight
this.$element
.addClass('collapsing')
.removeClass('collapse')
.removeClass('in')
this.transitioning = 1
var complete = function() {
this.transitioning = 0
this.$element
.trigger('hidden.bs.collapse')
.removeClass('collapsing')
.addClass('collapse')
}
if (!$.support.transition)
return complete.call(this)
this.$element
[dimension](0)
.one($.support.transition.end, $.proxy(complete, this))
.emulateTransitionEnd(350)
}
Collapse.prototype.toggle = function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
// COLLAPSE PLUGIN DEFINITION
// ==========================
var old = $.fn.collapse
$.fn.collapse = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.collapse')
var options = $.extend({}, Collapse.DEFAULTS, $this.data(), typeof option == 'object' && option)
if (!data)
$this.data('bs.collapse', (data = new Collapse(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.collapse.Constructor = Collapse
// COLLAPSE NO CONFLICT
// ====================
$.fn.collapse.noConflict = function() {
$.fn.collapse = old
return this
}
// COLLAPSE DATA-API
// =================
$(document).on('click.bs.collapse.data-api', '[data-toggle=collapse]', function(e) {
var $this = $(this), href
var target = $this.attr('data-target')
|| e.preventDefault()
|| (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '') //strip for ie7
var $target = $(target)
var data = $target.data('bs.collapse')
var option = data ? 'toggle' : $this.data()
var parent = $this.attr('data-parent')
var $parent = parent && $(parent)
if (!data || !data.transitioning) {
if ($parent)
$parent.find('[data-toggle=collapse][data-parent="' + parent + '"]').not($this).addClass('collapsed')
$this[$target.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
}
$target.collapse(option)
})
}(jQuery);
/* ========================================================================
* Bootstrap: scrollspy.js v3.0.3
* http://getbootstrap.com/javascript/#scrollspy
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// SCROLLSPY CLASS DEFINITION
// ==========================
function ScrollSpy(element, options) {
var href
var process = $.proxy(this.process, this)
this.$element = $(element).is('body') ? $(window) : $(element)
this.$body = $('body')
this.$scrollElement = this.$element.on('scroll.bs.scroll-spy.data-api', process)
this.options = $.extend({}, ScrollSpy.DEFAULTS, options)
this.selector = (this.options.target
|| ((href = $(element).attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) //strip for ie7
|| '') + ' .nav li > a'
this.offsets = $([])
this.targets = $([])
this.activeTarget = null
this.refresh()
this.process()
}
ScrollSpy.DEFAULTS = {
offset: 10
}
ScrollSpy.prototype.refresh = function() {
var offsetMethod = this.$element[0] == window ? 'offset' : 'position'
this.offsets = $([])
this.targets = $([])
var self = this
var $targets = this.$body
.find(this.selector)
.map(function() {
var $el = $(this)
var href = $el.data('target') || $el.attr('href')
var $href = /^#\w/.test(href) && $(href)
return ($href
&& $href.length
&& [[$href[offsetMethod]().top + (!$.isWindow(self.$scrollElement.get(0)) && self.$scrollElement.scrollTop()), href]]) || null
})
.sort(function(a, b) {
return a[0] - b[0]
})
.each(function() {
self.offsets.push(this[0])
self.targets.push(this[1])
})
}
ScrollSpy.prototype.process = function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset
var scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight
var maxScroll = scrollHeight - this.$scrollElement.height()
var offsets = this.offsets
var targets = this.targets
var activeTarget = this.activeTarget
var i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0]) && this.activate(i)
}
for (i = offsets.length; i--; ) {
activeTarget != targets[i]
&& scrollTop >= offsets[i]
&& (!offsets[i + 1] || scrollTop <= offsets[i + 1])
&& this.activate(targets[i])
}
}
ScrollSpy.prototype.activate = function(target) {
this.activeTarget = target
$(this.selector)
.parents('.active')
.removeClass('active')
var selector = this.selector
+ '[data-target="' + target + '"],'
+ this.selector + '[href="' + target + '"]'
var active = $(selector)
.parents('li')
.addClass('active')
if (active.parent('.dropdown-menu').length) {
active = active
.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate.bs.scrollspy')
}
// SCROLLSPY PLUGIN DEFINITION
// ===========================
var old = $.fn.scrollspy
$.fn.scrollspy = function(option) {
return this.each(function() {
var $this = $(this)
var data = $this.data('bs.scrollspy')
var options = typeof option == 'object' && option
if (!data)
$this.data('bs.scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string')
data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
// SCROLLSPY NO CONFLICT
// =====================
$.fn.scrollspy.noConflict = function() {
$.fn.scrollspy = old
return this
}
// SCROLLSPY DATA-API
// ==================
$(window).on('load', function() {
$('[data-spy="scroll"]').each(function() {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(jQuery);
/* ========================================================================
* Bootstrap: transition.js v3.0.3
* http://getbootstrap.com/javascript/#transitions
* ========================================================================
* Copyright 2013 Twitter, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* ======================================================================== */
+function($) {
"use strict";
// CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
// ============================================================
function transitionEnd() {
var el = document.createElement('bootstrap')
var transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd'
, 'MozTransition': 'transitionend'
, 'OTransition': 'oTransitionEnd otransitionend'
, 'transition': 'transitionend'
}
for (var name in transEndEventNames) {
if (el.style[name] !== undefined) {
return {end: transEndEventNames[name]}
}
}
}
// http://blog.alexmaccaw.com/css-transitions
$.fn.emulateTransitionEnd = function(duration) {
var called = false, $el = this
$(this).one($.support.transition.end, function() {
called = true
})
var callback = function() {
if (!called)
$($el).trigger($.support.transition.end)
}
setTimeout(callback, duration)
return this
}
$(function() {
$.support.transition = transitionEnd()
})
}(jQuery);
| nick144/Tournaments | js/bootstrap.js | JavaScript | gpl-2.0 | 36,381 |
var express = require('express'),
Weapon = require('../models/Weapon'),
router = express.Router();
// HOMEPAGE
router.get('/', function(req, res) {
res.render('index', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'Hello Word!'
});
});
// WEAPON
router.get('/weapon', function(req, res) {
var schema = {};
Weapon.schema.eachPath(function (pathname, schemaType) {
schema[pathname] = schemaType.instance;
});
res.render('weapon', {
title:'Weapons Guide | Fire Emblem | Awakening',
credit: 'Matt.Dodson.Digital',
msg: 'This is a form.',
schema: schema
});
});
module.exports = router;
| dodsonm/fire-emblem-awakening | routes/index.js | JavaScript | gpl-2.0 | 717 |
/*BEGIN_LEGAL
Intel Open Source License
Copyright (c) 2002-2013 Intel Corporation. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer. Redistributions
in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution. Neither the name of
the Intel Corporation nor the names of its contributors may be used to
endorse or promote products derived from this software without
specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE INTEL OR
ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
END_LEGAL */
#include <stdio.h>
#pragma data_seg("dsec")
static char greeting[] = "Hello";
#pragma code_seg("asection")
void report()
{
printf("%s, world\n", greeting);
}
#pragma code_seg(".text")
int main ()
{
report();
return 0;
}
| cyjseagull/SHMA | zsim-nvmain/pin_kit/source/tools/ToolUnitTests/secname_app.cpp | C++ | gpl-2.0 | 1,776 |
<?php
/* Icinga Web 2 | (c) 2013-2015 Icinga Development Team | GPLv2+ */
namespace Icinga\Module\Monitoring\DataView;
class Contactgroup extends DataView
{
/**
* {@inheritdoc}
*/
public function isValidFilterTarget($column)
{
if ($column[0] === '_' && preg_match('/^_(?:host|service)_/', $column)) {
return true;
}
return parent::isValidFilterTarget($column);
}
/**
* {@inheritdoc}
*/
public function getColumns()
{
return array(
'contactgroup_name',
'contactgroup_alias',
'contact_object_id',
'contact_id',
'contact_name',
'contact_alias',
'contact_email',
'contact_pager',
'contact_has_host_notfications',
'contact_has_service_notfications',
'contact_can_submit_commands',
'contact_notify_service_recovery',
'contact_notify_service_warning',
'contact_notify_service_critical',
'contact_notify_service_unknown',
'contact_notify_service_flapping',
'contact_notify_service_downtime',
'contact_notify_host_recovery',
'contact_notify_host_down',
'contact_notify_host_unreachable',
'contact_notify_host_flapping',
'contact_notify_host_downtime',
'contact_notify_host_timeperiod',
'contact_notify_service_timeperiod'
);
}
/**
* {@inheritdoc}
*/
public function getSortRules()
{
return array(
'contactgroup_name' => array(
'order' => self::SORT_ASC
),
'contactgroup_alias' => array(
'order' => self::SORT_ASC
)
);
}
/**
* {@inheritdoc}
*/
public function getFilterColumns()
{
return array(
'contactgroup', 'contact',
'host', 'host_name', 'host_display_name', 'host_alias',
'hostgroup', 'hostgroup_alias', 'hostgroup_name',
'service', 'service_description', 'service_display_name',
'servicegroup', 'servicegroup_alias', 'servicegroup_name'
);
}
/**
* {@inheritdoc}
*/
public function getSearchColumns()
{
return array('contactgroup_alias');
}
}
| yodaaut/icingaweb2 | modules/monitoring/library/Monitoring/DataView/Contactgroup.php | PHP | gpl-2.0 | 2,396 |
<h2><?php print $node->title; ?></h2>
<h3><?php print content_format('field_subtitle', $field_subtitle[0]); ?></h3>
<? print l('Back', 'node/'.$node->field_case_project[0]['nid'], array('html'=>TRUE, 'attributes'=>array('class'=>'back-link'))); ?>
<? print content_format('field_case_intro_title', $field_case_intro_title[0]); ?>
<? print content_format('field_case_intro_body', $field_case_intro_body[0]); ?>
<? print content_format('field_case_video', $field_case_video[0]); ?>
<?
$distribution_body = strip_tags($field_case_distribution_body[0]['value']);
if (!empty($distribution_body))
print content_format('field_case_distribution_body', $field_case_distribution_body[0]);
?>
<? if (!empty($field_case_distribution_image[0]['filename'])) print content_format('field_case_distribution_image', $field_case_distribution_image[0], 'image_plain'); ?>
<?
$finance_body = strip_tags($field_case_finance_body[0]['value']);
if (!empty($finance_body))
print content_format('field_case_finance_body', $field_case_finance_body[0]);
?>
<? if (!empty($field_case_finance_image[0]['filename'])) print content_format('field_case_finance_image', $field_case_finance_image[0], 'image_plain'); ?>
<?
$multiplatform_body = strip_tags($field_case_multiplatform_body[0]['value']);
if (!empty($multiplatform_body))
print content_format('field_case_multiplatform_body', $field_case_multiplatform_body[0]);
?>
<? if (!empty($field_case_multiplatform_image[0]['filename'])) print content_format('field_case_multiplatform_image', $field_case_multiplatform_image[0], 'image_plain'); ?>
<?
$ad_body = strip_tags($field_case_ad_body[0]['value']);
if (!empty($ad_body))
print content_format('field_case_ad_body', $field_case_ad_body[0]);
?>
<? if (!empty($field_case_ad_image[0]['filename'])) print content_format('field_case_ad_image', $field_case_ad_image[0], 'image_plain'); ?>
<?
$international_body = strip_tags($field_case_international_body[0]['value']);
if (!empty($international_body))
print content_format('field_case_international_body', $field_case_international_body[0]);
?>
<? if (!empty($field_case_international_image[0]['filename'])) print content_format('field_case_international_image', $field_case_international_image[0], 'image_plain'); ?>
<?
$format_body = strip_tags($field_case_format_body[0]['value']);
if (!empty($format_body))
print content_format('field_case_format_body', $field_case_format_body[0]);
?>
<? if (!empty($field_case_format_image[0]['filename'])) print content_format('field_case_format_image', $field_case_format_image[0], 'image_plain'); ?>
<? print content_format('field_case_whitepaper', $field_case_whitepaper[0]); ?>
<div class="sponsor-logos">
<? print views_embed_view('sponsor_logos', 'block_1', $field_case_project[0]['nid']); ?>
</div> | iTTemple/html | 2012/themes/garland/node-case_study.tpl.php | PHP | gpl-2.0 | 2,796 |
package ms.aurora.browser.wrapper;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.tidy.Tidy;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.xpath.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
/**
* A parser / access layer for HTML pages
* @author Rick
*/
public final class HTML {
private static Logger logger = Logger.getLogger(HTML.class);
private Document dom;
public HTML(Document dom) {
this.dom = dom;
}
public Document getDOM() {
return dom;
}
public List<Node> searchXPath(String expression) {
List<Node> matchingElements = new ArrayList<Node>();
try {
XPathExpression expressionObj = getExpression(expression);
NodeList resultingNodeList = (NodeList) expressionObj.evaluate(dom,
XPathConstants.NODESET);
for (int index = 0; index < resultingNodeList.getLength(); index++) {
matchingElements.add(resultingNodeList.item(index));
}
} catch (XPathExpressionException e) {
logger.error("Incorrect XPath expression", e);
}
return matchingElements;
}
public List<Node> searchXPath(Node base, String expression) {
List<Node> matchingElements = new ArrayList<Node>();
try {
XPathExpression expressionObj = getExpression(expression);
NodeList resultingNodeList = (NodeList) expressionObj.evaluate(base,
XPathConstants.NODESET);
for (int index = 0; index < resultingNodeList.getLength(); index++) {
matchingElements.add(resultingNodeList.item(index));
}
} catch (XPathExpressionException e) {
logger.error("Incorrect XPath expression", e);
}
return matchingElements;
}
private XPathExpression getExpression(String expression) throws XPathExpressionException {
XPath xpath = XPathFactory.newInstance().newXPath();
return xpath.compile(expression);
}
public static HTML fromStream(InputStream stream) {
try {
/*
* UGLY ASS W3C API IS UGLY
*/
Tidy tidy = new Tidy();
tidy.setXHTML(true);
Document dom = tidy.parseDOM(stream, null);
dom.getDocumentElement().normalize();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Source xmlSource = new DOMSource(dom);
Result outputTarget = new StreamResult(outputStream);
TransformerFactory.newInstance().newTransformer().transform(xmlSource, outputTarget);
InputStream is = new ByteArrayInputStream(outputStream.toByteArray());
return new HTML(db.parse(is));
} catch (Exception e) {
logger.error("Failed to parse HTML properly", e);
}
return null;
}
}
| rvbiljouw/aurorabot | src/main/java/ms/aurora/browser/wrapper/HTML.java | Java | gpl-2.0 | 3,499 |
<?php
/**
* Plugin Name: Custom Register Form Plugin
* Plugin URI: http://tamanhquyen.com/register-form-for-wordpress.html
* Description: Create Custom Register Form Frontend Page
* Version: 1.0
* Author: TA MANH QUYEN
* Author URI: http://tamanhquyen.com
*/
global $wp_version;
if(version_compare($wp_version,'3.6.1','<'))
{
exit('This is plugin requice Wordpress Version 3.6 on highter. Please update now!');
}
register_activation_hook(__FILE__,'mq_register_setting');
register_deactivation_hook(__FILE__,'mq_delete_setting');
function enque_register()
{
wp_register_script('mq_register_ajax',plugins_url('inc/js/init.js',__FILE__),array('jquery'),true);
wp_localize_script('mq_register_ajax','mq_register_ajax',array('mq_ajax_url' => admin_url( 'admin-ajax.php' )));
wp_enqueue_script('mq_register_ajax');
}
add_action('wp_enqueue_scripts','enque_register');
function mq_registerform_menu()
{
add_menu_page('Register Form Setting','Register Form','update_plugins','register-form-setting','mq_registerform_set','',1);
}
add_action('admin_menu','mq_registerform_menu');
function mq_register_setting()
{
add_option('mq_register_form_title','','255','yes');
add_option('mq_register_form_setting','','255','yes');
add_option('mq_register_form_css','','255','yes');
add_option('mq_register_form_intro','','255','yes');
add_option('mq_register_facelink','','255','yes');
}
function mq_delete_setting()
{
delete_option('mq_register_form_setting');
delete_option('mq_register_form_title');
delete_option('mq_register_form_css');
delete_option('mq_register_facelink');
delete_option('mq_register_form_intro');
remove_shortcode('mq_register');
}
include_once('inc/mq_shortcode.php');
include_once('inc/mq_ajax.php');
include_once('inc/form_setting.php');
include_once('inc/form_create.php');
include_once('inc/script/register_action.php'); | Nguyenkain/hanghieusales | wp-content/plugins/tamanhquyen_register/plugin_funtion.php | PHP | gpl-2.0 | 1,849 |
<?php
class grid_assignments_progress{
private $db = false;
private $user;
private $edit_color = '#FFFFFF';
public function __construct(){
$this->db = Connection::getDB();
$this->user = new administrator();
if($this->user->role=='pupil' || $this->user->role=='parent'){
$this->edit_color = '#AAAAAA';
}
$this->db->query("START TRANSACTION");
error_reporting(E_ALL ^ E_NOTICE);
switch ($_POST['action']) {
case 'editresult':
$this->editResult($_POST['id'],$_POST['value'],$_POST['pass']);
break;
case 'editgrade':
$this->editGrade($_POST['id'],$_POST['value'],$_POST['pass']);
break;
case 'editassessment':
$this->editAssessment($_POST['id'],$_POST['assessment']);
break;
case 'deactive':
$this->deactivePerformance($_POST['id']);
break;
case 'reactive':
$this->reactivePerformance($_POST['id']);
break;
case 'editstatus':
$this->editStutus($_POST['assid'],$_POST['pid'],$_POST['value']);
break;
case 'makeassubmitted':
$this->makeAsSubmitted($_POST['assid'],$_POST['pid']);
break;
case 'makeasnotsubmitted':
$this->makeAsNotSubmitted($_POST['assid'],$_POST['pid']);
break;
case 'activate':
$this->activate($_POST['assid'],$_POST['pid'],$_POST['type']);
break;
case 'remove':
$this->remove($_POST['assid'],$_POST['pid'],$_POST['type']);
break;
case 'deactivate':
$this->deactivate($_POST['assid'],$_POST['pid'],$_POST['type']);
break;
default:
$this->getAssignmentsGrid();
break;
}
$this->db->query("COMMIT");
}
private function editStutus($id,$pid,$val){
$result = $this->db->query("UPDATE pupli_submission_slot SET status='$val' WHERE assignment_id=$id AND pupil_id=$pid");
}
private function makeAsSubmitted($id,$pid){
$result = $this->db->query("UPDATE pupli_submission_slot SET status='1', submission_date = NOW() WHERE assignment_id=$id AND pupil_id=$pid");
}
private function makeAsNotSubmitted($id,$pid){
$ns = dlang("grids_not_subm_text","Not subm.");
$result = $this->db->query("UPDATE pupli_submission_slot SET status='$ns' WHERE assignment_id=$id AND pupil_id=$pid");
}
private function editResult($id,$val,$pass){
@session_start();
$_SESSION['submissions_update']=$this->user->id;
session_write_close();
$this->db->query("UPDATE pupil_submission_result SET result='$val', pass='$pass' WHERE pupil_submission_result_id=$id");
if($val=='A' || $val=='B'|| $val=='C'||$val=='D'||$val=='E'||$val=='F'||$val=='Fx'||$val==dlang("passvalue","Pass")||$val==dlang("npassvalue","NPass")){
$result = $this->db->query("UPDATE pupil_submission_result SET assessment='$val' WHERE pupil_submission_result_id=$id");
}
$this->db->query("UPDATE pupli_submission_slot,pupil_submission_result SET pupli_submission_slot.status='1' WHERE pupli_submission_slot.submission_slot_id = pupil_submission_result.submission_slot_id
AND pupil_submission_result.pupil_submission_result_id = $id");
echo 1;
}
private function editGrade($id,$val,$pass){
$result = $this->db->query("UPDATE pupil_submission_result SET assessment='$assess', pass=$val WHERE pupil_submission_result_id=$id");
}
private function editAssessment($id, $assess){
$result = $this->db->query("UPDATE pupil_performance_assessment SET assessment='$assess' WHERE pupil_performance_assessment_id=$id");
}
private function remove($id,$pid,$type){
if($type=="performance"){
$result = $this->db->query("DELETE FROM pupil_performance_assessment WHERE pupil_id=$pid AND performance_id=$id");
}else{
$result = $this->db->query("DELETE FROM pupli_submission_slot WHERE pupil_id=$pid AND assignment_id=$id");
}
}
private function activate($id,$pid,$type){
if($type=="performance"){
$this->db->query("UPDATE pupil_performance_assessment SET active=1, activation_date=NOW() WHERE pupil_id=$pid AND performance_id=$id");
}else{
$this->db->query("UPDATE pupli_submission_slot SET active=1, activation_date=NOW() WHERE pupil_id=$pid AND assignment_id=$id");
}
}
private function deactivate($id,$pid,$type){
if($type=="performance"){
$this->db->query("UPDATE pupil_performance_assessment SET active=0 WHERE pupil_id=$pid AND performance_id=$id");
}else{
$this->db->query("UPDATE pupli_submission_slot SET active=0 WHERE pupil_id=$pid AND assignment_id=$id");
}
}
private function getPerformanceArray($result,$rows){
//$rows = array();
while($row = mysql_fetch_assoc($result)){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][12] = $row['performance_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][1] = $row['perf_title'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][7] = $row['sid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][8] = $row['s_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][11] = $row['active']?"1":"0.5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][13] = $row['active'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][10] = $row['active']?"#FFFFFF":"#F5F5F5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][0] = $row['pid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][3]= $row['ass'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][13] = $row['active'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][10] = $row['active']?"#FFFFFF":"#F5F5F5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][11] = $row['active']?"1":"0.5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][4][] = $row['obj_title'];
if($row['ass'] == "" || $row['ass'] == "na"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = $this->edit_color;
}elseif($row['ass'] == "F" || $row['ass'] == "Fx"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = "#ff8888";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['performancep_'.$row['performance_id']][14][$row['pid']][5] = "#88ff88";
}
}
//print_r($rows);
return $rows;
}
private function getAssignmentsGrid(){
header("Content-type:text/xml");
print('<?xml version="1.0" encoding="UTF-8"?>');
$id = $_GET['id'];
$and = "";
if(isset($_GET['stg']) && $_GET['stg']!=""){
$and = "AND studygroups.studygroup_id = ".$_GET['stg'];
}
$result = $this->db->query("
SELECT course_rooms_assignments.number as numb, course_rooms_assignments.title_en as title_assignment,
course_rooms_assignments.assignment_id as aid,
DATEDIFF(course_rooms_assignments.deadline_date, CURDATE()) as dl_date,
DATEDIFF(course_rooms_assignments.deadline_date, pupli_submission_slot.submission_date) as submission_date,
course_rooms_assignments.deadline_date as deadline_date2,
pupli_submission_slot.submission_date as submission_date2,
course_objectives.title_en as title_course_obj,
course_rooms_assignments.deadline as deadline,
course_rooms_assignments.deadline_passed as dp,
pupli_submission_slot.content_en as pcont,
pupli_submission_slot.status as status,
pupli_submission_slot.active as active,
resultsets.result_max as max_rs,
resultsets.result_pass as pass_rs,
resultsets.studygroup_ids as studygroup_ids,
result_units.result_unit_en as unit_rs,
pupil_submission_result.result as subm_result,
pupil_submission_result.assessment as assessment,
pupil_submission_result.pupil_submission_result_id as psr,
studygroups.title_en as sid,
studygroups.studygroup_id as s_id,
result_units.result_unit_id as result_unit_id,
academic_years.title_en as acyear,
subjects.title_en as subject,
academic_years.academic_year_id as acyear_id,
subjects.subject_id as subject_id,
resultsets.castom_name as castom_name
FROM course_rooms,pupli_submission_slot, course_rooms_assignments, resultsets,
studygroups, course_objectives, result_units, pupil_submission_result, resultset_to_course_objectives, academic_years, subjects
WHERE pupli_submission_slot.assignment_id = course_rooms_assignments.assignment_id
AND course_rooms_assignments.course_room_id = course_rooms.course_room_id
AND course_rooms.course_room_id = studygroups.course_room_id
AND resultsets.assignment_id = pupli_submission_slot.assignment_id
AND resultset_to_course_objectives.resultset_id = resultsets.resultset_id
AND course_objectives.objective_id = resultset_to_course_objectives.objective_id
AND result_units.result_unit_id = resultsets.result_unit_id
AND pupil_submission_result.result_set_id = resultsets.resultset_id
AND pupil_submission_result.submission_slot_id = pupli_submission_slot.submission_slot_id
AND pupli_submission_slot.pupil_id=$id
AND studygroups.subject_id=subjects.subject_id
AND subjects.academic_year_id = academic_years.academic_year_id
AND resultset_to_course_objectives.type = 'assignment'
{$and}
");
$result_perf = $this->db->query("
SELECT performance.title_en as perf_title, pupil_performance_assessment.pupil_performance_assessment_id as pid,
course_objectives.title_en as obj_title,pupil_performance_assessment.assessment as ass,
pupil_performance_assessment.passed as passed,
pupil_performance_assessment.active as active,
studygroups.title_en as sid, studygroups.studygroup_id as s_id,
pupil_performance_assessment.performance_id as performance_id,
resultsets.resultset_id as resultset_id,
academic_years.title_en as acyear,
subjects.title_en as subject,
academic_years.academic_year_id as acyear_id,
subjects.subject_id as subject_id
FROM course_rooms, pupil_performance_assessment, performance, studygroups,resultsets,course_objectives,resultset_to_course_objectives, academic_years, subjects
WHERE pupil_performance_assessment.performance_id = performance.performance_id
AND performance.course_room_id = course_rooms.course_room_id
AND course_rooms.course_room_id = studygroups.course_room_id
AND resultsets.resultset_id = pupil_performance_assessment.resultset_id
AND resultset_to_course_objectives.resultset_id = resultsets.resultset_id
AND course_objectives.objective_id = resultset_to_course_objectives.objective_id
AND pupil_performance_assessment.pupil_id = $id
AND studygroups.subject_id=subjects.subject_id
AND subjects.academic_year_id = academic_years.academic_year_id
AND resultset_to_course_objectives.type = 'performance'
");
echo '<rows>';
$assarr = $this->getAssignmentsArray($result);
$perfarr = $this->getPerformanceArray($result_perf,$assarr);
//$perform = $this->outPerformanceArray($this->getPerformanceArray($result_perf));
$this->outAssignmentsArray($perfarr);
echo '</rows>';
}
private function outPerformanceArray($value2){
$perf_xml = '
<row id="performance_'.$value2[12].'">
<cell bgColor="'.$value2[10].'" style="opacity: '.$value2[11].';" sid="performance_'.$value2[12].'" image="assessment.png">'.$value2[1].'</cell>
<cell bgColor="'.$value2[10].'" style="opacity: '.$value2[11].';"/><cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/>
<cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/><cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/>
<cell style="opacity: '.$value2[11].';" bgColor="'.$value2[10].'"/><cell bgColor="'.$value2[10].'"/>';
foreach ($value2[14] as $value3) {
$perf_xml.= '
<row id="p_'.$value3[0].'" style="opacity: '.$value3[11].';">
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$value3[11].';" image="objective.png" >'.$value2[7].': '.implode(', ',$value3[4]).'</cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';"></cell>
<cell bgColor="#FFFFFF" style="opacity: '.$value3[11].';">'.$value3[6].'</cell>
<cell style="opacity: '.$value3[11].';" xmlcontent="1" bgColor="'.$value3[5].'">'.$value3[3].'<option value="A">'."A".'</option>
<option value="B">'."B".'</option>
<option value="C">'."C".'</option>
<option value="D">'."D".'</option>
<option value="E">'."E".'</option>
<option value="F">'."F".'</option>
<option value="Fx">'."Fx".'</option>
<option value="">'."".'</option>
</cell>
</row>
';
}
$perf_xml.= '<userdata name="activate">'.$value2[13].'</userdata></row>';
return $perf_xml;
}
private function getAssignmentsArray($result){
$rows = array();
$graeds = array('A','B','C','D','E','F');
while($row = mysql_fetch_assoc($result)){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']][0] = $row['sid'];
$rows[$row['acyear_id']][0] = $row['acyear'];
$rows[$row['acyear_id']][$row['subject_id']][0] = $row['subject'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][0] = $row['aid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][2] = $row['title_assignment'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][3] = $row['dp'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][4] = $row['pcont'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][5] = $row['dl_date'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][20] = $row['deadline_date2'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][21] = $row['submission_date2'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][16] = $row['deadline'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][6] = $row['status'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][7] = $row['title_course'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][9] = $row['sid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][10] = $row['active']?"#FFFFFF":"#F5F5F5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][11] = $row['active']?"1":"0.5";
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][12] = $row['active'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][15] = $row['submission_date'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][0] = $row['psr'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][1] = $row['castom_name'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][2] = $row['max_rs'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][3] = $row['pass_rs'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][4] = $row['subm_result'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][6] = $row['dl_date'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][7] = $row['sid'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][8] = $row['s_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = $row['assessment'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][12] = $row['result_unit_id'];
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][14] = $row['studygroup_ids'];
if($row['assessment']=="p"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = dlang("passvalue","Pass");
}
if($row['assessment']=="np"){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][9] = dlang("npassvalue","NPass");
}
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][10] = $row['title_course'];
$pass = $row['pass_rs'];
$res = $row['subm_result'];
switch ($row['result_unit_id']) {
case '1':
if((int)$pass <= (int)$res){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
case '2':
if((int)$pass <= (int)$res){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
case '3':
if(array_search($pass,$graeds)>=array_search($res,$graeds)){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
case '4':
if(strtolower($res)==dlang("passvalue","Pass")){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}
break;
}
if($res==""){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = $this->edit_color;
}
if($row['assessment']!=""){
if($row['assessment']=='F' || $row['assessment']=="Fx" || $row['assessment']==dlang("npassvalue","NPass")){
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#ff8888";
}else{
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][11] = "#88ff88";
}
}
$rows[$row['acyear_id']][$row['subject_id']][$row['s_id']]['assignment_'.$row['aid']][8][$row['psr']][5][] = $row['title_course_obj'];
}
// print_r($rows);
return $rows;
}
private function outStgsArray($stg){
foreach ($stg as $key => $group){
if($key=="0")
continue;
echo '
<row id="stg_'.$key.'">
<cell style="color:rgb(73, 74, 75);" sid="stg_'.$key.'" image="studygroup.png">'.$group[0].'</cell>';
foreach ($group as $key2 => $assignment){
if($key2=="0"){
continue;
}
$tkey2 = explode('_',$key2);
if($tkey2[0] == 'performancep'){
echo $this->outPerformanceArray($assignment);
continue;
}
echo '<row style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';" bgColor="'.$assignment[10].'" id="assignment_'.$assignment[0].'"><cell bgColor="'.$assignment[10].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';" image="submission.png">'.$assignment[2].'</cell>';
if($assignment[6]!="1" && $assignment[6]!=dlang("grids_not_subm_text","Not subm.") && $assignment[6]!="Not subm."){
echo '<cell bgColor="'.$this->edit_color.'" style="color:#006699; opacity: '.$assignment[11].';">'.$assignment[6].'</cell>';
}else{
if($assignment[5]>=0 && ($assignment[6]==dlang("grids_not_subm_text","Not subm.") || $assignment[6]=="Not subm.") ){
echo '<cell bgColor="'.$this->edit_color.'" style="color:#6495ED; opacity: '.$assignment[11].';">'.dlang("grids_not_subm_text","Not subm.").'</cell>';
}elseif($assignment[5]<0 && ($assignment[6]==dlang("grids_not_subm_text","Not subm."))){
echo '<cell bgColor="'.$this->edit_color.'" style="color:#EE6A50; opacity: '.$assignment[11].';">'.dlang("grids_not_subm_text","Not subm.").'</cell>';
}else{
if($assignment[16]=='No deadline'){
echo '<cell bgColor="'.$this->edit_color.'" style="color:green; opacity: '.$assignment[9].';">'.dlang("grids_subm_text","Subm.").'</cell>';
}else{
if($assignment[15]>=0){
if($assignment[21]<=$assignment[20]){
echo '<cell bgColor="'.$this->edit_color.'" style="color:green; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_daye","day early").'</cell>';
}else{
echo '<cell bgColor="'.$this->edit_color.'" style="color:red; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_dayl","day late").'</cell>';
}
}else{
echo '<cell bgColor="'.$this->edit_color.'" style="color:red; opacity: '.$assignment[13].';">'.abs($assignment[15]).' '.dlang("grids_not_subm_dayl","day late").'</cell>';
}
}
}
}
echo '<cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/><cell bgColor="'.$assignment[10].'"/>';
foreach ($assignment[8] as $key3 => $rset) {
$sql = "SELECT title_en FROM studygroups WHERE studygroup_id IN (".$rset[14].")";
$result = $this->db->query($sql);
$sgids = null;
while($row = mysql_fetch_assoc($result)){
$sgids[] = $row['title_en'];
}
echo '
<row id="a_'.$rset[0].'" style="opacity: '.$assignment[11].';">
<cell image="objective.png" bgColor="#FFFFFF" style="opacity: '.$assignment[11].'; color:rgb(73, 74, 75);">'.implode(', ', $sgids).': '.implode(', ',$rset[5]).'</cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';"></cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[1].'</cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[2].'</cell>
<cell bgColor="#FFFFFF" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[3].'</cell>
';
switch ($rset[12]) {
case '1':
echo '<cell type="ed" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'</cell>';
break;
case '2':
echo '<cell type="ed" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'</cell>';
break;
case '3':
echo '<cell type="co" xmlcontent="1" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[4].'<option value="'."A".'">'."A".'</option>
<option value="B">'."B".'</option>
<option value="C">'."C".'</option>
<option value="D">'."D".'</option>
<option value="E">'."E".'</option>
<option value="F">'."F".'</option>
<option value="Fx">'."Fx".'</option>
</cell>
';
break;
case '4':
echo '<cell type="co" xmlcontent="1" bgColor="'.$this->edit_color.'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.dlang($rset[4]).'<option value="'.dlang("passvalue","Pass").'">'.dlang("passvalue","Pass").'</option>
<option value="'.dlang("npassvalue","NPass").'">'.dlang("npassvalue","NPass").'</option>
<option value="">'."".'</option>
</cell>';
break;
default:
break;
}
if($rset[12]=='4'){
echo '<cell xmlcontent="1" bgColor="'.$rset[11].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[9].'<option value="'.dlang("passvalue","Pass").'">'.dlang("passvalue","Pass").'</option>
<option value="'.dlang("npassvalue","NPass").'">'.dlang("npassvalue","NPass").'</option>
<option value="">'."".'</option>
</cell><userdata name="unit">'.$rset[12].'</userdata></row>';
}else{
echo '<cell xmlcontent="1" bgColor="'.$rset[11].'" style="color:rgb(73, 74, 75); opacity: '.$assignment[11].';">'.$rset[9].'<option value="'."A".'">'."A".'</option>
<option value="B">'."B".'</option>
<option value="C">'."C".'</option>
<option value="D">'."D".'</option>
<option value="E">'."E".'</option>
<option value="F">'."F".'</option>
<option value="Fx">'."Fx".'</option>
<option value="">'."".'</option>
</cell><userdata name="unit">'.$rset[12].'</userdata></row>';
}
}
echo "<userdata name='submitted'>".($assignment[6]=="1"?1:0)."</userdata>";
echo "<userdata name='activate'>".$assignment[12]."</userdata>";
echo '</row>';
}
echo '</row>';
}
}
private function outAssignmentsArray($acyears){
foreach($acyears as $yid => $year){
if($yid=="0")
continue;
echo '<row id="year_'.$yid.'">
<cell style="color:rgb(73, 74, 75);" sid="year_'.$yid.'" image="folder_closed.png">'.$year[0].'</cell>';
foreach($year as $subid => $subject){
if($subid=="0" || !$subject[0])
continue;
echo '<row id="subject_'.$subid.'">
<cell style="color:rgb(73, 74, 75);" sid="subject_'.$subid.'" image="folder_closed.png">'.$subject[0].'</cell>';
$this->outStgsArray($subject);
echo '</row>';
}
echo '</row>';
}
}
}
?> | ya6adu6adu/schoolmule | connectors/grid_assignments_progress.php | PHP | gpl-2.0 | 30,338 |
/*
* Copyright (C) 2004
* Swiss Federal Institute of Technology, Lausanne. All rights reserved.
*
* Developed at the Autonomous Systems Lab.
* Visit our homepage at http://asl.epfl.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.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#ifndef NPM_TRAJECTORYDRAWING_HPP
#define NPM_TRAJECTORYDRAWING_HPP
#include <npm/gfx/Drawing.hpp>
namespace npm {
class RobotServer;
class TrajectoryDrawing
: public Drawing
{
public:
TrajectoryDrawing(const RobotServer * owner);
virtual void Draw();
private:
const RobotServer * m_owner;
};
}
#endif // NPM_TRAJECTORYDRAWING_HPP
| poftwaresatent/sfl2 | npm/gfx/TrajectoryDrawing.hpp | C++ | gpl-2.0 | 1,294 |
/*
* This file is part of Soprano Project.
*
* Copyright (C) 2007-2010 Sebastian Trueg <trueg@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "servercore.h"
#include "servercore_p.h"
#include "soprano-server-config.h"
#include "serverconnection.h"
#ifdef BUILD_DBUS_SUPPORT
#include "dbus/dbuscontroller.h"
#endif
#include "modelpool.h"
#include "localserver.h"
#include "tcpserver.h"
#include "backend.h"
#include "storagemodel.h"
#include "global.h"
#include "asyncmodel.h"
#include <QtCore/QHash>
#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtNetwork/QTcpServer>
#include <QtNetwork/QHostAddress>
#include <QtNetwork/QTcpSocket>
#include <QtDBus/QtDBus>
const quint16 Soprano::Server::ServerCore::DEFAULT_PORT = 5000;
void Soprano::Server::ServerCorePrivate::addConnection( ServerConnection* conn )
{
connections.append( conn );
QObject::connect( conn, SIGNAL(destroyed(QObject*)), q, SLOT(serverConnectionFinished(QObject*)) );
conn->start();
qDebug() << Q_FUNC_INFO << "New connection. New count:" << connections.count();
}
Soprano::Server::ServerCore::ServerCore( QObject* parent )
: QObject( parent ),
d( new ServerCorePrivate() )
{
d->q = this;
// default backend
d->backend = Soprano::usedBackend();
d->modelPool = new ModelPool( this );
}
Soprano::Server::ServerCore::~ServerCore()
{
#ifdef BUILD_DBUS_SUPPORT
delete d->dbusController;
#endif
// We avoid using qDeleteAll because d->connections is modified by each delete operation
foreach(const Soprano::Server::ServerConnection* con, d->connections) {
delete con;
}
qDeleteAll( d->models );
delete d->modelPool;
delete d;
}
void Soprano::Server::ServerCore::setBackend( const Backend* backend )
{
d->backend = backend;
}
const Soprano::Backend* Soprano::Server::ServerCore::backend() const
{
return d->backend;
}
void Soprano::Server::ServerCore::setBackendSettings( const QList<BackendSetting>& settings )
{
d->settings = settings;
}
QList<Soprano::BackendSetting> Soprano::Server::ServerCore::backendSettings() const
{
return d->settings;
}
void Soprano::Server::ServerCore::setMaximumConnectionCount( int max )
{
d->maxConnectionCount = max;
}
int Soprano::Server::ServerCore::maximumConnectionCount() const
{
return d->maxConnectionCount;
}
Soprano::Model* Soprano::Server::ServerCore::model( const QString& name )
{
QHash<QString, Model*>::const_iterator it = d->models.constFind( name );
if ( it == d->models.constEnd() ) {
BackendSettings settings = d->createBackendSettings( name );
if ( isOptionInSettings( settings, BackendOptionStorageDir ) ) {
QDir().mkpath( valueInSettings( settings, BackendOptionStorageDir ).toString() );
}
Model* model = createModel( settings );
d->models.insert( name, model );
return model;
}
else {
return *it;
}
}
void Soprano::Server::ServerCore::removeModel( const QString& name )
{
clearError();
QHash<QString, Model*>::iterator it = d->models.find( name );
if ( it == d->models.end() ) {
setError( QString( "Could not find model with name %1" ).arg( name ) );
}
else {
Model* model = *it;
d->models.erase( it );
// delete the model, removing any cached data
delete model;
if ( isOptionInSettings( d->settings, BackendOptionStorageDir ) ) {
// remove the data on disk
backend()->deleteModelData( d->createBackendSettings( name ) );
// remove the dir which should now be empty
QDir( valueInSettings( d->settings, BackendOptionStorageDir ).toString() ).rmdir( name );
}
}
}
bool Soprano::Server::ServerCore::listen( quint16 port )
{
clearError();
if ( !d->tcpServer ) {
d->tcpServer = new TcpServer( d, this );
}
if ( !d->tcpServer->listen( QHostAddress::Any, port ) ) {
setError( QString( "Failed to start listening at port %1 on localhost." ).arg( port ) );
qDebug() << "Failed to start listening at port " << port;
return false;
}
else {
qDebug() << "Listening on port " << port;
return true;
}
}
void Soprano::Server::ServerCore::stop()
{
qDebug() << "Stopping and deleting";
// We avoid using qDeleteAll because d->connections is modified by each delete operation
foreach(const Soprano::Server::ServerConnection* con, d->connections) {
delete con;
}
qDeleteAll( d->models );
delete d->tcpServer;
d->tcpServer = 0;
delete d->socketServer;
d->socketServer = 0;
#ifdef BUILD_DBUS_SUPPORT
delete d->dbusController;
d->dbusController = 0;
#endif
}
quint16 Soprano::Server::ServerCore::serverPort() const
{
if ( d->tcpServer ) {
return d->tcpServer->serverPort();
}
else {
return 0;
}
}
bool Soprano::Server::ServerCore::start( const QString& name )
{
clearError();
if ( !d->socketServer ) {
d->socketServer = new LocalServer( d, this );
}
QString path( name );
if ( path.isEmpty() ) {
path = QDir::homePath() + QLatin1String( "/.soprano/socket" );
}
if ( !d->socketServer->listen( path ) ) {
setError( QString( "Failed to start listening at %1." ).arg( path ) );
return false;
}
else {
return true;
}
}
void Soprano::Server::ServerCore::registerAsDBusObject( const QString& objectPath )
{
#ifdef BUILD_DBUS_SUPPORT
if ( !d->dbusController ) {
QString path( objectPath );
if ( path.isEmpty() ) {
path = "/org/soprano/Server";
}
d->dbusController = new Soprano::Server::DBusController( this, path );
}
#else
qFatal("Soprano has been built without D-Bus support!" );
#endif
}
void Soprano::Server::ServerCore::serverConnectionFinished(QObject* obj)
{
qDebug() << Q_FUNC_INFO << d->connections.count();
// We use static_cast cause qobject_case will fail since the object has been destroyed
ServerConnection* conn = static_cast<ServerConnection*>( obj );
d->connections.removeAll( conn );
qDebug() << Q_FUNC_INFO << "Connection removed. Current count:" << d->connections.count();
}
Soprano::Model* Soprano::Server::ServerCore::createModel( const QList<BackendSetting>& settings )
{
Model* m = backend()->createModel( settings );
if ( m ) {
clearError();
}
else if ( backend()->lastError() ) {
setError( backend()->lastError() );
}
else {
setError( "Could not create new Model for unknown reason" );
}
return m;
}
QStringList Soprano::Server::ServerCore::allModels() const
{
return d->models.keys();
}
| KDE/soprano | server/servercore.cpp | C++ | gpl-2.0 | 7,513 |
package es.uniovi.asw.gui.util.form.validator.specific;
import es.uniovi.asw.gui.util.form.validator.composite.CheckAllValidator;
import es.uniovi.asw.gui.util.form.validator.simple.LengthValidator;
import es.uniovi.asw.gui.util.form.validator.simple.NumberValidator;
public class TelephoneValidator extends CheckAllValidator {
public TelephoneValidator() {
super(new NumberValidator(), new LengthValidator(9));
}
@Override
public String help() {
return "S�lo n�meros, 9 caracteres.";
}
}
| Arquisoft/Trivial5a | game/src/main/java/es/uniovi/asw/gui/util/form/validator/specific/TelephoneValidator.java | Java | gpl-2.0 | 507 |
Package.describe({
summary: "Next bike list package"
});
Package.on_use(function (api) {
api.use(['nb','underscore', 'templating', 'nb-autocomplete', 'nb-markers', 'nb-infowindow', 'nb-directions', 'nb-geocoder', 'nb-markerlabel', 'nb-citypicker'], ['client']);
api.add_files(['list.html', 'list.js'], ['client']);
});
| wolasss/nextbike-poland | packages/nb-list/package.js | JavaScript | gpl-2.0 | 326 |
<?php
/**
*
* @package phpBB Extension - Senky Post Links
* @copyright (c) 2014 Jakub Senko
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
* Swedish translation by/
* Svensk översättning av: Tage Strandell, Webmaster vulcanriders-sweden.org
*
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
$lang = array_merge($lang, array(
'ACP_POST_LINKS' => 'Post links',
'PL_ENABLE' => 'Tillåt inläggslänkar',
'PL_ENABLE_EXPLAIN' => 'Om tillåtna, varje länk kommer att innehålla kopierbara av de typer som tillåts nedan.',
'PL_LINK_ENABLE' => 'Tillåt normallänk',
'PL_BBCODE_ENABLE' => 'Tillåt BB-kodlänk',
'PL_HTML_ENABLE' => 'Tillåt HTML-länk',
));
| Senky/phpbb-ext-postlinks | language/sv/acp.php | PHP | gpl-2.0 | 755 |
package com.greenpineyu.fel.function.operator;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.greenpineyu.fel.Expression;
import com.greenpineyu.fel.common.ArrayUtils;
import com.greenpineyu.fel.common.Null;
import com.greenpineyu.fel.common.ReflectUtil;
import com.greenpineyu.fel.compile.FelMethod;
import com.greenpineyu.fel.compile.SourceBuilder;
import com.greenpineyu.fel.context.FelContext;
import com.greenpineyu.fel.function.CommonFunction;
import com.greenpineyu.fel.function.Function;
import com.greenpineyu.fel.parser.FelNode;
import com.greenpineyu.fel.security.SecurityMgr;
public class Dot implements Function {
private static final Logger logger = LoggerFactory.getLogger(Dot.class);
private SecurityMgr securityMgr;
public SecurityMgr getSecurityMgr() {
return securityMgr;
}
public void setSecurityMgr(SecurityMgr securityMgr) {
this.securityMgr = securityMgr;
}
static final Map<Class<?>, Class<?>> PRIMITIVE_TYPES;
static {
PRIMITIVE_TYPES = new HashMap<Class<?>, Class<?>>();
PRIMITIVE_TYPES.put(Boolean.class, Boolean.TYPE);
PRIMITIVE_TYPES.put(Byte.class, Byte.TYPE);
PRIMITIVE_TYPES.put(Character.class, Character.TYPE);
PRIMITIVE_TYPES.put(Double.class, Double.TYPE);
PRIMITIVE_TYPES.put(Float.class, Float.TYPE);
PRIMITIVE_TYPES.put(Integer.class, Integer.TYPE);
PRIMITIVE_TYPES.put(Long.class, Long.TYPE);
PRIMITIVE_TYPES.put(Short.class, Short.TYPE);
}
public static final String DOT = ".";
@Override
public String getName() {
return DOT;
}
@Override
public Object call(FelNode node, FelContext context) {
List<FelNode> children = node.getChildren();
Object left = children.get(0);
if (left instanceof Expression) {
Expression exp = (Expression) left;
left = exp.eval(context);
}
FelNode right = children.get(1);
FelNode exp = right;
Class<?>[] argsType = new Class<?>[0];
Object[] args = CommonFunction.evalArgs(right, context);
if (!ArrayUtils.isEmpty(args)) {
argsType = new Class[args.length];
for (int i = 0; i < args.length; i++) {
if (args[i] == null) {
argsType[i] = Null.class;
continue;
}
argsType[i] = args[i].getClass();
}
}
Method method = null;
Class<?> cls = left instanceof Class<?> ? (Class<?>) left : left.getClass();
String methodName = right.getText();
method = findMethod(cls, methodName, argsType);
if (method == null) {
String getMethod = "get";
method = findMethod(cls, getMethod, new Class<?>[] { String.class });
args = new Object[] { exp.getText() };
}
if (method != null) return invoke(left, method, args);
return null;
}
private Method findMethod(Class<?> cls, String methodName, Class<?>[] argsType) {
Method method = ReflectUtil.findMethod(cls, methodName, argsType);
return getCallableMethod(method);
}
private Method getMethod(Class<?> cls, String methodName, Class<?>[] argsType) {
Method method = ReflectUtil.getMethod(cls, methodName, argsType);
return getCallableMethod(method);
}
private Method getCallableMethod(Method m) {
if (m == null || securityMgr.isCallable(m)) return m;
throw new SecurityException("安全管理器[" + securityMgr.getClass().getSimpleName() + "]禁止调用方法[" + m.toString() + "]");
}
/**
* 调用方法
*
* @param obj
* @param method
* @param args
* @return
*/
public static Object invoke(Object obj, Method method, Object[] args) {
try {
return method.invoke(obj, args);
} catch (IllegalArgumentException | IllegalAccessException e) {
logger.error("", e);
} catch (InvocationTargetException e) {
logger.error("", e.getTargetException());
}
return null;
}
@Override
public FelMethod toMethod(FelNode node, FelContext context) {
StringBuilder sb = new StringBuilder();
List<FelNode> children = node.getChildren();
FelNode l = children.get(0);
SourceBuilder leftMethod = l.toMethod(context);
Class<?> cls = leftMethod.returnType(context, l);
String leftSrc = leftMethod.source(context, l);
if (cls.isPrimitive()) {
Class<?> wrapperClass = ReflectUtil.toWrapperClass(cls);
// 如果左边返回的值的基本类型,要转成包装类型[eg:((Integer)1).doubleValue()]
sb.append("((").append(wrapperClass.getSimpleName()).append(")").append(leftSrc).append(")");
} else {
sb.append(leftSrc);
}
sb.append(".");
Method method = null;
FelNode rightNode = children.get(1);
List<FelNode> params = rightNode.getChildren();
List<SourceBuilder> paramMethods = new ArrayList<SourceBuilder>();
Class<?>[] paramValueTypes = null;
boolean hasParam = params != null && !params.isEmpty();
String rightMethod = rightNode.getText();
String rightMethodParam = "";
if (hasParam) {
// 有参数
paramValueTypes = new Class<?>[params.size()];
for (int i = 0; i < params.size(); i++) {
FelNode p = params.get(i);
SourceBuilder paramMethod = p.toMethod(context);
paramMethods.add(paramMethod);
paramValueTypes[i] = paramMethod.returnType(context, p);
}
// 根据参数查找方法
method = findMethod(cls, rightNode.getText(), paramValueTypes);
if (method != null) {
Class<?>[] paramTypes = method.getParameterTypes();
for (int i = 0; i < paramTypes.length; i++) {
Class<?> paramType = paramTypes[i];
FelNode p = params.get(i);
String paramCode = getParamCode(paramType, p, context);
rightMethodParam += paramCode + ",";
}
rightMethod = method.getName();
}
} else {
method = findMethod(cls, rightNode.getText(), new Class<?>[0]);
if (method == null) {
// 当没有找到方法 ,直接使用get方法来获取属性
method = getMethod(cls, "get", new Class<?>[] { String.class });
if (method != null) {
rightMethod = "get";
rightMethodParam = "\"" + rightNode.getText() + "\"";
}
} else {
rightMethod = method.getName();
}
}
if (method != null) {}
if (rightMethodParam.endsWith(",")) {
rightMethodParam = rightMethodParam.substring(0, rightMethodParam.length() - 1);
}
rightMethod += "(" + rightMethodParam + ")";
sb.append(rightMethod);
FelMethod returnMe = new FelMethod(method == null ? null : method.getReturnType(), sb.toString());
return returnMe;
}
/**
* 获取参数代码
*
* @param paramType
* 方法声明的参数类型
* @param paramValueType
* 参数值的类型
* @param paramMethod
* @return
*/
public static String getParamCode(Class<?> paramType, FelNode node, FelContext ctx) {
// 如果类型相等(包装类型与基本类型(int和Integer)也认为是相等 ),直接添加参数。
String paramCode = "";
SourceBuilder paramMethod = node.toMethod(ctx);
Class<?> paramValueType = paramMethod.returnType(ctx, node);
if (ReflectUtil.isTypeMatch(paramType, paramValueType)) {
paramCode = paramMethod.source(ctx, node);
} else {
// 如果类型不匹配,使用强制转型
String className = null;
Class<?> wrapperClass = ReflectUtil.toWrapperClass(paramType);
if (wrapperClass != null) {
className = wrapperClass.getName();
} else {
className = paramType.getName();
}
paramCode = "(" + className + ")" + paramMethod.source(ctx, node);
}
return paramCode;
}
}
| zbutfly/albacore | expr-fel-import/src/main/java/com/greenpineyu/fel/function/operator/Dot.java | Java | gpl-2.0 | 7,449 |
/* *****************************************************************************
* The method lives() is based on Xitari's code, from Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* *****************************************************************************
* A.L.E (Arcade Learning Environment)
* Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and
* the Reinforcement Learning and Artificial Intelligence Laboratory
* Released under the GNU General Public License; see License.txt for details.
*
* Based on: Stella -- "An Atari 2600 VCS Emulator"
* Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team
*
* *****************************************************************************
*/
#include "games/supported/ChopperCommand.hpp"
#include "games/RomUtils.hpp"
namespace ale {
using namespace stella;
ChopperCommandSettings::ChopperCommandSettings() { reset(); }
/* create a new instance of the rom */
RomSettings* ChopperCommandSettings::clone() const {
return new ChopperCommandSettings(*this);
}
/* process the latest information from ALE */
void ChopperCommandSettings::step(const System& system) {
// update the reward
reward_t score = getDecimalScore(0xEE, 0xEC, &system);
score *= 100;
m_reward = score - m_score;
m_score = score;
// update terminal status
m_lives = readRam(&system, 0xE4) & 0xF;
m_terminal = (m_lives == 0);
/*
* Memory address 0xC2 indicates whether the Chopper is pointed
* left or right on the screen.
* - If the value is 0x00 we're looking left.
* - If the value ix 0x01 we are looking right.
* At the beginning of the game when we're selecting the game mode
* we are always facing left, therefore, 0xC2 == 0x00.
* When the game starts the chopper is initialized facing
* right, i.e., 0xC2 == 0x01. We know if the game has started
* if at any point 0xC2 == 0x01 so we can just OR the LSB of 0xC2
* to keep track of whether the game has started or not.
*
* */
m_is_started |= readRam(&system, 0xC2) & 0x1;
}
/* is end of game */
bool ChopperCommandSettings::isTerminal() const {
return (m_is_started && m_terminal);
};
/* get the most recently observed reward */
reward_t ChopperCommandSettings::getReward() const { return m_reward; }
/* is an action part of the minimal set? */
bool ChopperCommandSettings::isMinimal(const Action& a) const {
switch (a) {
case PLAYER_A_NOOP:
case PLAYER_A_FIRE:
case PLAYER_A_UP:
case PLAYER_A_RIGHT:
case PLAYER_A_LEFT:
case PLAYER_A_DOWN:
case PLAYER_A_UPRIGHT:
case PLAYER_A_UPLEFT:
case PLAYER_A_DOWNRIGHT:
case PLAYER_A_DOWNLEFT:
case PLAYER_A_UPFIRE:
case PLAYER_A_RIGHTFIRE:
case PLAYER_A_LEFTFIRE:
case PLAYER_A_DOWNFIRE:
case PLAYER_A_UPRIGHTFIRE:
case PLAYER_A_UPLEFTFIRE:
case PLAYER_A_DOWNRIGHTFIRE:
case PLAYER_A_DOWNLEFTFIRE:
return true;
default:
return false;
}
}
/* reset the state of the game */
void ChopperCommandSettings::reset() {
m_reward = 0;
m_score = 0;
m_terminal = false;
m_lives = 3;
m_is_started = false;
}
/* saves the state of the rom settings */
void ChopperCommandSettings::saveState(Serializer& ser) {
ser.putInt(m_reward);
ser.putInt(m_score);
ser.putBool(m_terminal);
ser.putInt(m_lives);
}
// loads the state of the rom settings
void ChopperCommandSettings::loadState(Deserializer& ser) {
m_reward = ser.getInt();
m_score = ser.getInt();
m_terminal = ser.getBool();
m_lives = ser.getInt();
}
// returns a list of mode that the game can be played in
ModeVect ChopperCommandSettings::getAvailableModes() {
return {0, 2};
}
// set the mode of the game
// the given mode must be one returned by the previous function
void ChopperCommandSettings::setMode(
game_mode_t m, System& system,
std::unique_ptr<StellaEnvironmentWrapper> environment) {
if (m == 0 || m == 2) {
// read the mode we are currently in
unsigned char mode = readRam(&system, 0xE0);
// press select until the correct mode is reached
while (mode != m) {
environment->pressSelect(2);
mode = readRam(&system, 0xE0);
}
//reset the environment to apply changes.
environment->softReset();
} else {
throw std::runtime_error("This mode doesn't currently exist for this game");
}
}
DifficultyVect ChopperCommandSettings::getAvailableDifficulties() {
return {0, 1};
}
} // namespace ale
| mgbellemare/Arcade-Learning-Environment | src/games/supported/ChopperCommand.cpp | C++ | gpl-2.0 | 5,077 |
package gui;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import logic.DB.MongoUserManager;
import logic.model.Statistics;
import logic.model.User;
import javax.swing.JLabel;
import java.awt.Font;
import java.awt.Toolkit;
public class ListPlayers extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
private JPanel contentPane;
private JScrollPane spUsers;
private JTable tabUsers;
private MongoUserManager mongo = new MongoUserManager();
private List<User> users;
private JButton btnClose;
private JLabel lbListUsers;
/**
* Launch the application.
*/
/*public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
ListPlayers frame = new ListPlayers();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}*/
/**
* Create the frame.
*/
public ListPlayers() {
setIconImage(Toolkit.getDefaultToolkit().getImage("C:\\Users\\Raquel\\Desktop\\ASWProject\\Trivial_i1b\\Game\\src\\main\\resources\\Images\\icono.png"));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 532, 340);
contentPane = new JPanel();
contentPane.setBackground(new Color(0,0,139));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
contentPane.add(getSpUsers());
contentPane.add(getBtnClose());
contentPane.setBackground(InitialWindow.pnFondo.getBackground());
JButton btnSeeStatistics = new JButton("See statistics");
btnSeeStatistics.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
users = mongo.getAllUsers();
StatisticsWindow statistics = new StatisticsWindow();
statistics.setVisible(true);
statistics.txPlayer.setText((String) tabUsers.getValueAt(tabUsers.getSelectedRow(), 0));
int row = tabUsers.getSelectedRow();
int newRow = 0;
for (User u : users){
if (u.getEmail().equals(tabUsers.getValueAt(row, 1))){
Statistics s = u.getStatistics();
statistics.tabStatistics.setValueAt(s.getQuestionsMatched(), newRow, 0);
statistics.tabStatistics.setValueAt(s.getQuestionsAnswered(), newRow, 1);
statistics.tabStatistics.setValueAt(s.getTimesPlayed(), newRow, 2);
newRow++;
}
}
}
});
btnSeeStatistics.setBounds(357, 42, 123, 23);
contentPane.add(btnSeeStatistics);
contentPane.add(getLbListUsers());
}
private JScrollPane getSpUsers() {
if (spUsers == null) {
spUsers = new JScrollPane();
spUsers.setBounds(42, 103, 306, 128);
spUsers.setViewportView(getTabUsers());
spUsers.setBackground(InitialWindow.pnFondo.getBackground());
}
return spUsers;
}
private JTable getTabUsers() {
if (tabUsers == null) {
tabUsers = new JTable();
tabUsers.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
tabUsers.setModel(new DefaultTableModel(
new Object[][] {
},
new String[] {
"Username", "Email"
}
));
}
DefaultTableModel model = (DefaultTableModel)tabUsers.getModel();
listUsers(model);
return tabUsers;
}
private JButton getBtnClose() {
if (btnClose == null) {
btnClose = new JButton("Close");
btnClose.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
dispose();
}
});
btnClose.setBounds(378, 230, 76, 23);
}
return btnClose;
}
private void listUsers(DefaultTableModel model) {
users = mongo.getAllUsers();
Object[] row = new Object[2];
for (int i = 0; i < users.size(); i++) {
row[0] = users.get(i).getUsername();
row[1] = users.get(i).getEmail();
model.addRow(row);
}
}
private JLabel getLbListUsers() {
if (lbListUsers == null) {
lbListUsers = new JLabel("List of users:");
lbListUsers.setFont(new Font("Arial", Font.PLAIN, 25));
lbListUsers.setBounds(142, 32, 195, 32);
}
return lbListUsers;
}
}
| Arquisoft/Trivial_i1b | Game/src/main/java/gui/ListPlayers.java | Java | gpl-2.0 | 4,299 |
package sabstracta;
/**
* Represents an or operation in the syntax tree.
*
*/
public class Or extends ExpresionBinariaLogica {
public Or(Expresion _izq, Expresion _dch) {
super(_izq, _dch);
}
/**
* Returns the instruction code.
*/
@Override
protected String getInst() {
return "or";
}
}
| igofunke/LPM | src/sabstracta/Or.java | Java | gpl-2.0 | 325 |
<?php
/**
* @package JFBConnect
* @copyright (c) 2009-2015 by SourceCoast - All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
* @version Release v7.1.1
* @build-date 2016/11/18
*/
defined('JPATH_PLATFORM') or die;
jimport('joomla.form.helper');
class JFormFieldProviderloginbutton extends JFormField
{
protected function getInput()
{
$html = array();
$provider = $this->element['provider'] ? (string)$this->element['provider'] : null;
$style = $this->element['style'] ? (string)$this->element['style'] . '"' : '';
// Initialize some field attributes.
$class = !empty($this->class) ? ' class="radio ' . $this->class . '"' : ' class="radio"';
$required = $this->required ? ' required aria-required="true"' : '';
$autofocus = $this->autofocus ? ' autofocus' : '';
$disabled = $this->disabled ? ' disabled' : '';
$readonly = $this->readonly;
$style = 'style="float:left;' . $style . '"';
$html[] = '<div style="clear: both"> </div>';
// Start the radio field output.
$html[] = '<fieldset id="' . $this->id . '"' . $class . $required . $autofocus . $disabled . $style . ' >';
// Get the field options.
$options = $this->getOptions();
$p = JFBCFactory::provider($provider);
// Build the radio field output.
$html[] = '<label class="providername">' . $p->name . '</label>';
foreach ($options as $i => $option)
{
// Initialize some option attributes.
$checked = ((string)$option->value == (string)$this->value) ? ' checked="checked"' : '';
$class = !empty($option->class) ? ' class="' . $option->class . '"' : '';
$disabled = !empty($option->disable) || ($readonly && !$checked);
$disabled = $disabled ? ' disabled' : '';
$html[] = '<input type="radio" id="' . $this->id . $i . '" name="' . $this->name . '" value="'
. htmlspecialchars($option->value, ENT_COMPAT, 'UTF-8') . '"' . $checked . $class . $required . $disabled . ' />';
$html[] = '<label for="' . $this->id . $i . '"' . $class . ' >' .
'<img src="' . JUri::root() . 'media/sourcecoast/images/provider/' . $provider . '/' . $option->value . '" />' .
#. JText::alt($option->text, preg_replace('/[^a-zA-Z0-9_\-]/', '_', $this->fieldname)) . '</label>'
'</label>' .
$required = '';
}
// End the radio field output.
$html[] = '</fieldset>';
$html[] = '<div style="clear: both"> </div>';
return implode($html);
}
protected function getOptions()
{
// Scan the /media/sourcecoast/images/provider directory for this provider's buttons
// Merge in any custom images from ??
$provider = $this->element['provider'] ? (string)$this->element['provider'] : null;
$options = array();
$buttons = $this->getButtons('/media/sourcecoast/images/provider/' . $provider);
if ($buttons)
{
foreach ($buttons as $button)
{
$options[] = JHtml::_('select.option', $button, $button, 'value', 'text', false);
}
}
reset($options);
return $options;
}
private function getButtons($folder)
{
$folder = JPATH_SITE . $folder;
$buttons = array();
if (JFolder::exists($folder))
{
$buttons = JFolder::files($folder, '^' . '.*(\.png|\.jpg|\.gif)$');
}
return $buttons;
}
}
| Creativetech-Solutions/joomla-easysocial-network | administrator/components/com_jfbconnect/models/fields/providerloginbutton.php | PHP | gpl-2.0 | 3,688 |
package org.oguz.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class XMLServlet extends HttpServlet
{
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String fullName = request.getParameter("fullname");
String profession = request.getParameter("profession");
// HttpSession session =request.getSession();
ServletContext context = request.getServletContext();
if (userName != "" && userName != null)
{
// session.setAttribute("savedUser",userName);
context.setAttribute("savedUser", userName);
out.println("<p>Hello context parameter " + (String)context.getAttribute("savedUser") +
" from GET method</p>");
}
else
{
out.println("<p>Hello default user " +
this.getServletConfig().getInitParameter("username") + " from GET method</p>");
}
if (fullName != "" && fullName != null)
{
// session.setAttribute("savedFull", fullName);
context.setAttribute("savedFull", fullName);
out.println("<p> your full name is: " + (String)context.getAttribute("savedFull") +
"</p>");
}
else
{
out.println("<p>Hello default fullname " +
this.getServletConfig().getInitParameter("fullname") + " from GET method</p>");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("username");
String fullName = request.getParameter("fullname");
String profession = request.getParameter("profession");
// String location = request.getParameter("location");
String[] location = request.getParameterValues("location");
out.println("<p>Hello " + userName + " from POST method in XMLSERVLET response</p>");
out.println("<p> your full name is: " + fullName + "</p>");
out.println("<p>your profession is: " + profession + "</p>");
for (int i = 0; i < location.length; i++)
{
out.println("<p>your location is: " + location[i].toUpperCase() + "</p>");
}
}
}
| ogz00/Servlet-SimpleServletProject | src/org/oguz/servlet/XMLServlet.java | Java | gpl-2.0 | 2,759 |
package fr.npellegrin.xebia.mower.parser.model;
/**
* Parsed position.
*/
public class PositionDefinition {
private int x;
private int y;
private OrientationDefinition orientation;
public int getX() {
return x;
}
public void setX(final int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(final int y) {
this.y = y;
}
public OrientationDefinition getOrientation() {
return orientation;
}
public void setOrientation(final OrientationDefinition orientation) {
this.orientation = orientation;
}
}
| npellegrin/MowItNow | src/main/java/fr/npellegrin/xebia/mower/parser/model/PositionDefinition.java | Java | gpl-2.0 | 550 |
#!/usr/bin/env python3
import sys
import numpy as np
from spc import SPC
import matplotlib.pyplot as plt
def plot(files, fac=1.0):
for f in files:
if f.split('.')[-1] == 'xy':
td = np.loadtxt(f)
plt.plot(td[:, 0], np.log(1. / td[:, 1]) * fac, label=f)
elif f.split('.')[-1] == 'spc':
td = SPC(f)
plt.plot(td.xdata, np.log(1. / np.array(td.ydata)), label=f)
plt.legend()
plt.show()
if __name__ == '__main__':
files = sys.argv[2:]
fac = float(sys.argv[1])
plot(files, fac)
| JHeimdal/HalIR | Test/plotf.py | Python | gpl-2.0 | 564 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\CanonVRD;
use PHPExiftool\Driver\AbstractTag;
class LandscapeRawContrast extends AbstractTag
{
protected $Id = 33;
protected $Name = 'LandscapeRawContrast';
protected $FullName = 'CanonVRD::Ver2';
protected $GroupName = 'CanonVRD';
protected $g0 = 'CanonVRD';
protected $g1 = 'CanonVRD';
protected $g2 = 'Image';
protected $Type = 'int16s';
protected $Writable = true;
protected $Description = 'Landscape Raw Contrast';
}
| Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/CanonVRD/LandscapeRawContrast.php | PHP | gpl-2.0 | 739 |
/****************************************************************************
**
** This file is part of the Qtopia Opensource Edition Package.
**
** Copyright (C) 2008 Trolltech ASA.
**
** Contact: Qt Extended Information (info@qtextended.org)
**
** This file may be used under the terms of the GNU General Public License
** versions 2.0 as published by the Free Software Foundation and appearing
** in the file LICENSE.GPL included in the packaging of this file.
**
** Please review the following information to ensure GNU General Public
** Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html.
**
**
****************************************************************************/
#include <qtopia/private/qmimetypedata_p.h>
#include <qtopia/private/drmcontent_p.h>
#include <QApplication>
#include <QtDebug>
Q_GLOBAL_STATIC_WITH_ARGS(QIcon,unknownDocumentIcon,(QLatin1String(":image/qpe/UnknownDocument")));
Q_GLOBAL_STATIC_WITH_ARGS(QIcon,validDrmUnknownDocumentIcon,(DrmContentPrivate::createIcon(
*unknownDocumentIcon(),
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
true )));
Q_GLOBAL_STATIC_WITH_ARGS(QIcon,invalidDrmUnknownDocumentIcon,(DrmContentPrivate::createIcon(
*unknownDocumentIcon(),
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
false )));
class QMimeTypeDataPrivate : public QSharedData
{
public:
struct AppData
{
QContent application;
QString iconFile;
QIcon icon;
QIcon validDrmIcon;
QIcon invalidDrmIcon;
QDrmRights::Permission permission;
bool iconLoaded;
bool validDrmIconLoaded;
bool invalidDrmIconLoaded;
};
QMimeTypeDataPrivate()
{
}
~QMimeTypeDataPrivate()
{
qDeleteAll( applicationData.values() );
}
QString id;
QContentList applications;
QContent defaultApplication;
QMap< QContentId, AppData * > applicationData;
void loadIcon( AppData *data ) const;
void loadValidDrmIcon( AppData *data ) const;
void loadInvalidDrmIcon( AppData *data ) const;
};
void QMimeTypeDataPrivate::loadIcon( AppData *data ) const
{
if( !data->iconFile.isEmpty() )
data->icon = QIcon( QLatin1String( ":icon/" ) + data->iconFile );
data->iconLoaded = true;
}
void QMimeTypeDataPrivate::loadValidDrmIcon( AppData *data ) const
{
if( !data->icon.isNull() )
data->validDrmIcon = DrmContentPrivate::createIcon(
data->icon,
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
true );
data->validDrmIconLoaded = true;
}
void QMimeTypeDataPrivate::loadInvalidDrmIcon( AppData *data ) const
{
if( !data->icon.isNull() )
data->invalidDrmIcon = DrmContentPrivate::createIcon(
data->icon,
qApp->style()->pixelMetric( QStyle::PM_ListViewIconSize ),
qApp->style()->pixelMetric( QStyle::PM_LargeIconSize ),
false );
data->invalidDrmIconLoaded = true;
}
Q_GLOBAL_STATIC_WITH_ARGS(QSharedDataPointer<QMimeTypeDataPrivate>,nullQMimeTypeDataPrivate,(new QMimeTypeDataPrivate));
QMimeTypeData::QMimeTypeData()
{
d = *nullQMimeTypeDataPrivate();
}
QMimeTypeData::QMimeTypeData( const QString &id )
{
if( !id.isEmpty() )
{
d = new QMimeTypeDataPrivate;
d->id = id;
}
else
d = *nullQMimeTypeDataPrivate();
}
QMimeTypeData::QMimeTypeData( const QMimeTypeData &other )
: d( other.d )
{
}
QMimeTypeData::~QMimeTypeData()
{
}
QMimeTypeData &QMimeTypeData::operator =( const QMimeTypeData &other )
{
d = other.d;
return *this;
}
bool QMimeTypeData::operator ==( const QMimeTypeData &other )
{
return d->id == other.d->id;
}
QString QMimeTypeData::id() const
{
return d->id;
}
QContentList QMimeTypeData::applications() const
{
return d->applications;
}
QContent QMimeTypeData::defaultApplication() const
{
return d->defaultApplication;
}
QIcon QMimeTypeData::icon( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
if( !data->iconLoaded )
d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
return !data->icon.isNull() ? data->icon : data->application.icon();
}
else
return *unknownDocumentIcon();
}
QIcon QMimeTypeData::validDrmIcon( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
if( !data->iconLoaded )
d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
if( !data->validDrmIconLoaded )
d->loadValidDrmIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
return !data->validDrmIcon.isNull() ? data->validDrmIcon : data->application.icon();
}
else
return *validDrmUnknownDocumentIcon();
}
QIcon QMimeTypeData::invalidDrmIcon( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
if( !data->iconLoaded )
d->loadIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
if( !data->invalidDrmIconLoaded )
d->loadInvalidDrmIcon( const_cast< QMimeTypeDataPrivate::AppData * >( data ) );
return !data->invalidDrmIcon.isNull() ? data->invalidDrmIcon : data->application.icon();
}
else
return *invalidDrmUnknownDocumentIcon();
}
QDrmRights::Permission QMimeTypeData::permission( const QContent &application ) const
{
if( d->applicationData.contains( application.id() ) )
{
const QMimeTypeDataPrivate::AppData *data = d->applicationData.value( application.id() );
return data->permission;
}
else
return QDrmRights::Unrestricted;
}
void QMimeTypeData::addApplication( const QContent &application, const QString &iconFile, QDrmRights::Permission permission )
{
if( application.id() != QContent::InvalidId && !d->applicationData.contains( application.id() ) )
{
QMimeTypeDataPrivate::AppData *data = new QMimeTypeDataPrivate::AppData;
data->application = application;
data->iconFile = iconFile;
data->permission = permission;
data->iconLoaded = false;
data->validDrmIconLoaded = false;
data->invalidDrmIconLoaded = false;
d->applicationData.insert( application.id(), data );
d->applications.append( application );
if(d->defaultApplication.id() == QContent::InvalidId)
setDefaultApplication(application);
}
}
void QMimeTypeData::removeApplication( const QContent &application )
{
if(d->applicationData.contains( application.id() ))
{
delete d->applicationData.take(application.id());
d->applications.removeAll(application);
}
}
void QMimeTypeData::setDefaultApplication( const QContent &application )
{
if(application.id() != QContent::InvalidId)
d->defaultApplication = application;
}
template <typename Stream> void QMimeTypeData::serialize(Stream &stream) const
{
stream << d->id;
stream << d->defaultApplication.id();
stream << d->applicationData.count();
QList< QContentId > keys = d->applicationData.keys();
foreach( QContentId contentId, keys )
{
QMimeTypeDataPrivate::AppData *data = d->applicationData.value( contentId );
stream << contentId;
stream << data->iconFile;
stream << data->permission;
}
}
template <typename Stream> void QMimeTypeData::deserialize(Stream &stream)
{
qDeleteAll( d->applicationData.values() );
d->applicationData.clear();
stream >> d->id;
{
QContentId contentId;
stream >> contentId;
d->defaultApplication = QContent( contentId );
}
int count;
stream >> count;
for( int i = 0; i < count; i++ )
{
QContentId contentId;
QString iconFile;
QDrmRights::Permission permission;
stream >> contentId;
stream >> iconFile;
stream >> permission;
addApplication( QContent( contentId ), iconFile, permission );
}
}
Q_IMPLEMENT_USER_METATYPE(QMimeTypeData);
| muromec/qtopia-ezx | src/libraries/qtopia/qmimetypedata.cpp | C++ | gpl-2.0 | 8,816 |
package org.iproduct.iptpi.domain.movement;
import static java.lang.Math.PI;
import static java.lang.Math.abs;
import static java.lang.Math.atan;
import static java.lang.Math.cbrt;
import static java.lang.Math.cos;
import static java.lang.Math.hypot;
import static java.lang.Math.min;
import static java.lang.Math.pow;
import static java.lang.Math.signum;
import static java.lang.Math.sin;
import static java.lang.Math.sqrt;
import static java.lang.Math.tan;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAIN_AXE_LENGTH;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_ANGULAR_ACCELERATION;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_LINEAR_ACCELERATION;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.MAX_ROBOT_LINEAR_VELOCITY;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.ROBOT_STOPPING_DECCELERATION;
import static org.iproduct.iptpi.demo.robot.RobotParametrs.WHEEL_RADIUS;
import static org.iproduct.iptpi.domain.CommandName.STOP;
import static org.iproduct.iptpi.domain.CommandName.VOID;
import org.iproduct.iptpi.domain.Command;
import org.iproduct.iptpi.domain.arduino.LineReadings;
import org.iproduct.iptpi.domain.audio.AudioPlayer;
import org.iproduct.iptpi.domain.position.Position;
import org.iproduct.iptpi.domain.position.PositionsFlux;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import com.pi4j.wiringpi.Gpio;
import reactor.core.publisher.EmitterProcessor;
import reactor.core.publisher.Flux;
import reactor.util.function.Tuple2;
import reactor.util.function.Tuple3;
import reactor.util.function.Tuple4;
import reactor.util.function.Tuples;
public class MovementCommandSubscriber implements Subscriber<Command> {
public static final int MAX_SPEED = 1024;
public static final int CLOCK_DIVISOR = 2;
public static final double LANDING_CURVE_PARAMETER = 0.000000005;
public static final MotorsCommand STOP_COMMAND = new MotorsCommand(0, 0, 0, 0, 0);
private Subscription subscription;
private PositionsFlux positions;
private Flux<LineReadings> lineReadings;
// private SchedulerGroup eventLoops = SchedulerGroup.async();
//Create movement command broadcaster
private EmitterProcessor<Command> commandFlux = EmitterProcessor.create();
public MovementCommandSubscriber(PositionsFlux positions, Flux<LineReadings> lineReadings) {
this.positions = positions;
this.lineReadings = lineReadings;
}
@Override
public void onNext(Command command) {
setupGpioForMovement();
switch (command.getName()) {
case MOVE_FORWARD : moveForward(command); break;
case FOLLOW_LINE : followLine(command); break;
case MOVE_RELATIVE : moveRelative(command); break;
case STOP :
System.out.println("STOPPING THE ROBOT");
runMotors(STOP_COMMAND);
break;
default:
break;
}
}
protected void moveRelative(Command command) {
RelativeMovement relMove = (RelativeMovement) command.getData();
// start moving - and think later as it comes :)
int directionL, directionR;
if(relMove.getVelocity() < 0) {
directionL = directionR = -1;
} else {
directionL = directionR = 1;
}
double targetVelocity = abs(relMove.getVelocity());
int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max
MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown
System.out.println(initialCommand);
runMotors(initialCommand);
Position startPos = positions.elementAt(1).block();
double targetDeltaX = relMove.getDeltaX();
double targetDeltaY = relMove.getDeltaY();
double targetX = startPos.getX() + targetDeltaX;
double targetY = startPos.getY() + targetDeltaY;
double distance = hypot(targetDeltaX, targetDeltaY);
System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX );
System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY );
System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance);
double targetHeading, targetDeltaHeading, targetCurvature, h = 0;
if(relMove.getDeltaHeading() == 0 ) {
targetCurvature = targetDeltaHeading = 0;
targetHeading = startPos.getHeading();
} else {
targetDeltaHeading = relMove.getDeltaHeading();
targetHeading = startPos.getHeading() + targetDeltaHeading ;
targetCurvature = (2 * sin(targetDeltaHeading / 2) ) / distance ;
h = sqrt( 1/(targetCurvature * targetCurvature) - 0.25 * distance * distance );
}
double xC, yC; //circle center coordinates
double r = hypot(distance/2, h);
if(targetCurvature != 0) {
double q = hypot( targetX - startPos.getX(), targetY - startPos.getY() ),
x3 = (targetX + startPos.getX()) /2,
y3 = (targetY + startPos.getY()) /2;
if(targetCurvature > 0) {
xC = x3 + sqrt(r*r - (q*q/4)) * (startPos.getY() - targetY)/q;
yC = y3 + sqrt(r*r - (q*q/4)) * (targetX - startPos.getX() )/q;
} else {
xC = x3 - sqrt(r*r - (q*q/4)) * (startPos.getY() - targetY)/q;
yC = y3 - sqrt(r*r - (q*q/4)) * (targetX - startPos.getX() )/q;
}
} else {
xC = (targetX + startPos.getX()) /2;
yC = (targetY + startPos.getY()) /2;
}
System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading );
System.out.println("$$$$$$$$$$$$$$ TargetCurvature=" + targetCurvature );
double targetAngularVelocity;
if (targetDeltaHeading != 0 && relMove.getAngularVelocity() == 0)
targetAngularVelocity = targetVelocity * targetCurvature;
else
targetAngularVelocity = relMove.getAngularVelocity();
double startH = startPos.getHeading();
System.out.println("START POSITION: " + startPos);
Flux<Position> skip1 = positions.skip(1);
Flux.zip(positions, skip1)
.scan(initialCommand, (last, tupple) -> {
Position prevPos = ((Position)tupple.getT1());
Position currPos = ((Position)tupple.getT2());
float prevX = prevPos.getX();
float prevY = prevPos.getY();
double prevH = prevPos.getHeading();
float currX = currPos.getX();
float currY = currPos.getY();
double currH = currPos.getHeading();
System.out.println(currPos + " - " + prevPos);
double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings
if(dt <= 0) return last; // if invalid sequence do nothing
double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0;
// calculating the ideal trajectory position
double tarX, tarY, tarH, remainingPathLength;
if(targetCurvature == 0) {
tarX = startPos.getX() + targetVelocity * time * cos(targetHeading);
tarY = startPos.getY() + targetVelocity * time * sin(targetHeading);
remainingPathLength = hypot(targetX - currX, targetY - currY) ;
tarH = targetHeading;
} else {
double deltaHeading = targetAngularVelocity * time;
double startAng = atan((startPos.getY() - yC) / (startPos.getX() - xC));
double angle = startAng + deltaHeading;
if(signum(angle) != (startPos.getY() - yC))
angle -= PI;
tarX = cos(angle) * r + xC;
tarY = sin(angle) * r + yC;
tarH = startPos.getHeading() + deltaHeading;
remainingPathLength = (targetDeltaHeading - deltaHeading ) / targetCurvature;
// System.out.println(" -----> tarX=" + tarX + ", tarY=" + tarY + ", tarH=" + tarH + ", deltaHeading=" + deltaHeading + ", startAng=" + startAng + ", angle=" + angle);
// System.out.println(" -----> r=" + r + ", xC=" + xC + ", yC=" + yC );
}
//calculating current trajectory parameters
float dX = currX - prevX;
float dY = currY - prevY;
double currDist = hypot(dX, dY);
double currV = currDist / dt; // current velocity [mm/s]
double currAngV = (currH - prevH) / dt;
//calculating errors
double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH);
double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH);
double errH = tarH - currH;
//calculating landing curve
double Cx = LANDING_CURVE_PARAMETER;
double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY);
double landH = tarH + atan(dlandY);
double dErrY = -targetAngularVelocity * errX + currV * sin (errH);
double landAngV = targetAngularVelocity + (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) /
(1 + tan(landH - tarH) * tan(landH - tarH));
//calculating the corrected trajectory control parameters
double switchAngV = landAngV - currAngV +
sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH))
* signum(landH - currH) * 0.2;
double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV);
double newAngV = currAngV + switchAngA * dt;
//calculating new velocity
double dErrX = targetVelocity - currV * cos(errH) + targetAngularVelocity * errY;
double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX);
double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV);
//calculating delta motor speed control values
double k = 0.1;
double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS);
//calculating new motor speed control values
int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL());
int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL());
System.out.println("--> errH=" + errH + ", targetHeading=" + targetHeading + ", currH=" + currH + ", dist=" + currDist
);
// System.out.println("!!! landH=" + landH + ", dErrY=" + dErrY
// + ", currAngV=" + currAngV + ", landAngV=" + landAngV + ", switchAngV=" + switchAngV
// + ", switchAngA=" + switchAngA + ", newAngV=" + newAngV );
// System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA );
// System.out.println("!!! newDeltaV=" + switchA * dt / WHEEL_RADIUS + ", newDelatLR=" + newDeltaLR + ", newVL=" + newVL + ", newVR=" + newVR);
double remainingDeltaHeading = targetHeading - currH;
if(remainingPathLength < last.getRemainingPath()
&& remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION
|| targetDeltaHeading > 0.01
&& abs(remainingDeltaHeading) > 0.05 && remainingDeltaHeading * targetDeltaHeading > 0 ) { //drive until minimum distance to target
return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength);
} else {
System.out.println("FINAL POSITION: " + currPos);
return STOP_COMMAND;
}
}).map((MotorsCommand motorsCommand) -> {
runMotors(motorsCommand);
return motorsCommand;
})
.takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) )
.subscribe( (MotorsCommand motorsCommand) -> {
System.out.println(motorsCommand);
});
}
protected void followLine(Command command) {
{
ForwardMovement forwardMove = (ForwardMovement) command.getData();
// start moving - and think later as it comes :)
int directionL, directionR;
if(forwardMove.getVelocity() < 0) {
directionL = directionR = -1;
} else {
directionL = directionR = 1;
}
double targetVelocity = abs(forwardMove.getVelocity());
int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max
MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown
System.out.println(initialCommand);
runMotors(initialCommand);
Position startPos = positions.elementAt(1).block();
double distance = forwardMove.getDistance();
double targetHeading = startPos.getHeading();
double targetDeltaX = distance * cos(targetHeading);
double targetDeltaY = distance * sin(targetHeading);
double targetX = startPos.getX() + targetDeltaX;
double targetY = startPos.getY() + targetDeltaY;
System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX );
System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY );
System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance);
System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading );
double startH = startPos.getHeading();
System.out.println("START POSITION: " + startPos);
Flux<Position> skip1 = positions.skip(1);
Flux<Tuple2<Position, Position>> lastTwoPositionsFlux = Flux.zip(positions, skip1);
Flux<Tuple4<Position, Position, LineReadings, Command>> flux =
Flux.combineLatest(
lastTwoPositionsFlux,
lineReadings,
commandFlux.startWith(new Command(VOID, null)),
(Object[] args) ->
Tuples.of(((Tuple2<Position, Position>)args[0]).getT1(),
((Tuple2<Position, Position>)args[0]).getT2(),
(LineReadings)args[1],
(Command)args[2])
);
flux.scan(initialCommand, (last, tuple4) -> {
System.out.println("########## NEW EVENT !!!!!!!!!!!");
Position prevPos = tuple4.getT1();
Position currPos = tuple4.getT2();
LineReadings lastReadings = tuple4.getT3();
Command lastCommand = tuple4.getT4();
float prevX = prevPos.getX();
float prevY = prevPos.getY();
double prevH = prevPos.getHeading();
float currX = currPos.getX();
float currY = currPos.getY();
double currH = currPos.getHeading();
System.out.println(currPos + " - " + prevPos);
double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings
if(dt <= 0) return last; // if invalid sequence do nothing
double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0;
// calculating the ideal trajectory position
double tarX, tarY, tarH, remainingPathLength;
tarX = startPos.getX() + targetVelocity * time * cos(targetHeading);
tarY = startPos.getY() + targetVelocity * time * sin(targetHeading);
remainingPathLength = hypot(targetX - currX, targetY - currY) ;
tarH = targetHeading;
//calculating current trajectory parameters
float dX = currX - prevX;
float dY = currY - prevY;
double currDist = hypot(dX, dY);
double currV = currDist / dt; // current velocity [mm/s]
double currAngV = (currH - prevH) / dt;
//calculating errors
double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH);
double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH);
double errH = tarH - currH;
//calculating landing curve
double Cx = LANDING_CURVE_PARAMETER;
double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY);
double landH = tarH + atan(dlandY);
double dErrY = currV * sin (errH);
double landAngV = (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) /
(1 + tan(landH - tarH) * tan(landH - tarH));
//calculating the corrected trajectory control parameters
double switchAngV = landAngV - currAngV +
sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH))
* signum(landH - currH) * 0.2;
double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV);
double newAngV = currAngV + switchAngA * dt;
//calculating new velocity
double dErrX = targetVelocity - currV * cos(errH);
double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX);
double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV);
// double newV = currV + switchA * dt;
//calculating delta motor speed control values
double k = 0.1;
double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS);
//calculating new motor speed control values
int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL());
int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL());
System.out.println("!!! time=" + time + ", dt=" + dt + ", tarX=" + tarX + ", tarY=" + tarY
+ ", startH=" + startH + ", errH=" + errH + ", targetX=" + targetX + ", targetY=" + targetY + ", targetHeading=" + targetHeading
+ ", errX=" + errX + ", errY=" + errY + ", dlandY=" + dlandY + ", currV=" + currV + ", dist=" + currDist
+ ", switchAngV/dt=" + switchAngV / dt );
System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA );
if(lastCommand.getName() != STOP && remainingPathLength < last.getRemainingPath()
&& remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION ) { //drive until minimum distance to target
return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength);
} else {
System.out.println("FINAL POSITION: " + currPos);
return STOP_COMMAND;
}
}).map((MotorsCommand motorsCommand) -> {
runMotors(motorsCommand);
return motorsCommand;
})
.takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) )
.subscribe( (MotorsCommand motorsCommand) -> {
System.out.println(motorsCommand);
});
}
}
protected void moveForward(Command command) {
{
ForwardMovement forwardMove = (ForwardMovement) command.getData();
// start moving - and think later as it comes :)
int directionL, directionR;
if(forwardMove.getVelocity() < 0) {
directionL = directionR = -1;
} else {
directionL = directionR = 1;
}
double targetVelocity = abs(forwardMove.getVelocity());
int velocity = (int)(MAX_SPEED * targetVelocity / MAX_ROBOT_LINEAR_VELOCITY); // 50 mm/s max
MotorsCommand initialCommand = new MotorsCommand(directionL, directionR, velocity, velocity, Long.MAX_VALUE); //distance still unknown
System.out.println(initialCommand);
runMotors(initialCommand);
Position startPos = positions.elementAt(1).block();
double distance = forwardMove.getDistance();
double targetHeading = startPos.getHeading();
double targetDeltaX = distance * cos(targetHeading);
double targetDeltaY = distance * sin(targetHeading);
double targetX = startPos.getX() + targetDeltaX;
double targetY = startPos.getY() + targetDeltaY;
System.out.println("$$$$$$$$$$$$$$ TargetX=" + targetX );
System.out.println("$$$$$$$$$$$$$$ TargetY=" + targetY );
System.out.println("$$$$$$$$$$$$$$ Target Distance=" + distance);
System.out.println("$$$$$$$$$$$$$$ TargetHeading=" + targetHeading );
double startH = startPos.getHeading();
System.out.println("START POSITION: " + startPos);
Flux<Position> skip1 = positions.skip(1);
Flux<Tuple2<Position, Position>> lastTwoPositionsFlux = Flux.zip(positions, skip1);
Flux<Tuple3<Position, Position, Command>> flux =
Flux.combineLatest(
lastTwoPositionsFlux,
commandFlux.startWith(new Command(VOID, null)),
(tuple2, lastCommand) -> Tuples.of(tuple2.getT1(), tuple2.getT2(), lastCommand)
);
flux.scan(initialCommand, (last, tuple3) -> {
System.out.println("########## NEW EVENT !!!!!!!!!!!");
Position prevPos = tuple3.getT1();
Position currPos = tuple3.getT2();
Command lastCommand = tuple3.getT3();
float prevX = prevPos.getX();
float prevY = prevPos.getY();
double prevH = prevPos.getHeading();
float currX = currPos.getX();
float currY = currPos.getY();
double currH = currPos.getHeading();
System.out.println(currPos + " - " + prevPos);
double dt = (currPos.getTimestamp() - prevPos.getTimestamp()) / 1000.0; //delta time in seconds between position redings
if(dt <= 0) return last; // if invalid sequence do nothing
double time = (currPos.getTimestamp() - startPos.getTimestamp()) /1000.0;
// calculating the ideal trajectory position
double tarX, tarY, tarH, remainingPathLength;
tarX = startPos.getX() + targetVelocity * time * cos(targetHeading);
tarY = startPos.getY() + targetVelocity * time * sin(targetHeading);
remainingPathLength = hypot(targetX - currX, targetY - currY) ;
tarH = targetHeading;
//calculating current trajectory parameters
float dX = currX - prevX;
float dY = currY - prevY;
double currDist = hypot(dX, dY);
double currV = currDist / dt; // current velocity [mm/s]
double currAngV = (currH - prevH) / dt;
//calculating errors
double errX = (tarX - currX) * cos(tarH) + (tarY - currY) + sin(tarH);
double errY = (tarX - currX) * sin(tarH) + (tarY - currY) + cos(tarH);
double errH = tarH - currH;
//calculating landing curve
double Cx = LANDING_CURVE_PARAMETER;
double dlandY = 3 * Cx * pow(cbrt(abs(errY) / Cx), 2) * signum(errY);
double landH = tarH + atan(dlandY);
double dErrY = currV * sin (errH);
double landAngV = (2 * (1 / cbrt(abs(errY) / Cx)) * dErrY) /
(1 + tan(landH - tarH) * tan(landH - tarH));
//calculating the corrected trajectory control parameters
double switchAngV = landAngV - currAngV +
sqrt(2 * MAX_ROBOT_ANGULAR_ACCELERATION * abs(landH - currH))
* signum(landH - currH) * 0.2;
double switchAngA = min(abs(switchAngV / dt), MAX_ROBOT_ANGULAR_ACCELERATION) * signum(switchAngV);
double newAngV = currAngV + switchAngA * dt;
//calculating new velocity
double dErrX = targetVelocity - currV * cos(errH);
double switchV = dErrX + sqrt( 2 * MAX_ROBOT_LINEAR_ACCELERATION * abs(errX)) * signum(errX);
double switchA = min(abs(switchV / dt), MAX_ROBOT_LINEAR_ACCELERATION) * signum(switchV);
// double newV = currV + switchA * dt;
//calculating delta motor speed control values
double k = 0.1;
double newDeltaLR = k* MAX_SPEED * MAIN_AXE_LENGTH * dt * switchAngA / (2 * WHEEL_RADIUS);
//calculating new motor speed control values
int newVL = (int) (last.getVelocityL() + switchA * dt / WHEEL_RADIUS - newDeltaLR * last.getDirL());
int newVR = (int) (last.getVelocityR() + switchA * dt / WHEEL_RADIUS + newDeltaLR * last.getDirL());
System.out.println("!!! time=" + time + ", dt=" + dt + ", tarX=" + tarX + ", tarY=" + tarY
+ ", startH=" + startH + ", errH=" + errH + ", targetX=" + targetX + ", targetY=" + targetY + ", targetHeading=" + targetHeading
+ ", errX=" + errX + ", errY=" + errY + ", dlandY=" + dlandY + ", currV=" + currV + ", dist=" + currDist
+ ", switchAngV/dt=" + switchAngV / dt );
System.out.println("!!! remainingPathLength=" + remainingPathLength + ", dErrX=" + dErrX + ", switchV=" + switchV + ", switchA=" + switchA );
if(lastCommand.getName() != STOP && remainingPathLength < last.getRemainingPath()
&& remainingPathLength > currV * currV / ROBOT_STOPPING_DECCELERATION ) { //drive until minimum distance to target
return new MotorsCommand(last.getDirL(), last.getDirR(), newVL, newVR, (float) remainingPathLength);
} else {
System.out.println("FINAL POSITION: " + currPos);
return STOP_COMMAND;
}
}).map((MotorsCommand motorsCommand) -> {
runMotors(motorsCommand);
return motorsCommand;
})
.takeUntil((MotorsCommand motorsCommand) -> motorsCommand.equals(STOP_COMMAND) )
.subscribe( (MotorsCommand motorsCommand) -> {
System.out.println(motorsCommand);
});
}
}
protected void setupGpioForMovement() {
// Motor direction pins
Gpio.pinMode(5, Gpio.OUTPUT);
Gpio.pinMode(6, Gpio.OUTPUT);
Gpio.pinMode(12, Gpio.PWM_OUTPUT);
Gpio.pinMode(13, Gpio.PWM_OUTPUT);
Gpio.pwmSetMode(Gpio.PWM_MODE_MS);
Gpio.pwmSetRange(MAX_SPEED);
Gpio.pwmSetClock(CLOCK_DIVISOR);
}
private void runMotors(MotorsCommand mc) {
//setting motor directions
Gpio.digitalWrite(5, mc.getDirR() > 0 ? 1 : 0);
Gpio.digitalWrite(6, mc.getDirL() > 0 ? 1 : 0);
//setting speed
if(mc.getVelocityR() >= 0 && mc.getVelocityR() <= MAX_SPEED)
Gpio.pwmWrite(12, mc.getVelocityR()); // speed up to MAX_SPEED
if(mc.getVelocityL() >= 0 && mc.getVelocityL() <= MAX_SPEED)
Gpio.pwmWrite(13, mc.getVelocityL());
}
@Override
public void onSubscribe(Subscription s) {
subscription = s;
subscription.request(Long.MAX_VALUE);
}
@Override
public void onError(Throwable t) {
// TODO Auto-generated method stub
}
@Override
public void onComplete() {
// TODO Auto-generated method stub
}
}
| iproduct/course-social-robotics | iptpi-demo/src/main/java/org/iproduct/iptpi/domain/movement/MovementCommandSubscriber.java | Java | gpl-2.0 | 25,456 |
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.FocusFinder;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import com.android.launcher.R;
public class Cling extends FrameLayout {
static final String WORKSPACE_CLING_DISMISSED_KEY = "cling.workspace.dismissed";
static final String ALLAPPS_CLING_DISMISSED_KEY = "cling.allapps.dismissed";
static final String FOLDER_CLING_DISMISSED_KEY = "cling.folder.dismissed";
private static String WORKSPACE_PORTRAIT = "workspace_portrait";
private static String WORKSPACE_LANDSCAPE = "workspace_landscape";
private static String WORKSPACE_LARGE = "workspace_large";
private static String WORKSPACE_CUSTOM = "workspace_custom";
private static String ALLAPPS_PORTRAIT = "all_apps_portrait";
private static String ALLAPPS_LANDSCAPE = "all_apps_landscape";
private static String ALLAPPS_LARGE = "all_apps_large";
private static String FOLDER_PORTRAIT = "folder_portrait";
private static String FOLDER_LANDSCAPE = "folder_landscape";
private static String FOLDER_LARGE = "folder_large";
private Launcher mLauncher;
private boolean mIsInitialized;
private String mDrawIdentifier;
private Drawable mBackground;
private Drawable mPunchThroughGraphic;
private Drawable mHandTouchGraphic;
private int mPunchThroughGraphicCenterRadius;
private int mAppIconSize;
private int mButtonBarHeight;
private float mRevealRadius;
private int[] mPositionData;
private Paint mErasePaint;
public Cling(Context context) {
this(context, null, 0);
}
public Cling(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public Cling(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Cling, defStyle, 0);
mDrawIdentifier = a.getString(R.styleable.Cling_drawIdentifier);
a.recycle();
setClickable(true);
}
void init(Launcher l, int[] positionData) {
if (!mIsInitialized) {
mLauncher = l;
mPositionData = positionData;
Resources r = getContext().getResources();
mPunchThroughGraphic = r.getDrawable(R.drawable.cling);
mPunchThroughGraphicCenterRadius =
r.getDimensionPixelSize(R.dimen.clingPunchThroughGraphicCenterRadius);
mAppIconSize = r.getDimensionPixelSize(R.dimen.app_icon_size);
mRevealRadius = r.getDimensionPixelSize(R.dimen.reveal_radius) * 1f;
mButtonBarHeight = r.getDimensionPixelSize(R.dimen.button_bar_height);
mErasePaint = new Paint();
mErasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY));
mErasePaint.setColor(0xFFFFFF);
mErasePaint.setAlpha(0);
mIsInitialized = true;
}
}
void cleanup() {
mBackground = null;
mPunchThroughGraphic = null;
mHandTouchGraphic = null;
mIsInitialized = false;
}
public String getDrawIdentifier() {
return mDrawIdentifier;
}
private int[] getPunchThroughPositions() {
if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT)) {
return new int[]{getMeasuredWidth() / 2, getMeasuredHeight() - (mButtonBarHeight / 2)};
} else if (mDrawIdentifier.equals(WORKSPACE_LANDSCAPE)) {
return new int[]{getMeasuredWidth() - (mButtonBarHeight / 2), getMeasuredHeight() / 2};
} else if (mDrawIdentifier.equals(WORKSPACE_LARGE)) {
final float scale = LauncherApplication.getScreenDensity();
final int cornerXOffset = (int) (scale * 15);
final int cornerYOffset = (int) (scale * 10);
return new int[]{getMeasuredWidth() - cornerXOffset, cornerYOffset};
} else if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
return mPositionData;
}
return new int[]{-1, -1};
}
@Override
public View focusSearch(int direction) {
return this.focusSearch(this, direction);
}
@Override
public View focusSearch(View focused, int direction) {
return FocusFinder.getInstance().findNextFocus(this, focused, direction);
}
@Override
public boolean onHoverEvent(MotionEvent event) {
return (mDrawIdentifier.equals(WORKSPACE_PORTRAIT)
|| mDrawIdentifier.equals(WORKSPACE_LANDSCAPE)
|| mDrawIdentifier.equals(WORKSPACE_LARGE)
|| mDrawIdentifier.equals(ALLAPPS_PORTRAIT)
|| mDrawIdentifier.equals(ALLAPPS_LANDSCAPE)
|| mDrawIdentifier.equals(ALLAPPS_LARGE)
|| mDrawIdentifier.equals(WORKSPACE_CUSTOM));
}
@Override
public boolean onTouchEvent(android.view.MotionEvent event) {
if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) ||
mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) ||
mDrawIdentifier.equals(WORKSPACE_LARGE) ||
mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
int[] positions = getPunchThroughPositions();
for (int i = 0; i < positions.length; i += 2) {
double diff = Math.sqrt(Math.pow(event.getX() - positions[i], 2) +
Math.pow(event.getY() - positions[i + 1], 2));
if (diff < mRevealRadius) {
return false;
}
}
} else if (mDrawIdentifier.equals(FOLDER_PORTRAIT) ||
mDrawIdentifier.equals(FOLDER_LANDSCAPE) ||
mDrawIdentifier.equals(FOLDER_LARGE)) {
Folder f = mLauncher.getWorkspace().getOpenFolder();
if (f != null) {
Rect r = new Rect();
f.getHitRect(r);
if (r.contains((int) event.getX(), (int) event.getY())) {
return false;
}
}
}
return true;
};
@Override
protected void dispatchDraw(Canvas canvas) {
if (mIsInitialized) {
DisplayMetrics metrics = new DisplayMetrics();
mLauncher.getWindowManager().getDefaultDisplay().getMetrics(metrics);
// Initialize the draw buffer (to allow punching through)
Bitmap b = Bitmap.createBitmap(getMeasuredWidth(), getMeasuredHeight(),
Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
// Draw the background
if (mBackground == null) {
if (mDrawIdentifier.equals(WORKSPACE_PORTRAIT) ||
mDrawIdentifier.equals(WORKSPACE_LANDSCAPE) ||
mDrawIdentifier.equals(WORKSPACE_LARGE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling1);
} else if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling2);
} else if (mDrawIdentifier.equals(FOLDER_PORTRAIT) ||
mDrawIdentifier.equals(FOLDER_LANDSCAPE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling3);
} else if (mDrawIdentifier.equals(FOLDER_LARGE)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling4);
} else if (mDrawIdentifier.equals(WORKSPACE_CUSTOM)) {
mBackground = getResources().getDrawable(R.drawable.bg_cling5);
}
}
if (mBackground != null) {
mBackground.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
mBackground.draw(c);
} else {
c.drawColor(0x99000000);
}
int cx = -1;
int cy = -1;
float scale = mRevealRadius / mPunchThroughGraphicCenterRadius;
int dw = (int) (scale * mPunchThroughGraphic.getIntrinsicWidth());
int dh = (int) (scale * mPunchThroughGraphic.getIntrinsicHeight());
// Determine where to draw the punch through graphic
int[] positions = getPunchThroughPositions();
for (int i = 0; i < positions.length; i += 2) {
cx = positions[i];
cy = positions[i + 1];
if (cx > -1 && cy > -1) {
c.drawCircle(cx, cy, mRevealRadius, mErasePaint);
mPunchThroughGraphic.setBounds(cx - dw / 2, cy - dh / 2, cx + dw / 2, cy + dh / 2);
mPunchThroughGraphic.draw(c);
}
}
// Draw the hand graphic in All Apps
if (mDrawIdentifier.equals(ALLAPPS_PORTRAIT) ||
mDrawIdentifier.equals(ALLAPPS_LANDSCAPE) ||
mDrawIdentifier.equals(ALLAPPS_LARGE)) {
if (mHandTouchGraphic == null) {
mHandTouchGraphic = getResources().getDrawable(R.drawable.hand);
}
int offset = mAppIconSize / 4;
mHandTouchGraphic.setBounds(cx + offset, cy + offset,
cx + mHandTouchGraphic.getIntrinsicWidth() + offset,
cy + mHandTouchGraphic.getIntrinsicHeight() + offset);
mHandTouchGraphic.draw(c);
}
canvas.drawBitmap(b, 0, 0, null);
c.setBitmap(null);
b = null;
}
// Draw the rest of the cling
super.dispatchDraw(canvas);
};
}
| rex-xxx/mt6572_x201 | packages/apps/Launcher2/src/com/android/launcher2/Cling.java | Java | gpl-2.0 | 11,008 |
package rb;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.persistence.TypedQuery;
import rb.helpers.ClassificationResult;
import rb.helpers.DBHandler;
import rb.helpers.StemmerHelper;
import rb.persistentobjects.Statement;
import rb.persistentobjects.Word;
import ca.uwo.csd.ai.nlp.common.SparseVector;
import ca.uwo.csd.ai.nlp.kernel.KernelManager;
import ca.uwo.csd.ai.nlp.kernel.LinearKernel;
import ca.uwo.csd.ai.nlp.libsvm.svm_model;
import ca.uwo.csd.ai.nlp.libsvm.ex.Instance;
import ca.uwo.csd.ai.nlp.libsvm.ex.SVMPredictor;
import com.cd.reddit.Reddit;
import com.cd.reddit.RedditException;
import com.cd.reddit.json.jackson.RedditJsonParser;
import com.cd.reddit.json.mapping.RedditComment;
import com.cd.reddit.json.mapping.RedditLink;
import com.cd.reddit.json.util.RedditComments;
import de.daslaboratorium.machinelearning.classifier.BayesClassifier;
import de.daslaboratorium.machinelearning.classifier.Classification;
public class Poster {
private static Random randomGenerator;
static Reddit reddit = new Reddit("machinelearningbot/0.1 by elggem");
static String subreddit = "";
static BayesClassifier<String, String> bayes = null;
static svm_model model = null;
static List<Statement> statements = null;
static List<Word> words = null;
static int max_reply_length = 25;
static int classifier = 0;
static ArrayList<String> alreadyPostedComments = new ArrayList<String>();
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Reddit BOT Final stage. Armed and ready to go!");
randomGenerator = new Random();
if (args.length < 4) {
System.out.println(" usage: java -Xmx4g -jar JAR SUBREDDIT CLASSIFIER USER PASS\n" +
" with: SUBREDDIT = the subreddit to post to\n" +
" CLASSIFIER = 1:BN, 2:SVM 3:Random\n" +
" USER/PASS = username and password\n");
System.exit(1);
}
subreddit = args[0];
classifier = Integer.valueOf(args[1]);
try {
reddit.login(args[2], args[3]);
} catch (RedditException e) {
e.printStackTrace();
}
DBHandler.initializeHandler(args[0]);
if (statements == null) {
TypedQuery<Statement> query=DBHandler.em.createQuery("Select o from Statement o where o.text != \"[deleted]\" and o.parentStatement!= null and o.length>0 and o.length < " + max_reply_length,Statement.class);
statements = query.getResultList();
}
if (words == null) {
TypedQuery<Word> queryW=DBHandler.em.createQuery("Select o from Word o",Word.class);
words = queryW.getResultList();
}
//TIMER CODE
Timer timer = new Timer();
long thirty_minutes = 30*60*1000;
long one_hour = thirty_minutes*2;
long waiting_time = (long) (one_hour+(Math.random()*one_hour));
timer.schedule(new TimerTask() {
@Override
public void run() {
System.out.println("-> Awake from Hibernation");
RedditComment commentToReplyTo = findInterestingCommentPopularity(subreddit);
System.out.println("-> Generating Reply for " + commentToReplyTo.getBody());
String generatedReply = generateCommentFor(commentToReplyTo, classifier);
System.out.println("-> Generated " + generatedReply);
System.out.println("-> Posting..");
postCommentAsReplyTo(generatedReply, commentToReplyTo);
System.out.println("-> Going Back to Sleep...");
}
}, waiting_time, waiting_time);
//-------------
System.out.println("-> Awake from Hibernation");
RedditComment commentToReplyTo = findInterestingCommentPopularity(subreddit);
System.out.println("-> Generating Reply for " + commentToReplyTo.getBody());
String generatedReply = generateCommentFor(commentToReplyTo, classifier);
System.out.println("-> Generated " + generatedReply);
System.out.println("-> Posting..");
postCommentAsReplyTo(generatedReply, commentToReplyTo);
System.out.println("-> Going Back to Sleep...");
///---------------------
//DBHandler.closeHandler();
}
public static RedditComment findInterestingCommentRelevance(String subreddit) {
//Get the first 25 posts.
try {
List<RedditLink> links = reddit.listingFor(subreddit, "");
Collections.shuffle(links);
RedditLink linkOfInterest = links.get(0);
System.out.println(" findInterestingComment post: " + linkOfInterest);
List<RedditComment> comments = getAllCommentsForLink(linkOfInterest, subreddit);
ArrayList<ClassificationResult> classifications = new ArrayList<ClassificationResult>();
for (RedditComment redditComment : comments) {
classifications.add(classifyCommentBayes(redditComment));
}
RedditComment bestComment = null;
double max_prob = 0;
int i=0;
for (RedditComment redditComment : comments) {
double prob = classifications.get(i).probability;
if (prob>max_prob && convertStringToStemmedList(redditComment.getBody()).size()>0) {
max_prob = prob;
bestComment = redditComment;
}
i++;
}
System.out.println(" findInterestingComment comment: " + bestComment);
return bestComment;
} catch (Exception e) {
System.out.println("ERROR, trying next time: " + e.getLocalizedMessage());
}
return null;
}
public static RedditComment findInterestingCommentPopularity(String subreddit) {
//Get the first 25 posts.
try {
List<RedditLink> links = reddit.listingFor(subreddit, "");
Collections.shuffle(links);
RedditLink linkOfInterest = links.get(0);
System.out.println(" findInterestingComment post: " + linkOfInterest);
List<RedditComment> comments = getAllCommentsForLink(linkOfInterest, subreddit);
RedditComment bestComment = null;
long max_karma = 0;
for (RedditComment redditComment : comments) {
if (redditComment.getUps()-redditComment.getDowns() > max_karma) {
//if (redditComment.getReplies().toString().length() <= 10) {
max_karma = redditComment.getUps()-redditComment.getDowns();
bestComment = redditComment;
//}
}
}
System.out.println(" findInterestingComment comment: " + bestComment);
return bestComment;
} catch (Exception e) {
System.out.println("ERROR, trying next time: " + e.getLocalizedMessage());
}
return null;
}
public static String generateCommentFor(RedditComment comment, int classifierID) {
String generated = "";
if (classifierID == 1) {
generated = classifyCommentBayes(comment).resultString;
} else if (classifierID == 2) {
generated = classifyCommentSVM(comment);
} else if (classifierID == 3) {
generated = classifyCommentRandom(comment);
} else {
System.out.println("Choose a valid classifier dude.");
System.exit(1);
}
return generated;
}
public static void postCommentAsReplyTo(String comment, RedditComment parent) {
try {
System.out.println(" postCommentAsReplyTo response: "+reddit.comment(comment, parent.getName()));
} catch (RedditException e) {
System.out.println("ERROR, trying next time: " + e.getLocalizedMessage());
}
}
public static String classifyCommentSVM(RedditComment comment) {
if (model == null) {
try {
model = SVMPredictor.loadModel(subreddit + ".model");
} catch (Exception e1) {
System.out.println("ERROR: Couldnt load SVM model. Exitting");
System.exit(1);
}
KernelManager.setCustomKernel(new LinearKernel());
System.out.println(" classifyCommentSVM: loaded model!!");
}
ArrayList<String> inputlist = convertStringToStemmedList(comment.getBody());
SparseVector vec = new SparseVector();
for (Word word : words) {
int value = 0;
if(inputlist.contains(word.word)) {
value = 1;
}
vec.add(words.indexOf(word), value);
}
Instance inst = new Instance(0, vec);
double result = SVMPredictor.predict(inst, model, false);
return statements.get((int) result).text;
}
public static ClassificationResult classifyCommentBayes(RedditComment comment) {
if (bayes == null) {
// Create a new bayes classifier with string categories and string features.
bayes = new BayesClassifier<String, String>();
// Change the memory capacity. New learned classifications (using
// learn method are stored in a queue with the size given here and
// used to classify unknown sentences.
bayes.setMemoryCapacity(50000);
TypedQuery<Statement> query=DBHandler.em.createQuery("Select o from Statement o where o.text != \"[deleted]\" and o.parentStatement!= null and o.length>0 and o.length < " + max_reply_length,Statement.class);
List<Statement> statements = query.getResultList();
System.out.println(" classifyCommentBayes analyzing " + statements.size() + " statements... ");
for (Statement statement : statements) {
ArrayList<String> wordStrings = new ArrayList<String>();
for (Word word : statement.parentStatement.includedWords) {
wordStrings.add(word.word);
}
//LEARN
bayes.learn(statement.text, wordStrings);
}
}
ArrayList<String> list = convertStringToStemmedList(comment.getBody());
Classification<String,String> result = bayes.classify(list);
System.out.println(" classifyCommentBayes " + list + " prob " + result.getProbability());
return new ClassificationResult(result.getCategory(), result.getProbability());
}
public static String classifyCommentRandom(RedditComment comment) {
String result = statements.get(randomGenerator.nextInt(statements.size())).text;
System.out.println(" classifyCommentRandom ");
return result;
}
public static List<RedditComment>getAllRepliesForComment(RedditComment redditComment) {
List<RedditComment> thelist = new ArrayList<RedditComment>();
try {
thelist.add(redditComment);
if (redditComment.getReplies().toString().length() >= 10) {
final RedditJsonParser parser = new RedditJsonParser(redditComment.getReplies());
List<RedditComment> redditReplies = parser.parseCommentsOnly();
for (RedditComment redditCommentReply : redditReplies) {
List<RedditComment> additionalList = getAllRepliesForComment(redditCommentReply);
for (RedditComment redditComment2 : additionalList) {
redditComment2.parent = redditComment;
}
thelist.addAll(additionalList);
}
}
} catch (RedditException e) {
e.printStackTrace();
}
return thelist;
}
public static List<RedditComment>getAllCommentsForLink(RedditLink redditLink, String subreddit) {
List<RedditComment> thelist = new ArrayList<RedditComment>();
try {
if (redditLink.getNum_comments()>0) {
RedditComments comments;
comments = reddit.commentsFor(subreddit, redditLink.getId());
for (RedditComment redditComment : comments.getComments()) {
List<RedditComment> additionalList = getAllRepliesForComment(redditComment);
thelist.addAll(additionalList);
}
}
} catch (RedditException e) {
e.printStackTrace();
}
return thelist;
}
public static ArrayList<String> convertStringToStemmedList(String input) {
ArrayList<String> wordStrings = new ArrayList<String>();
for (String string : input.split("\\s+")) {
String pruned = string.replaceAll("[^a-zA-Z]", "").toLowerCase();
String stemmed = StemmerHelper.stemWord(pruned);
if (DBHandler.checkWord(stemmed)) {
wordStrings.add(stemmed);
}
}
return wordStrings;
}
}
| elggem/redditbot | src/rb/Poster.java | Java | gpl-2.0 | 11,681 |
<?php
class WebApplication extends CWebApplication
{
public $keywords;
public $description;
} | daixianceng/microwall | protected/components/WebApplication.php | PHP | gpl-2.0 | 95 |
using System;
using Server.Misc;
using Server.Network;
using System.Collections;
using Server.Items;
using Server.Targeting;
namespace Server.Mobiles
{
public class KhaldunZealot : BaseCreature
{
public override bool ClickTitle{ get{ return false; } }
public override bool ShowFameTitle{ get{ return false; } }
[Constructable]
public KhaldunZealot(): base( AIType.AI_Melee, FightMode.Closest, 10, 1, 0.2, 0.4 )
{
Body = 0x190;
Name = "Zealot of Khaldun";
Title = "the Knight";
Hue = 0;
SetStr( 351, 400 );
SetDex( 151, 165 );
SetInt( 76, 100 );
SetHits( 448, 470 );
SetDamage( 15, 25 );
SetDamageType( ResistanceType.Physical, 75 );
SetDamageType( ResistanceType.Cold, 25 );
SetResistance( ResistanceType.Physical, 35, 45 );
SetResistance( ResistanceType.Fire, 25, 30 );
SetResistance( ResistanceType.Cold, 50, 60 );
SetResistance( ResistanceType.Poison, 25, 35 );
SetResistance( ResistanceType.Energy, 25, 35 );
SetSkill( SkillName.Wrestling, 70.1, 80.0 );
SetSkill( SkillName.Swords, 120.1, 130.0 );
SetSkill( SkillName.Anatomy, 120.1, 130.0 );
SetSkill( SkillName.MagicResist, 90.1, 100.0 );
SetSkill( SkillName.Tactics, 90.1, 100.0 );
Fame = 10000;
Karma = -10000;
VirtualArmor = 40;
VikingSword weapon = new VikingSword();
weapon.Hue = 0x835;
weapon.Movable = false;
AddItem( weapon );
MetalShield shield = new MetalShield();
shield.Hue = 0x835;
shield.Movable = false;
AddItem( shield );
BoneHelm helm = new BoneHelm();
helm.Hue = 0x835;
AddItem( helm );
BoneArms arms = new BoneArms();
arms.Hue = 0x835;
AddItem( arms );
BoneGloves gloves = new BoneGloves();
gloves.Hue = 0x835;
AddItem( gloves );
BoneChest tunic = new BoneChest();
tunic.Hue = 0x835;
AddItem( tunic );
BoneLegs legs = new BoneLegs();
legs.Hue = 0x835;
AddItem( legs );
AddItem( new Boots() );
}
public override int GetIdleSound()
{
return 0x184;
}
public override int GetAngerSound()
{
return 0x286;
}
public override int GetDeathSound()
{
return 0x288;
}
public override int GetHurtSound()
{
return 0x19F;
}
public override bool AlwaysMurderer{ get{ return true; } }
public override bool Unprovokable{ get{ return true; } }
public override Poison PoisonImmune{ get{ return Poison.Deadly; } }
public KhaldunZealot( Serial serial ) : base( serial )
{
}
public override bool OnBeforeDeath()
{
BoneKnight rm = new BoneKnight();
rm.Team = this.Team;
rm.Combatant = this.Combatant;
rm.NoKillAwards = true;
if ( rm.Backpack == null )
{
Backpack pack = new Backpack();
pack.Movable = false;
rm.AddItem( pack );
}
for ( int i = 0; i < 2; i++ )
{
LootPack.FilthyRich.Generate( this, rm.Backpack, true, LootPack.GetLuckChanceForKiller( this ) );
LootPack.FilthyRich.Generate( this, rm.Backpack, false, LootPack.GetLuckChanceForKiller( this ) );
}
Effects.PlaySound(this, Map, GetDeathSound());
Effects.SendLocationEffect( Location, Map, 0x3709, 30, 10, 0x835, 0 );
rm.MoveToWorld( Location, Map );
Delete();
return false;
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
/*int version = */reader.ReadInt();
}
}
} | brodock/sunuo | scripts/legacy/Mobiles/Monsters/Humanoid/Melee/KhaldunZealot.cs | C# | gpl-2.0 | 3,472 |
<?php
/**
* WordPress CRON API
*
* @package WordPress
*/
/**
* Schedules a hook to run only once.
*
* Schedules a hook which will be executed once by the Wordpress actions core at
* a time which you specify. The action will fire off when someone visits your
* WordPress site, if the schedule time has passed.
*
* @since 2.1.0
* @link http://codex.wordpress.org/Function_Reference/wp_schedule_single_event
*
* @param int $timestamp Timestamp for when to run the event.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
*/
function wp_schedule_single_event( $timestamp, $hook, $args = array()) {
// don't schedule a duplicate if there's already an identical event due in the next 10 minutes
$next = wp_next_scheduled($hook, $args);
if ( $next && $next <= $timestamp + 600 )
return;
$crons = _get_cron_array();
$key = md5(serialize($args));
$crons[$timestamp][$hook][$key] = array( 'schedule' => false, 'args' => $args );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Schedule a periodic event.
*
* Schedules a hook which will be executed by the WordPress actions core on a
* specific interval, specified by you. The action will trigger when someone
* visits your WordPress site, if the scheduled time has passed.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return bool|null False on failure, null when complete with scheduling event.
*/
function wp_schedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
$key = md5(serialize($args));
if ( !isset( $schedules[$recurrence] ) )
return false;
$crons[$timestamp][$hook][$key] = array( 'schedule' => $recurrence, 'args' => $args, 'interval' => $schedules[$recurrence]['interval'] );
uksort( $crons, "strnatcasecmp" );
_set_cron_array( $crons );
}
/**
* Reschedule a recurring event.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param string $recurrence How often the event should recur.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return bool|null False on failure. Null when event is rescheduled.
*/
function wp_reschedule_event( $timestamp, $recurrence, $hook, $args = array()) {
$crons = _get_cron_array();
$schedules = wp_get_schedules();
$key = md5(serialize($args));
$interval = 0;
// First we try to get it from the schedule
if ( 0 == $interval )
$interval = $schedules[$recurrence]['interval'];
// Now we try to get it from the saved interval in case the schedule disappears
if ( 0 == $interval )
$interval = $crons[$timestamp][$hook][$key]['interval'];
// Now we assume something is wrong and fail to schedule
if ( 0 == $interval )
return false;
while ( $timestamp < time() + 1 )
$timestamp += $interval;
wp_schedule_event( $timestamp, $recurrence, $hook, $args );
}
/**
* Unschedule a previously scheduled cron job.
*
* The $timestamp and $hook parameters are required, so that the event can be
* identified.
*
* @since 2.1.0
*
* @param int $timestamp Timestamp for when to run the event.
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
*/
function wp_unschedule_event( $timestamp, $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
unset( $crons[$timestamp][$hook][$key] );
if ( empty($crons[$timestamp][$hook]) )
unset( $crons[$timestamp][$hook] );
if ( empty($crons[$timestamp]) )
unset( $crons[$timestamp] );
_set_cron_array( $crons );
}
/**
* Unschedule all cron jobs attached to a specific hook.
*
* @since 2.1.0
*
* @param callback $hook Function or method to call, when cron is run.
* @param mixed $args,... Optional. Event arguments.
*/
function wp_clear_scheduled_hook( $hook ) {
$args = array_slice( func_get_args(), 1 );
while ( $timestamp = wp_next_scheduled( $hook, $args ) )
wp_unschedule_event( $timestamp, $hook, $args );
}
/**
* Retrieve the next timestamp for a cron event.
*
* @since 2.1.0
*
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return bool|int The UNIX timestamp of the next time the scheduled event will occur.
*/
function wp_next_scheduled( $hook, $args = array() ) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $timestamp;
}
return false;
}
/**
* Send request to run cron through HTTP request that doesn't halt page loading.
*
* @since 2.1.0
*
* @return null Cron could not be spawned, because it is not needed to run.
*/
function spawn_cron( $local_time ) {
/*
* do not even start the cron if local server timer has drifted
* such as due to power failure, or misconfiguration
*/
$timer_accurate = check_server_timer( $local_time );
if ( !$timer_accurate )
return;
//sanity check
$crons = _get_cron_array();
if ( !is_array($crons) )
return;
$keys = array_keys( $crons );
$timestamp = $keys[0];
if ( $timestamp > $local_time )
return;
$cron_url = get_option( 'siteurl' ) . '/wp-cron.php?check=' . wp_hash('187425');
/*
* multiple processes on multiple web servers can run this code concurrently
* try to make this as atomic as possible by setting doing_cron switch
*/
$flag = get_option('doing_cron');
// clean up potential invalid value resulted from various system chaos
if ( $flag != 0 ) {
if ( $flag > $local_time + 10*60 || $flag < $local_time - 10*60 ) {
update_option('doing_cron', 0);
$flag = 0;
}
}
//don't run if another process is currently running it
if ( $flag > $local_time )
return;
update_option( 'doing_cron', $local_time + 30 );
wp_remote_post($cron_url, array('timeout' => 0.01, 'blocking' => false));
}
/**
* Run scheduled callbacks or spawn cron for all scheduled events.
*
* @since 2.1.0
*
* @return null When doesn't need to run Cron.
*/
function wp_cron() {
// Prevent infinite loops caused by lack of wp-cron.php
if ( strpos($_SERVER['REQUEST_URI'], '/wp-cron.php') !== false )
return;
$crons = _get_cron_array();
if ( !is_array($crons) )
return;
$keys = array_keys( $crons );
if ( isset($keys[0]) && $keys[0] > time() )
return;
$local_time = time();
$schedules = wp_get_schedules();
foreach ( $crons as $timestamp => $cronhooks ) {
if ( $timestamp > $local_time ) break;
foreach ( (array) $cronhooks as $hook => $args ) {
if ( isset($schedules[$hook]['callback']) && !call_user_func( $schedules[$hook]['callback'] ) )
continue;
spawn_cron( $local_time );
break 2;
}
}
}
/**
* Retrieve supported and filtered Cron recurrences.
*
* The supported recurrences are 'hourly' and 'daily'. A plugin may add more by
* hooking into the 'cron_schedules' filter. The filter accepts an array of
* arrays. The outer array has a key that is the name of the schedule or for
* example 'weekly'. The value is an array with two keys, one is 'interval' and
* the other is 'display'.
*
* The 'interval' is a number in seconds of when the cron job should run. So for
* 'hourly', the time is 3600 or 60*60. For weekly, the value would be
* 60*60*24*7 or 604800. The value of 'interval' would then be 604800.
*
* The 'display' is the description. For the 'weekly' key, the 'display' would
* be <code>__('Once Weekly')</code>.
*
* For your plugin, you will be passed an array. you can easily add your
* schedule by doing the following.
* <code>
* // filter parameter variable name is 'array'
* $array['weekly'] = array(
* 'interval' => 604800,
* 'display' => __('Once Weekly')
* );
* </code>
*
* @since 2.1.0
*
* @return array
*/
function wp_get_schedules() {
$schedules = array(
'hourly' => array( 'interval' => 3600, 'display' => __('Once Hourly') ),
'twicedaily' => array( 'interval' => 43200, 'display' => __('Twice Daily') ),
'daily' => array( 'interval' => 86400, 'display' => __('Once Daily') ),
);
return array_merge( apply_filters( 'cron_schedules', array() ), $schedules );
}
/**
* Retrieve Cron schedule for hook with arguments.
*
* @since 2.1.0
*
* @param callback $hook Function or method to call, when cron is run.
* @param array $args Optional. Arguments to pass to the hook function.
* @return string|bool False, if no schedule. Schedule on success.
*/
function wp_get_schedule($hook, $args = array()) {
$crons = _get_cron_array();
$key = md5(serialize($args));
if ( empty($crons) )
return false;
foreach ( $crons as $timestamp => $cron ) {
if ( isset( $cron[$hook][$key] ) )
return $cron[$hook][$key]['schedule'];
}
return false;
}
//
// Private functions
//
/**
* Retrieve cron info array option.
*
* @since 2.1.0
* @access private
*
* @return array CRON info array.
*/
function _get_cron_array() {
$cron = get_option('cron');
if ( ! is_array($cron) )
return false;
if ( !isset($cron['version']) )
$cron = _upgrade_cron_array($cron);
unset($cron['version']);
return $cron;
}
/**
* Updates the CRON option with the new CRON array.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
*/
function _set_cron_array($cron) {
$cron['version'] = 2;
update_option( 'cron', $cron );
}
/**
* Upgrade a Cron info array.
*
* This function upgrades the Cron info array to version 2.
*
* @since 2.1.0
* @access private
*
* @param array $cron Cron info array from {@link _get_cron_array()}.
* @return array An upgraded Cron info array.
*/
function _upgrade_cron_array($cron) {
if ( isset($cron['version']) && 2 == $cron['version'])
return $cron;
$new_cron = array();
foreach ( (array) $cron as $timestamp => $hooks) {
foreach ( (array) $hooks as $hook => $args ) {
$key = md5(serialize($args['args']));
$new_cron[$timestamp][$hook][$key] = $args;
}
}
$new_cron['version'] = 2;
update_option( 'cron', $new_cron );
return $new_cron;
}
// stub for checking server timer accuracy, using outside standard time sources
function check_server_timer( $local_time ) {
return true;
}
?>
| pravinhirmukhe/flow1 | wp-includes/cron.php | PHP | gpl-2.0 | 11,000 |
#!/usr/bin/env python
## tumblrserv.py implements a Tumblr (http://www.tumblr.com) markup parsing
## engine and compatible webserver.
##
## Version: 0.2 final
##
## Copyright (C) 2009 Jeremy Herbert
## Contact mailto:jeremy@jeremyherbert.net
##
## This program is free software; you can redistribute it and/or
## modify it under the terms of the GNU General Public License
## as published by the Free Software Foundation; either version 2
## of the License, or (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
## 02110-1301, USA.
import os, sys, ftplib, yaml, cherrypy, re, urllib2
from src.post_classes import *
from src import json
from src.constants import *
from src.support import *
from src.net import *
from src.server import *
post_types = ['Regular', 'Photo', 'Quote', 'Link', 'Conversation', 'Video', 'Audio', 'Conversation']
args_dict = {
'autoreload': 0, # Whether to add the meta refresh tag
'publish': False, # Whether to push the new theme data to tumblr
'data_source': DATA_LOCAL, # Whether to use local data in the theme
}
########################################
# take the arguments and place them in a mutable list
arguments = sys.argv
# if the script has been run with the interpreter prefix, get rid of it
if arguments[0] == 'python' or arguments[0] == 'ipython' \
or arguments[0] == 'python2.5':
arguments.pop(0)
# pop off the script name
arguments.pop(0)
# load the configuration file
config_path = 'data/config.yml'
if contains(arguments, '--config'):
if os.path.exists(next_arg(arguments, '--config')):
config_path = next_arg(arguments, '--config')
config = get_config(config_path)
# now we check if there are any data processing flags
if contains(arguments, '--pull-data'):
# call pull_data with the argument after the flag
pull_data( next_arg(arguments, '--pull-data') )
if contains(arguments, '--theme'):
if not os.path.exists("themes/" + next_arg(arguments, '--theme') + '.thtml'):
err_exit("The theme file %s.thtml does not exist in the themes\
directory." % next_arg(arguments, '--theme'))
config['defaults']['theme_name'] = next_arg(arguments, '--theme')
if contains(arguments, '--publish'):
if not has_keys(config['publishing_info'], \
( 'url', 'username', 'password' )):
err_exit('The configuration file is missing some critical publishing\
information. Please make sure you have specified your url, username and\
password.')
publish_theme(config['publishing_info']['url'],\
config['publishing_info']['username'],\
config['publishing_info']['password'],\
get_markup('themes/%s.thtml' % config['defaults']['theme_name']))
if contains(arguments, '--do-nothing'):
config['optimisations']['do_nothing'] = True
# start the server up
cherrypy.config.update('data/cherrypy.conf')
cherrypy.quickstart(TumblrServ(config), '/') | jeremyherbert/TumblrServ | tumblrserv.py | Python | gpl-2.0 | 3,373 |
/*
* Copyright 2006-2016 The MZmine 3 Development Team
*
* This file is part of MZmine 3.
*
* MZmine 3 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.
*
* MZmine 3 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 MZmine 3; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package io.github.mzmine.util;
import java.io.File;
import java.util.List;
import javax.annotation.Nonnull;
import com.google.common.io.Files;
/**
* File name utilities
*/
public class FileNameUtil {
public static @Nonnull String findCommonPrefix(@Nonnull List<File> fileNames) {
if (fileNames.size() < 2)
return "";
String firstName = fileNames.get(0).getName();
for (int prefixLen = 0; prefixLen < firstName.length(); prefixLen++) {
char c = firstName.charAt(prefixLen);
for (int i = 1; i < fileNames.size(); i++) {
String ithName = fileNames.get(i).getName();
if (prefixLen >= ithName.length() || ithName.charAt(prefixLen) != c) {
// Mismatch found
return ithName.substring(0, prefixLen);
}
}
}
return firstName;
}
public static @Nonnull String findCommonSuffix(@Nonnull List<File> fileNames) {
if (fileNames.isEmpty())
return "";
if (fileNames.size() == 1) {
// Return file extension
String ext = Files.getFileExtension(fileNames.get(0).getAbsolutePath());
return "." + ext;
}
String firstName = fileNames.get(0).getName();
for (int suffixLen = 0; suffixLen < firstName.length(); suffixLen++) {
char c = firstName.charAt(firstName.length() - 1 - suffixLen);
for (int i = 1; i < fileNames.size(); i++) {
String ithName = fileNames.get(i).getName();
if (suffixLen >= ithName.length()
|| ithName.charAt(ithName.length() - 1 - suffixLen) != c) {
// Mismatch found
return ithName.substring(ithName.length() - suffixLen);
}
}
}
return firstName;
}
}
| DrewG/mzmine3 | src/main/java/io/github/mzmine/util/FileNameUtil.java | Java | gpl-2.0 | 2,482 |
<?php locate_template( array( 'mobile/header-mobile.php' ), true, false ); ?>
<?php if ( have_posts() ) { ?>
<?php while ( have_posts() ) {
the_post(); ?>
<div <?php post_class( 'tbm-post tbm-padded' ) ?> id="post-<?php the_ID(); ?>">
<h2><?php the_title(); ?></h2>
<?php the_content(); ?>
<?php wp_link_pages('before=<div class="tbm-pc-navi">' . __('Pages', 'fastfood') . ':&after=</div>'); ?>
</div>
<?php comments_template('/mobile/comments-mobile.php'); ?>
<?php
$tbm_args = array(
'post_type' => 'page',
'post_parent' => $post->ID,
'order' => 'ASC',
'orderby' => 'menu_order',
'numberposts' => 0
);
$tbm_sub_pages = get_posts( $tbm_args ); // retrieve the child pages
if (!empty($tbm_sub_pages)) { ?>
<?php echo fastfood_mobile_seztitle( 'before' ) . __( 'Child pages', 'fastfood' ) . fastfood_mobile_seztitle( 'after' ); ?>
<ul class="tbm-group">
<?php
foreach ( $tbm_sub_pages as $tbm_children ) {
echo '<li class="outset"><a href="' . get_permalink( $tbm_children ) . '" title="' . esc_attr( strip_tags( get_the_title( $tbm_children ) ) ) . '">' . get_the_title( $tbm_children ) . '</a></li>';
}
?>
</ul>
<?php } ?>
<?php $tbm_the_parent_page = $post->post_parent; // retrieve the parent page
if ( $tbm_the_parent_page ) {?>
<?php echo fastfood_mobile_seztitle( 'before' ) . __( 'Parent page', 'fastfood' ) . fastfood_mobile_seztitle( 'after' ); ?>
<ul class="tbm-group">
<li class="outset"><a href="<?php echo get_permalink( $tbm_the_parent_page ); ?>" title="<?php echo esc_attr( strip_tags( get_the_title( $tbm_the_parent_page ) ) ); ?>"><?php echo get_the_title( $tbm_the_parent_page ); ?></a></li>
</ul>
<?php } ?>
<?php } ?>
<?php } else { ?>
<p class="tbm-padded"><?php _e( 'Sorry, no posts matched your criteria.', 'fastfood' );?></p>
<?php } ?>
<?php locate_template( array( 'mobile/footer-mobile.php' ), true, false ); ?>
| zdislaw/phenon_wp | wp-content/themes/fastfood/mobile/loop-page-mobile.php | PHP | gpl-2.0 | 1,989 |
<?php
/**
* @author Linkero
* @filename fselink.class.php
* @copyright 2014
* @version 0.1b
*/
class fseLink
{
protected $userKey = "INSERT_USER_KEY"; //User Key
protected $groupKey = "INSERT_GROUP_KEY"; //Group Key
protected $groupId = "INSERT_GROUP_ID"; //Group ID
/* --------DO NOT EDIT BELOW THIS LINE-------- */
/* --Define initial arrays-- */
public $memberArray = array();
public $groupArray = array();
public $aircraftArray = array();
/* --Initializer-- */
public function startFSELink()
{
/* --Sets up groupArray-- */
/* --Structure: Flights, Time, Distance, Profit-- */
$this->groupArray = array(
0,
0,
0,
number_format(0.00, 2));
/* --Loads Aircraft feed and sets up aircraftArray-- */
/* --Structure: Registration, Make/Model, Flights, Time, Distance, Profit-- */
$ac = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=aircraft&search=key&readaccesskey=$this->groupKey");
foreach ($ac->Aircraft as $aircraft) {
array_push($this->aircraftArray, array(
"$aircraft->Registration",
"$aircraft->MakeModel",
0,
0,
0,
number_format(0.00, 2)));
}
/* --Loads Group Member feed and sets up memberArray-- */
/* --Structure: Pilot Name, Group Status, Flights, Time, Distance, Profit-- */
$mem = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=group&search=members&readaccesskey=$this->groupKey");
foreach ($mem->Member as $Member) {
array_push($this->memberArray, array(
"$Member->Name",
"$Member->Status",
0,
0,
0,
number_format(0.00, 2))); //name, status, flights, time, distance, profit
}
/* --Populate arrays and return for use-- */
$this->populateArrays($this->memberArray, $this->groupArray, $this->
aircraftArray);
return $this->memberArray;
return $this->groupArray;
return $this->aircraftArray;
}
/* --Populate Arrays-- */
private function populateArrays(&$memberArray, &$groupArray, &$aircraftArray)
{
/* --Loads Flight Log feed(LIMIT 500) and starts populating-- */
$logs = simplexml_load_file("http://www.fseconomy.net/data?userkey=$this->userKey&format=xml&query=flightlogs&search=id&readaccesskey=$this->groupKey&fromid=$this->groupId");
foreach ($logs->FlightLog as $log) {
$ft = explode(":", $log->FlightTime); //Split time for use
/* --Populate memberArray-- */
for ($x = 0; $x < count($memberArray); $x++) {
if (strcmp($memberArray[$x][0], $log->Pilot) == 0) {
$memberArray[$x][2] = $memberArray[$x][2] + 1; //Increment flight counter
$memberArray[$x][3] = $memberArray[$x][3] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes)
$memberArray[$x][4] = $memberArray[$x][4] + $log->Distance; //Add Distance
$memberArray[$x][5] = $memberArray[$x][5] + floatval($log->PilotFee); //Add Pilot's Pay
}
}
/* --Populates groupArray-- */
$groupArray[1] = $groupArray[1] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes)
$groupArray[2] = $groupArray[2] + $log->Distance; //Add Distance
$groupArray[3] = $groupArray[3] + floatval($log->Income) - floatval($log->
PilotFee) - floatval($log->CrewCost) - floatval($log->BookingFee) - floatval($log->
FuelCost) - floatval($log->GCF) - floatval($log->RentalCost); //Calculate Profit
/* --Populates aircraftArray-- */
for ($x = 0; $x < count($aircraftArray); $x++) {
if (strcmp($aircraftArray[$x][0], $log->Aircraft) == 0) {
$aircraftArray[$x][2] = $aircraftArray[$x][2] + 1; //Increment flight counter
$aircraftArray[$x][3] = $aircraftArray[$x][3] + $ft[1] + ($ft[0] * 60); //Add Flight time(in minutes)
$aircraftArray[$x][4] = $aircraftArray[$x][4] + $log->Distance; //Add Distance
$aircraftArray[$x][5] = $aircraftArray[$x][5] + floatval($log->Income) -
floatval($log->CrewCost) - floatval($log->BookingFee) - floatval($log->FuelCost) -
floatval($log->GCF); //Calculate Profit
}
}
$groupArray[0] = count($logs->FlightLog); //Increment flight counter
}
/* --Returns populated arrays-- */
return $aircraftArray;
return $memberArray;
return $groupArray;
}
/* --Display sortable Pilot stats table-- */
public function displayPilotStats()
{
echo "<table id=\"memberTable\" class=\"tablesorter\"><thead><tr><th>Pilot</th><th>Status</th><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>";
for ($x = 0; $x < count($this->memberArray); $x++) {
echo "<tr><td>" . $this->memberArray[$x][0] . "</td><td>" . ucfirst($this->
memberArray[$x][1]) . "</td><td>" . $this->memberArray[$x][2] . "</td><td>" . $this->
formatTime($this->memberArray[$x][3]) . "</td><td>" . $this->memberArray[$x][4] .
"nm</td><td>$" . number_format($this->memberArray[$x][5], 2) . "</td></tr>";
}
echo "</tbody></table>";
}
/* --Display sortable Pilot stats table-- */
public function displayGroupStats()
{
echo "<table id=\"groupTable\" class=\"tablesorter\"><thead><tr><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>";
echo "<tr><td>" . $this->groupArray[0] . "</td><td>" . $this->formatTime($this->
groupArray[1]) . "</td><td>" . $this->groupArray[2] . "nm</td><td>$" .
number_format($this->groupArray[3], 2) . "</td></tr> ";
echo "</tbody></table>";
}
/* --Display sortable Pilot stats table-- */
public function displayAircraftStats()
{
echo "<table id=\"aircraftTable\" class=\"tablesorter\"><thead><tr><th>Aircraft Registration</th><th>Make/Model</th><th>Total Flights</th><th>Total Time</th><th>Total Distance</th><th>Total Profit</th></tr></thead><tbody>";
for ($x = 0; $x < count($this->aircraftArray); $x++) {
echo "<tr><td>" . $this->aircraftArray[$x][0] . "</td><td>" . $this->
aircraftArray[$x][1] . "</td><td>" . $this->aircraftArray[$x][2] . "</td><td>" .
$this->formatTime($this->aircraftArray[$x][3]) . "</td><td>" . $this->
aircraftArray[$x][4] . "nm</td><td>$" . number_format($this->aircraftArray[$x][5],
2) . "</td></tr>";
}
echo "</tbody></table> ";
}
/* --Formats time-- */
public function formatTime($minutes)
{
$hours = floor($minutes / 60);
$min = $minutes - ($hours * 60);
$formattedTime = $hours . ":" . $min;
return $formattedTime;
}
}
?>
| linkerovx9/FSELink | fselink.class.php | PHP | gpl-2.0 | 7,357 |
<?php
/**
* @file
* The PHP page that serves all page requests on a Drupal installation.
*
* The routines here dispatch control to the appropriate handler, which then
* prints the appropriate page.
*
* All Drupal code is released under the GNU General Public License.
* See COPYRIGHT.txt and LICENSE.txt.
*/
/**
* Root directory of Drupal installation.
*/
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();
| sagarw/lantra | index.php | PHP | gpl-2.0 | 532 |
package ch.dritz.remedy2redmine;
import java.io.File;
import java.io.IOException;
import ch.dritz.common.Config;
import ch.dritz.remedy2redmine.modules.SyncModule;
/**
* Main class for Remedy2Redmine
* @author D.Ritz
*/
public class Main
{
private static void usage(String msg)
{
if (msg != null)
System.out.println("ERROR: " + msg);
System.out.println("Remedy2Redmine " + Version.getVersion());
System.out.println("Usage: Remedy2Redmine <config.properties> <command> [<command specific args>]");
System.out.println(" <command> : one of (sync)");
System.out.println(" <mode specific args> for each mode:");
System.out.println(" - sync: none");
System.out.println("OR: Remedy2Redmine -version");
System.exit(1);
}
/**
* main() entry point
* @param args
* @throws IOException
*/
public static void main(String[] args)
throws Exception
{
if (args.length == 1 && "-version".equals(args[0])) {
System.out.println("Remedy2Redmine " + Version.getVersion());
return;
}
if (args.length < 2)
usage("Not enough arguments");
File configFile = new File(args[0]);
String command = args[1];
Config config = new Config();
config.loadFromFile(configFile);
if ("sync".equals(command)) {
File syncConfig = new File(configFile.getParentFile(),
config.getString("sync.config", "sync.properties"));
config.loadFromFile(syncConfig);
SyncModule sync = new SyncModule(config);
try {
sync.start();
} finally {
sync.shutdown();
}
} else {
usage("Unknown command");
}
}
}
| dr-itz/redmine_remedy_view | java/src/main/java/ch/dritz/remedy2redmine/Main.java | Java | gpl-2.0 | 1,560 |
<?php
/*------------------------------------------------------------------------
# com_universal_ajaxlivesearch - Universal AJAX Live Search
# ------------------------------------------------------------------------
# author Janos Biro
# copyright Copyright (C) 2011 Offlajn.com. All Rights Reserved.
# @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
# Websites: http://www.offlajn.com
-------------------------------------------------------------------------*/
// No direct access
defined( '_JEXEC' ) or die( 'Restricted access' );
require_once(dirname(__FILE__).DS.'image.php');
class OfflajnImageCaching
{ // BEGIN class OfflajnImageCaching
var $cacheDir;
var $cacheUrl;
function OfflajnImageCaching()
{
$path = JPATH_SITE.DS.'images'.DS.'ajaxsearch'.DS;
if(!is_dir($path)){ mkdir($path);}
$this->cacheDir = $path;
$this->cacheUrl = JURI::root().'images/ajaxsearch/';
}
/*
------------------------------------------------------------------------------
Image methods start
*/
function generateImage($product_full_image, $w, $h, $product_name, $transparent=true){
if( substr( $product_full_image, 0, 4) == "http" ) {
$p = "/".str_replace(array("http","/"),array("http(s{0,1})","\\/"), JURI::base())."/";
$url = preg_replace($p ,JPATH_SITE.DS, $product_full_image);
}else{
$product_full_image = str_replace('%20',' ',$product_full_image);
if (@is_file(JPATH_SITE.DS.$product_full_image)){
$url = JPATH_SITE.DS.$product_full_image;
}elseif(@is_file(IMAGEPATH.'product/'.$product_full_image)){
// VM
$url = IMAGEPATH.'product/'.$product_full_image;
}elseif(@is_file($product_full_image)){
// VM
$url = $product_full_image;
}else{
return;
}
}
$cacheName = $this->generateImageCacheName(array($url, $w, $h));
if(!$this->checkImageCache($cacheName)){
if(!$this->createImage($url, $this->cacheDir.$cacheName, $w, $h, $transparent)){
return '';
}
}
$url = $this->cacheUrl.$cacheName;
return "<img width='".$w."' height='".$h."' alt='".$product_name."' src='".$url."' />";
}
function createImage($in, $out, $w, $h, $transparent){
$img = null;
$img = new OfflajnAJAXImageTool($in);
if($img->res === false){
return false;
}
$img->convertToPng();
if ($transparent) $img->resize($w, $h);
else $img->resize2($w, $h);
$img->write($out);
$img->destroy();
return true;
}
function checkImageCache($cacheName){
return is_file($this->cacheDir.$cacheName);
}
function generateImageCacheName($pieces){
return md5(implode('-', $pieces)).'.png';
}
/*
Image methods end
------------------------------------------------------------------------------
*/
} // END class OfflajnImageCaching
?> | knigherrant/decopatio | components/com_universal_ajax_live_search/helpers/caching.php | PHP | gpl-2.0 | 2,863 |
package com.gilecode.langlocker;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;
/**
* The activator class controls the plug-in life cycle
*/
public class Activator extends AbstractUIPlugin {
// The plug-in ID
public static final String PLUGIN_ID = "com.gilecode.langlocker"; //$NON-NLS-1$
// The shared instance
private static Activator plugin;
/**
* The constructor
*/
public Activator() {
super();
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
* )
*/
public void start(BundleContext context) throws Exception {
super.start(context);
plugin = this;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
* )
*/
public void stop(BundleContext context) throws Exception {
plugin = null;
super.stop(context);
}
/**
* Returns the shared instance
*
* @return the shared instance
*/
public static Activator getDefault() {
return plugin;
}
/**
* Returns an image descriptor for the image file at the given plug-in
* relative path
*
* @param path
* the path
* @return the image descriptor
*/
public static ImageDescriptor getImageDescriptor(String path) {
return imageDescriptorFromPlugin(PLUGIN_ID, path);
}
}
| amogilev/ide-lang-locker | eclipse-plugin/src/com/gilecode/langlocker/Activator.java | Java | gpl-2.0 | 1,423 |
<?php
/*
+---------------------------------------------------------------------------+
| OpenX v2.8 |
| ========== |
| |
| Copyright (c) 2003-2009 OpenX Limited |
| For contact details, see: http://www.openx.org/ |
| |
| This program is free software; you can redistribute it and/or modify |
| it under the terms of the GNU General Public License as published by |
| the Free Software Foundation; either version 2 of the License, or |
| (at your option) any later version. |
| |
| This program is distributed in the hope that it will be useful, |
| but WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License |
| along with this program; if not, write to the Free Software |
| Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
+---------------------------------------------------------------------------+
$Id: BasePublisherService.php 81439 2012-05-07 23:59:14Z chris.nutting $
*/
/**
* @package OpenX
* @author Andriy Petlyovanyy <apetlyovanyy@lohika.com>
*
*/
// Require Publisher Service Implementation
require_once MAX_PATH . '/www/api/v2/xmlrpc/PublisherServiceImpl.php';
/**
* Base Publisher Service
*
*/
class BasePublisherService
{
/**
* Reference to Publisher Service implementation.
*
* @var PublisherServiceImpl $_oPublisherServiceImp
*/
var $_oPublisherServiceImp;
/**
* This method initialises Service implementation object field.
*
*/
function BasePublisherService()
{
$this->_oPublisherServiceImp = new PublisherServiceImpl();
}
}
?> | soeffing/openx_test | www/api/v2/common/BasePublisherService.php | PHP | gpl-2.0 | 2,377 |
/***************************************************************************
qgsgeometryduplicatenodescheck.cpp
---------------------
begin : September 2015
copyright : (C) 2014 by Sandro Mani / Sourcepole AG
email : smani at sourcepole dot 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. *
* *
***************************************************************************/
#include "qgsgeometryduplicatenodescheck.h"
#include "qgsgeometryutils.h"
#include "../utils/qgsfeaturepool.h"
void QgsGeometryDuplicateNodesCheck::collectErrors( QList<QgsGeometryCheckError *> &errors, QStringList &/*messages*/, QAtomicInt *progressCounter, const QgsFeatureIds &ids ) const
{
const QgsFeatureIds &featureIds = ids.isEmpty() ? mFeaturePool->getFeatureIds() : ids;
Q_FOREACH ( QgsFeatureId featureid, featureIds )
{
if ( progressCounter ) progressCounter->fetchAndAddRelaxed( 1 );
QgsFeature feature;
if ( !mFeaturePool->get( featureid, feature ) )
{
continue;
}
QgsGeometry featureGeom = feature.geometry();
QgsAbstractGeometry *geom = featureGeom.geometry();
for ( int iPart = 0, nParts = geom->partCount(); iPart < nParts; ++iPart )
{
for ( int iRing = 0, nRings = geom->ringCount( iPart ); iRing < nRings; ++iRing )
{
int nVerts = QgsGeometryCheckerUtils::polyLineSize( geom, iPart, iRing );
if ( nVerts < 2 )
continue;
for ( int iVert = nVerts - 1, jVert = 0; jVert < nVerts; iVert = jVert++ )
{
QgsPoint pi = geom->vertexAt( QgsVertexId( iPart, iRing, iVert ) );
QgsPoint pj = geom->vertexAt( QgsVertexId( iPart, iRing, jVert ) );
if ( QgsGeometryUtils::sqrDistance2D( pi, pj ) < QgsGeometryCheckPrecision::tolerance() * QgsGeometryCheckPrecision::tolerance() )
{
errors.append( new QgsGeometryCheckError( this, featureid, pj, QgsVertexId( iPart, iRing, jVert ) ) );
}
}
}
}
}
}
void QgsGeometryDuplicateNodesCheck::fixError( QgsGeometryCheckError *error, int method, int /*mergeAttributeIndex*/, Changes &changes ) const
{
QgsFeature feature;
if ( !mFeaturePool->get( error->featureId(), feature ) )
{
error->setObsolete();
return;
}
QgsGeometry featureGeom = feature.geometry();
QgsAbstractGeometry *geom = featureGeom.geometry();
QgsVertexId vidx = error->vidx();
// Check if point still exists
if ( !vidx.isValid( geom ) )
{
error->setObsolete();
return;
}
// Check if error still applies
int nVerts = QgsGeometryCheckerUtils::polyLineSize( geom, vidx.part, vidx.ring );
if ( nVerts == 0 )
{
error->setObsolete();
return;
}
QgsPoint pi = geom->vertexAt( QgsVertexId( vidx.part, vidx.ring, ( vidx.vertex + nVerts - 1 ) % nVerts ) );
QgsPoint pj = geom->vertexAt( error->vidx() );
if ( QgsGeometryUtils::sqrDistance2D( pi, pj ) >= QgsGeometryCheckPrecision::tolerance() * QgsGeometryCheckPrecision::tolerance() )
{
error->setObsolete();
return;
}
// Fix error
if ( method == NoChange )
{
error->setFixed( method );
}
else if ( method == RemoveDuplicates )
{
if ( !QgsGeometryCheckerUtils::canDeleteVertex( geom, vidx.part, vidx.ring ) )
{
error->setFixFailed( tr( "Resulting geometry is degenerate" ) );
}
else if ( !geom->deleteVertex( error->vidx() ) )
{
error->setFixFailed( tr( "Failed to delete vertex" ) );
}
else
{
feature.setGeometry( featureGeom );
mFeaturePool->updateFeature( feature );
error->setFixed( method );
changes[error->featureId()].append( Change( ChangeNode, ChangeRemoved, error->vidx() ) );
}
}
else
{
error->setFixFailed( tr( "Unknown method" ) );
}
}
QStringList QgsGeometryDuplicateNodesCheck::getResolutionMethods() const
{
static QStringList methods = QStringList() << tr( "Delete duplicate node" ) << tr( "No action" );
return methods;
}
| GeoCat/QGIS | src/plugins/geometry_checker/checks/qgsgeometryduplicatenodescheck.cpp | C++ | gpl-2.0 | 4,484 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var Mecab = require('mecab-async');
var mecab = new Mecab();
var MarkovChain = function () {
function MarkovChain(text) {
_classCallCheck(this, MarkovChain);
this.text = text;
this.result = null;
this.dictionary = {};
this.output = 'output';
}
_createClass(MarkovChain, [{
key: 'start',
value: function start(sentence, callback) {
this.parse(sentence, callback);
}
}, {
key: 'parse',
value: function parse(sentence, callback) {
var _this = this;
mecab.parse(this.text, function (err, result) {
_this.dictionary = _this.makeDic(result);
_this.makeSentence(_this.dictionary, sentence);
callback(_this.output);
});
}
}, {
key: 'makeDic',
value: function makeDic(items) {
var tmp = ['@'];
var dic = {};
for (var i in items) {
var t = items[i];
var word = t[0];
word = word.replace(/\s*/, '');
if (word == '' || word == 'EOS') continue;
tmp.push(word);
if (tmp.length < 3) continue;
if (tmp.length > 3) tmp.splice(0, 1);
this.setWord3(dic, tmp);
if (word == '。') {
tmp = ['@'];
continue;
}
}
return dic;
}
}, {
key: 'setWord3',
value: function setWord3(p, s3) {
var w1 = s3[0];
var w2 = s3[1];
var w3 = s3[2];
if (p[w1] == undefined) p[w1] = {};
if (p[w1][w2] == undefined) p[w1][w2] = {};
if (p[w1][w2][w3] == undefined) p[w1][w2][w3] = 0;
p[w1][w2][w3]++;
}
}, {
key: 'makeSentence',
value: function makeSentence(dic, sentence) {
for (var i = 0; i < sentence; i++) {
var ret = [];
var top = dic['@'];
if (!top) continue;
var w1 = this.choiceWord(top);
var w2 = this.choiceWord(top[w1]);
ret.push(w1);
ret.push(w2);
for (;;) {
var w3 = this.choiceWord(dic[w1][w2]);
ret.push(w3);
if (w3 == '。') break;
w1 = w2, w2 = w3;
}
this.output = ret.join('');
return this.output;
}
}
}, {
key: 'objKeys',
value: function objKeys(obj) {
var r = [];
for (var i in obj) {
r.push(i);
}
return r;
}
}, {
key: 'choiceWord',
value: function choiceWord(obj) {
var ks = this.objKeys(obj);
var i = this.rnd(ks.length);
return ks[i];
}
}, {
key: 'rnd',
value: function rnd(num) {
return Math.floor(Math.random() * num);
}
}]);
return MarkovChain;
}();
module.exports = MarkovChain; | uraway/markov-chain-mecab | lib/index.js | JavaScript | gpl-2.0 | 3,365 |
package org.iatoki.judgels.jerahmeel.user.item;
public final class UserItem {
private final String userJid;
private final String itemJid;
private final UserItemStatus status;
public UserItem(String userJid, String itemJid, UserItemStatus status) {
this.userJid = userJid;
this.itemJid = itemJid;
this.status = status;
}
public String getUserJid() {
return userJid;
}
public String getItemJid() {
return itemJid;
}
public UserItemStatus getStatus() {
return status;
}
}
| judgels/jerahmeel | app/org/iatoki/judgels/jerahmeel/user/item/UserItem.java | Java | gpl-2.0 | 567 |
#ifndef SC_BOOST_MPL_BOOL_HPP_INCLUDED
#define SC_BOOST_MPL_BOOL_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Source: /Users/acg/CVSROOT/systemc-2.3/src/sysc/packages/boost/mpl/bool.hpp,v $
// $Date: 2009/10/14 19:11:02 $
// $Revision: 1.2 $
#include <sysc/packages/boost/mpl/bool_fwd.hpp>
#include <sysc/packages/boost/mpl/integral_c_tag.hpp>
#include <sysc/packages/boost/mpl/aux_/config/static_constant.hpp>
SC_BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN
template< bool C_ > struct bool_
{
SC_BOOST_STATIC_CONSTANT(bool, value = C_);
typedef integral_c_tag tag;
typedef bool_ type;
typedef bool value_type;
operator bool() const { return this->value; }
};
#if !defined(SC_BOOST_NO_INCLASS_MEMBER_INITIALIZATION)
template< bool C_ >
bool const bool_<C_>::value;
#endif
SC_BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE
#endif // SC_BOOST_MPL_BOOL_HPP_INCLUDED
| channgo2203/MAG | systemc-2.3.0_modified/src/sysc/packages/boost/mpl/bool.hpp | C++ | gpl-2.0 | 1,115 |
/***************************************************************************
* Copyright (C) 2012 by David Edmundson <kde@davidedmundson.co.uk> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
#include "message-view.h"
#include "adium-theme-view.h"
#include "adium-theme-status-info.h"
#include <KTp/message-processor.h>
#include <KDebug>
#include <KIconLoader>
#include <QLabel>
#include <QResizeEvent>
#include <KTp/Logger/log-manager.h>
#include <KTp/Logger/pending-logger-logs.h>
#include <TelepathyQt/Account>
MessageView::MessageView(QWidget *parent) :
AdiumThemeView(parent),
m_infoLabel(new QLabel(this))
{
loadSettings();
QFont font = m_infoLabel->font();
font.setBold(true);
m_infoLabel->setFont(font);
m_infoLabel->setAlignment(Qt::AlignCenter);
connect(this, SIGNAL(loadFinished(bool)), SLOT(processStoredEvents()));
}
void MessageView::loadLog(const Tp::AccountPtr &account, const KTp::LogEntity &entity,
const Tp::ContactPtr &contact, const QDate &date,
const QPair< QDate, QDate > &nearestDates)
{
if (account.isNull() || !entity.isValid()) {
//note contact can be null
showInfoMessage(i18n("Unknown or invalid contact"));
return;
}
m_infoLabel->hide();
m_account = account;
// FIXME: Workaround for a bug, probably in QGlib which causes that
// m_entity = m_entity results in invalid m_entity->m_class being null
if (m_entity != entity) {
m_entity = entity;
}
m_contact = m_contact.dynamicCast<Tp::Contact>(contact);
m_date = date;
m_prev = nearestDates.first;
m_next = nearestDates.second;
if (entity.entityType() == Tp::HandleTypeRoom) {
load(AdiumThemeView::GroupChat);
} else {
load(AdiumThemeView::SingleUserChat);
}
Tp::Avatar avatar = m_account->avatar();
if (!avatar.avatarData.isEmpty()) {
m_accountAvatar = QString(QLatin1String("data:%1;base64,%2")).
arg(avatar.MIMEType.isEmpty() ? QLatin1String("image/*") : avatar.MIMEType).
arg(QString::fromLatin1(m_account->avatar().avatarData.toBase64().data()));
}
KTp::LogManager *logManager = KTp::LogManager::instance();
KTp::PendingLoggerLogs *pendingLogs = logManager->queryLogs(m_account, m_entity, m_date);
connect(pendingLogs, SIGNAL(finished(KTp::PendingLoggerOperation*)), SLOT(onEventsLoaded(KTp::PendingLoggerOperation*)));
}
void MessageView::showInfoMessage(const QString& message)
{
m_infoLabel->setText(message);
m_infoLabel->show();
m_infoLabel->raise();
m_infoLabel->setGeometry(0, 0, width(), height());
}
void MessageView::resizeEvent(QResizeEvent* e)
{
m_infoLabel->setGeometry(0, 0, e->size().width(), e->size().height());
QWebView::resizeEvent(e);
}
void MessageView::setHighlightText(const QString &text)
{
m_highlightedText = text;
}
void MessageView::clearHighlightText()
{
setHighlightText(QString());
}
void MessageView::onEventsLoaded(KTp::PendingLoggerOperation *po)
{
KTp::PendingLoggerLogs *pl = qobject_cast<KTp::PendingLoggerLogs*>(po);
m_events << pl->logs();
/* Wait with initialization for the first event so that we can know when the chat session started */
AdiumThemeHeaderInfo headerInfo;
headerInfo.setDestinationDisplayName(m_contact.isNull() ? m_entity.alias() : m_contact->alias());
headerInfo.setChatName(m_contact.isNull() ? m_entity.alias() : m_contact->alias());
headerInfo.setGroupChat(m_entity.entityType() == Tp::HandleTypeRoom);
headerInfo.setSourceName(m_account->displayName());
headerInfo.setIncomingIconPath(m_contact.isNull() ? QString() : m_contact->avatarData().fileName);
headerInfo.setService(m_account->serviceName());
// check iconPath docs for minus sign in -KIconLoader::SizeMedium
headerInfo.setServiceIconPath(KIconLoader::global()->iconPath(m_account->iconName(), -KIconLoader::SizeMedium));
if (pl->logs().count() > 0) {
headerInfo.setTimeOpened(pl->logs().first().time());
}
initialise(headerInfo);
}
bool logMessageOlderThan(const KTp::LogMessage &e1, const KTp::LogMessage &e2)
{
return e1.time() < e2.time();
}
bool logMessageNewerThan(const KTp::LogMessage &e1, const KTp::LogMessage &e2)
{
return e1.time() > e2.time();
}
void MessageView::processStoredEvents()
{
AdiumThemeStatusInfo prevConversation;
if (m_prev.isValid()) {
prevConversation = AdiumThemeStatusInfo(AdiumThemeMessageInfo::HistoryStatus);
prevConversation.setMessage(QString(QLatin1String("<a href=\"#x-prevConversation\"><<< %1</a>")).arg(i18n("Older conversation")));
prevConversation.setTime(QDateTime(m_prev));
}
AdiumThemeStatusInfo nextConversation;
if (m_next.isValid()) {
nextConversation = AdiumThemeStatusInfo(AdiumThemeMessageInfo::HistoryStatus);
nextConversation.setMessage(QString(QLatin1String("<a href=\"#x-nextConversation\">%1 >>></a>")).arg(i18n("Newer conversation")));
nextConversation.setTime(QDateTime(m_next));
}
if (m_sortMode == MessageView::SortOldestTop) {
if (m_prev.isValid()) {
addAdiumStatusMessage(nextConversation);
}
qSort(m_events.begin(), m_events.end(), logMessageOlderThan);
} else if (m_sortMode == MessageView::SortNewestTop) {
if (m_next.isValid()) {
addAdiumStatusMessage(prevConversation);
}
qSort(m_events.begin(), m_events.end(), logMessageNewerThan);
}
if (m_events.isEmpty()) {
showInfoMessage(i18n("There are no logs for this day"));
}
while (!m_events.isEmpty()) {
const KTp::LogMessage msg = m_events.takeFirst();
KTp::MessageContext ctx(m_account, Tp::TextChannelPtr());
KTp::Message message = KTp::MessageProcessor::instance()->processIncomingMessage(msg, ctx);
addMessage(message);
}
if (m_sortMode == MessageView::SortOldestTop && m_next.isValid()) {
addAdiumStatusMessage(prevConversation);
} else if (m_sortMode == MessageView::SortNewestTop && m_prev.isValid()) {
addAdiumStatusMessage(nextConversation);
}
/* Can't highlight the text directly, we need to wait for the JavaScript in
* AdiumThemeView to include the log messages into DOM. */
QTimer::singleShot(100, this, SLOT(doHighlightText()));
}
void MessageView::onLinkClicked(const QUrl &link)
{
// Don't emit the signal directly, KWebView does not like when we reload the
// page from an event handler (and then chain up) and we can't guarantee
// that everyone will use QueuedConnection when connecting to
// conversationSwitchRequested() slot
if (link.fragment() == QLatin1String("x-nextConversation")) {
// Q_EMIT conversationSwitchRequested(m_next)
QMetaObject::invokeMethod(this, "conversationSwitchRequested", Qt::QueuedConnection,
Q_ARG(QDate, m_next));
return;
}
if (link.fragment() == QLatin1String("x-prevConversation")) {
// Q_EMIT conversationSwitchRequested(m_prev)
QMetaObject::invokeMethod(this, "conversationSwitchRequested", Qt::QueuedConnection,
Q_ARG(QDate, m_prev));
return;
}
AdiumThemeView::onLinkClicked(link);
}
void MessageView::loadSettings()
{
const KConfig config(QLatin1String("ktelepathyrc"));
const KConfigGroup group = config.group("LogViewer");
m_sortMode = static_cast<SortMode>(group.readEntry("SortMode", static_cast<int>(SortOldestTop)));
}
void MessageView::reloadTheme()
{
loadSettings();
loadLog(m_account, m_entity, m_contact, m_date, qMakePair(m_prev, m_next));
}
void MessageView::doHighlightText()
{
findText(QString());
if (!m_highlightedText.isEmpty()) {
findText(m_highlightedText, QWebPage::HighlightAllOccurrences |
QWebPage::FindWrapsAroundDocument);
}
}
| Ziemin/ktp-text-ui | logviewer/message-view.cpp | C++ | gpl-2.0 | 9,205 |
field_dict={'ROME-FIELD-01':[ 267.835895375 , -30.0608178195 , '17:51:20.6149','-30:03:38.9442' ],
'ROME-FIELD-02':[ 269.636745458 , -27.9782661111 , '17:58:32.8189','-27:58:41.758' ],
'ROME-FIELD-03':[ 268.000049542 , -28.8195573333 , '17:52:00.0119','-28:49:10.4064' ],
'ROME-FIELD-04':[ 268.180171708 , -29.27851275 , '17:52:43.2412','-29:16:42.6459' ],
'ROME-FIELD-05':[ 268.35435 , -30.2578356389 , '17:53:25.044','-30:15:28.2083' ],
'ROME-FIELD-06':[ 268.356124833 , -29.7729819283 , '17:53:25.47','-29:46:22.7349' ],
'ROME-FIELD-07':[ 268.529571333 , -28.6937071111 , '17:54:07.0971','-28:41:37.3456' ],
'ROME-FIELD-08':[ 268.709737083 , -29.1867251944 , '17:54:50.3369','-29:11:12.2107' ],
'ROME-FIELD-09':[ 268.881108542 , -29.7704673333 , '17:55:31.4661','-29:46:13.6824' ],
'ROME-FIELD-10':[ 269.048498333 , -28.6440675 , '17:56:11.6396','-28:38:38.643' ],
'ROME-FIELD-11':[ 269.23883225 , -29.2716684211 , '17:56:57.3197','-29:16:18.0063' ],
'ROME-FIELD-12':[ 269.39478875 , -30.0992361667 , '17:57:34.7493','-30:05:57.2502' ],
'ROME-FIELD-13':[ 269.563719375 , -28.4422328996 , '17:58:15.2927','-28:26:32.0384' ],
'ROME-FIELD-14':[ 269.758843 , -29.1796030365 , '17:59:02.1223','-29:10:46.5709' ],
'ROME-FIELD-15':[ 269.78359875 , -29.63940425 , '17:59:08.0637','-29:38:21.8553' ],
'ROME-FIELD-16':[ 270.074981708 , -28.5375585833 , '18:00:17.9956','-28:32:15.2109' ],
'ROME-FIELD-17':[ 270.81 , -28.0978333333 , '18:03:14.4','-28:05:52.2' ],
'ROME-FIELD-18':[ 270.290886667 , -27.9986032778 , '18:01:09.8128','-27:59:54.9718' ],
'ROME-FIELD-19':[ 270.312763708 , -29.0084241944 , '18:01:15.0633','-29:00:30.3271' ],
'ROME-FIELD-20':[ 270.83674125 , -28.8431573889 , '18:03:20.8179','-28:50:35.3666' ]}
| ytsapras/robonet_site | scripts/rome_fields_dict.py | Python | gpl-2.0 | 1,964 |
<?php
include("config_mynonprofit.php");
include("connect.php");
//Start session
session_start();
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Sanitize the POST values
$fname = htmlentities($_POST['fname']);
$lname = htmlentities($_POST['lname']);
$email = htmlentities($_POST['email']);
$username = htmlentities($_POST['username']);
$member_type = htmlentities($_POST['member_type']);
$password = htmlentities($_POST['password']);
$cpassword = htmlentities($_POST['cpassword']);
$today = date('Y-m-d H:i:s');
$hash = md5($today);
//Input Validations
if ($fname == '') {
$errmsg_arr[] = 'First name missing';
$errflag = true;
}
if ($lname == '') {
$errmsg_arr[] = 'Last name missing';
$errflag = true;
}
if ($email == '') {
$errmsg_arr[] = 'Email missing';
$errflag = true;
}
if ($username == '') {
$errmsg_arr[] = 'Username missing';
$errflag = true;
}
if ($password == '') {
$errmsg_arr[] = 'Password missing';
$errflag = true;
}
if ($cpassword == '') {
$errmsg_arr[] = 'Confirm password missing';
$errflag = true;
}
if (strcmp($password, $cpassword) != 0) {
$errmsg_arr[] = 'Passwords do not match';
$errflag = true;
}
//Check for duplicate username
if ($username != '') {
$query = $db->prepare('SELECT * FROM members WHERE username=:username');
$query->execute(array('username' => $username));
if ($query->rowCount() > 0) {
$errmsg_arr[] = 'Username already in use';
$errflag = true;
}
}
//If there are input validations, redirect back to the registration form
if ($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: registration.php");
exit();
}
$password2 = md5($password);
if ($member_type != 'General') {
$to = 'ruthwitte@gmail.com, bjwitte@gmail.com';
$subject = 'New member requesting membership type.';
$body = 'New member ' . $username . ' ' . $fname . ' ' . $lname . ' ' . $email . ' requesting membership type of ' . $member_type . '';
$headers = "From: mygp@growingplaces.cc\r\n" .
mail($to, $subject, $body, $headers);
}
//Create INSERT query
$query2 = $db->prepare('INSERT INTO members(firstname, lastname, email, username, password, date_registered, member_type, confirm_hash, auth_type) VALUES(:fname,:lname,:email,:username,:password,:today ,"General",:hash, 0)');
$result = $query2->execute(array('fname' => $fname, 'lname' => $lname, 'email' => $email, 'username' => $username, 'password' => $password2, 'today' => $today, 'hash' => $hash));
$member_id = $db->lastInsertId('member_id');
if (is_array($_POST['volunteertypes'])) {
$query4 = $db->prepare('INSERT INTO volunteer_types_by_member (volunteer_type_id, member_id) VALUES (:checked ,:member_id)');
foreach ($_POST['volunteertypes'] as $checked) {
$query4->execute(array('checked' => $checked, 'member_id' => $member_id));
}
}
//Check whether the query was successful or not
if ($result) {
$to = $email;
$subject = "" . $site_name . " Confirmation";
$message = "<html><head><title>" . $site_name . " Confirmation</title></head><body><p> Click the following link to confirm your registration information.</p><a href='http://www.growingplaces.cc/mygp/confirm.php?confirm=" . $hash . "'>http://www.growingplaces.cc/mygp/confirm.php?confirm=" . $hash . "</a>";
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "From: mygp@growingplaces.cc\r\n";
$mailed = mail($to, $subject, $message, $headers);
header("location: register-success.php");
exit();
} else {
die("Query failed");
}
?> | Enjabain/My-NP | register-exec.php | PHP | gpl-2.0 | 3,724 |
<script type="text/javascript">
jQuery(document).ready(function() {
// type of media
jQuery('#type').change(function() {
switch (jQuery(this).val()) {
case '<?php echo MEDIA_TYPE_EMAIL; ?>':
jQuery('#smtp_server, #smtp_helo, #smtp_email').closest('li').removeClass('hidden');
jQuery('#exec_path, #gsm_modem, #jabber_username, #eztext_username, #eztext_limit, #passwd')
.closest('li')
.addClass('hidden');
jQuery('#eztext_link').addClass('hidden');
break;
case '<?php echo MEDIA_TYPE_EXEC; ?>':
jQuery('#exec_path').closest('li').removeClass('hidden');
jQuery('#smtp_server, #smtp_helo, #smtp_email, #gsm_modem, #jabber_username, #eztext_username, #eztext_limit, #passwd')
.closest('li')
.addClass('hidden');
jQuery('#eztext_link').addClass('hidden');
break;
case '<?php echo MEDIA_TYPE_SMS; ?>':
jQuery('#gsm_modem').closest('li').removeClass('hidden');
jQuery('#smtp_server, #smtp_helo, #smtp_email, #exec_path, #jabber_username, #eztext_username, #eztext_limit, #passwd')
.closest('li')
.addClass('hidden');
jQuery('#eztext_link').addClass('hidden');
break;
case '<?php echo MEDIA_TYPE_JABBER; ?>':
jQuery('#jabber_username, #passwd').closest('li').removeClass('hidden');
jQuery('#smtp_server, #smtp_helo, #smtp_email, #exec_path, #gsm_modem, #eztext_username, #eztext_limit')
.closest('li')
.addClass('hidden');
jQuery('#eztext_link').addClass('hidden');
break;
case '<?php echo MEDIA_TYPE_EZ_TEXTING; ?>':
jQuery('#eztext_username, #eztext_limit, #passwd').closest('li').removeClass('hidden');
jQuery('#eztext_link').removeClass('hidden');
jQuery('#smtp_server, #smtp_helo, #smtp_email, #exec_path, #gsm_modem, #jabber_username')
.closest('li')
.addClass('hidden');
break;
}
});
// clone button
jQuery('#clone').click(function() {
jQuery('#mediatypeid, #delete, #clone').remove();
jQuery('#update span').text(<?php echo CJs::encodeJson(_('Add')); ?>);
jQuery('#update').val('mediatype.create').attr({id: 'add'});
jQuery('#cancel').addClass('ui-corner-left');
jQuery('#description').focus();
});
// trim spaces on sumbit
jQuery('#mediaTypeForm').submit(function() {
jQuery('#description').val(jQuery.trim(jQuery('#description').val()));
jQuery('#smtp_server').val(jQuery.trim(jQuery('#smtp_server').val()));
jQuery('#smtp_helo').val(jQuery.trim(jQuery('#smtp_helo').val()));
jQuery('#smtp_email').val(jQuery.trim(jQuery('#smtp_email').val()));
jQuery('#exec_path').val(jQuery.trim(jQuery('#exec_path').val()));
jQuery('#gsm_modem').val(jQuery.trim(jQuery('#gsm_modem').val()));
jQuery('#jabber_username').val(jQuery.trim(jQuery('#jabber_username').val()));
jQuery('#eztext_username').val(jQuery.trim(jQuery('#eztext_username').val()));
});
// refresh field visibility on document load
jQuery('#type').trigger('change');
});
</script>
| TamasSzerb/zabbix | frontends/php/app/views/administration.mediatype.edit.js.php | PHP | gpl-2.0 | 2,993 |
/**************************************************
* Funkcje związane z geolokalizacją GPS
**************************************************/
WMB.Comment = {
/**
* Funkcja dodająca nowy komentarz do zgłoszenia
*
* @method onAddSubmit
*/
onAddSubmit: function(marker_id) {
if (WMB.User.isLoggedIn()) {
if ($('#add-comment-form')[0].checkValidity()) {
var post_data = new FormData();
post_data.append('user_id', parseInt(getCookie('user_id')));
post_data.append('marker_id', parseInt(marker_id));
post_data.append('comment', $('#comment').val());
$.ajax({
url: REST_API_URL + 'comment',
beforeSend: function(request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: post_data,
success: function(s) {
$('#add-comment-modal').modal('hide');
bootbox.alert('Pomyślnie dodaną komentarz.', function() {
location.reload();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('#add-comment-modal').modal('hide');
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message);
}
});
}
} else {
bootbox.alert('Aby móc dodawać komentarze musisz być zalogowany.');
}
},
onEditClick: function(id) {
// Pobranie danych o komentarzu
$.ajax({
url: REST_API_URL + 'comment/id/' + id,
type: 'GET',
success: function(data) {
// Wstawienie danych do formularza
$('#comment_id').val(id);
$('#comment').val(data.comment);
$('#edit-comment-modal').modal('show');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
},
onEditSubmit: function() {
if ($('#edit-comment-form')[0].checkValidity()) {
var comment_data = new FormData(),
comment_id = parseInt($('#comment_id').val()),
comment = $('#comment').val();
comment_data.append('comment', comment);
$.ajax({
url: REST_API_URL + 'comment/id/' + comment_id + '/edit',
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'POST',
cache: false,
processData: false,
contentType: false,
data: comment_data,
success: function(s) {
$('#edit-comment-modal').modal('hide');
bootbox.alert('Pomyślnie zedytowano komentarz.', function() {
window.location.href = WEBSITE_URL + 'comments';
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message);
}
});
}
},
onDeleteClick: function(id) {
$.ajax({
url: REST_API_URL + 'comment/id/' + id,
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'DELETE',
cache: false,
processData: false,
contentType: false,
success: function(data) {
$('#edit-comment-modal').modal('hide');
bootbox.alert('Pomyślnie usunięto komentarz.', function() {
location.reload();
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
},
/**
* Funkcja służąca do zmiany statusu komentarza
*
* @method changeStatus
* @param {Integer} id Identyfikator komentarza
* @param {Integer} status_id Identyfikator statusu
*/
changeStatus: function(id, status_id) {
if (WMB.User.isLoggedIn()) {
$.ajax({
url: REST_API_URL + 'comment/id/' + id + '/status/' + status_id,
beforeSend: function (request) {
request.setRequestHeader('Authorization', 'Token ' + getCookie('token'));
},
type: 'PUT',
cache: false,
processData: false,
contentType: false,
success: function(data) {
if (status_id == 0) {
bootbox.alert('Pomyślnie zgłoszono nadużycie w komentarzu.', function() {
location.reload();
});
} else {
bootbox.alert('Pomyślnie zmieniono status komentarza na ' + comment_statuses[status_id] + '.', function() {
location.reload();
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var response = JSON.parse(XMLHttpRequest.responseText);
bootbox.alert(response.message, function() {
window.location.href = WEBSITE_URL;
});
}
});
} else {
bootbox.alert('Aby zgłosić nadużycie musisz być zalogowany/a.');
}
},
/**
* Funkcja pobierająca wszystkie komentarze dla danego zgłoszenia
*
* @method getAll
* @param {Integer} marker_id Identyfikator zgłoszenia
*/
getAll: function(marker_id) {
$.ajax({
url: REST_API_URL + 'comment/marker/' + marker_id,
type: 'GET',
cache: false,
dataType: 'json',
success: function(data) {
$.each(data.comments, function(i) {
if (data.comments[i].status_id != 0 && data.comments[i].user_id == parseInt(getCookie('user_id'))) {
$('#marker-comment-list').append(
'<tr>' +
'<td>' + data.comments[i].login + '</td>' +
'<td>' + data.comments[i].date + '</td>' +
'<td>' + data.comments[i].comment + '</td>' +
'<td>brak</td>' +
'</tr>');
} else if (data.comments[i].status_id != 0) {
$('#marker-comment-list').append(
'<tr>' +
'<td>' + data.comments[i].login + '</td>' +
'<td>' + data.comments[i].date + '</td>' +
'<td>' + data.comments[i].comment + '</td>' +
'<td><a href="#" onclick="WMB.Comment.changeStatus(' + data.comments[i].comment_id + ', 0)">Zgłoś nadużycie</a></td>' +
'</tr>');
}
});
}
});
}
} | airwaves-pl/WroclawskaMapaBarier | web/lib/js/wmb.comment.js | JavaScript | gpl-2.0 | 5,969 |
<?php
/**
*
* Share On extension for the phpBB Forum Software package.
*
* @copyright (c) 2015 Vinny <https://github.com/vinny>
* @license GNU General Public License, version 2 (GPL-2.0)
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
//
// Some characters you may want to copy&paste:
// ’ » “ ” …
//
$lang = array_merge($lang, array(
'SO_SELECT' => 'Κοινοποίηση στο',
'SHARE_TOPIC' => 'Κοινοποίηση αυτού του θέματος στο',
'SHARE_POST' => 'Κοινοποίηση αυτής της απάντησης στο',
// Share On viewtopic.php
'SHARE_ON_FACEBOOK' => 'Κοινοποίηση στο Facebook',
'SHARE_ON_TWITTER' => 'Κοινοποίηση στο Twitter',
'SHARE_ON_TUENTI' => 'Κοινοποίηση στο Tuenti',
'SHARE_ON_DIGG' => 'Κοινοποίηση στο Digg',
'SHARE_ON_REDDIT' => 'Κοινοποίηση στο Reddit',
'SHARE_ON_DELICIOUS' => 'Κοινοποίηση στο Delicious',
'SHARE_ON_VK' => 'Κοινοποίηση στο VK',
'SHARE_ON_TUMBLR' => 'Κοινοποίηση στο Tumblr',
'SHARE_ON_GOOGLE' => 'Κοινοποίηση στο Google+',
'SHARE_ON_WHATSAPP' => 'Κοινοποίηση στο Whatsapp',
'SHARE_ON_POCKET' => 'Κοινοποίηση στο Pocket',
));
| vinny/share-on | language/el/shareon.php | PHP | gpl-2.0 | 1,990 |
# -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.selector import Selector
from kgrants.items import KgrantsItem
from scrapy.http import Request
import time
class GrantsSpider(Spider):
name = "grants"
allowed_domains = ["www.knightfoundation.org"]
pages = 1
base_url = 'http://www.knightfoundation.org'
start_url_str = 'http://www.knightfoundation.org/grants/?sort=title&page=%s'
def __init__(self, pages=None, *args, **kwargs):
super(GrantsSpider, self).__init__(*args, **kwargs)
if pages is not None:
self.pages = pages
self.start_urls = [ self.start_url_str % str(page) for page in xrange(1,int(self.pages)+1)]
def parse(self, response):
hxs = Selector(response)
projects = hxs.xpath('//article')
for project in projects:
time.sleep(2)
project_url = self.base_url + ''.join(project.xpath('a/@href').extract())
grants = KgrantsItem()
grants['page'] = project_url
grants['project'] = ''.join(project.xpath('a/div/header/h1/text()').extract()).strip()
grants['description'] = ''.join(project.xpath('p/text()').extract()).strip()
yield Request(grants['page'],
callback = self.parse_project,
meta={'grants':grants})
def parse_project(self,response):
hxs = Selector(response)
grants = response.meta['grants']
details = hxs.xpath('//section[@id="grant_info"]')
fields = hxs.xpath('//dt')
values = hxs.xpath('//dd')
self.log('field: <%s>' % fields.extract())
for item in details:
grants['fiscal_agent'] = ''.join(item.xpath('header/h2/text()').extract()).strip()
count = 0
for field in fields:
normalized_field = ''.join(field.xpath('text()').extract()).strip().lower().replace(' ','_')
self.log('field: <%s>' % normalized_field)
try:
grants[normalized_field] = values.xpath('text()').extract()[count]
except:
if normalized_field == 'community':
grants[normalized_field] = values.xpath('a/text()').extract()[1]
elif normalized_field == 'focus_area':
grants[normalized_field] = values.xpath('a/text()').extract()[0]
count += 1
grants['grantee_contact_email'] = ''.join(
item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/@href').extract()).replace('mailto:','').strip()
grants['grantee_contact_name'] = ''.join(
item.xpath('section[@id="grant_contact"]/ul/li[@class="email"]/a/text()').extract()).strip()
grants['grantee_contact_location'] = ''.join(
item.xpath('section[@id="grant_contact"]/ul/li[@class="location"]/text()').extract()).strip()
grants['grantee_contact_facebook'] = ''.join(
item.xpath('section[@id="grant_contact"]/ul/li[@class="facebook"]/a/@href').extract()).strip()
grants['grantee_contact_twitter'] = item.xpath('section[@id="grant_contact"]/ul/li[@class="twitter"]/a/@href').extract()
grants['grantee_contact_website'] = item.xpath('section[@id="grant_contact"]/ul/li[@class="website"]/a/@href').extract()
if 'grant_period' in grants:
grant_period = grants['grant_period'].split(' to ')
grants['grant_period_start'] = grant_period[0]
grants['grant_period_end'] = grant_period[1]
yield grants
| poderomedia/kfdata | kgrants/spiders/grants.py | Python | gpl-2.0 | 3,682 |
/**
*
*/
package co.innovate.rentavoz.services.almacen.impl;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import co.innovate.rentavoz.model.Tercero;
import co.innovate.rentavoz.model.almacen.Cuota;
import co.innovate.rentavoz.model.almacen.venta.Venta;
import co.innovate.rentavoz.repositories.GenericRepository;
import co.innovate.rentavoz.repositories.almacen.CuotaDao;
import co.innovate.rentavoz.services.almacen.CuotaService;
import co.innovate.rentavoz.services.impl.GenericServiceImpl;
/**
* @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* @project rentavoz3
* @class CuotaServiceImpl
* @date 7/02/2014
*
*/
@Service("cuotaService")
public class CuotaServiceImpl extends GenericServiceImpl<Cuota, Integer> implements CuotaService,Serializable {
/**
* 7/02/2014
* @author <a href="mailto:elmerdiazlazo@gmail.com">Elmer Jose Diaz Lazo</a>
* serialVersionUID
*/
private static final long serialVersionUID = 1L;
@Autowired
private CuotaDao cuotaDao;
/* (non-Javadoc)
* @see co.innovate.rentavoz.services.impl.GenericServiceImpl#getDao()
*/
@Override
public GenericRepository<Cuota, Integer> getDao() {
return cuotaDao;
}
/* (non-Javadoc)
* @see co.innovate.rentavoz.services.almacen.CuotaService#buscarCuotasPendientesPorCliente(co.innovate.rentavoz.model.Tercero)
*/
@Override
public List<Cuota> buscarCuotasPendientesPorCliente(Tercero cliente) {
return cuotaDao.buscarCuotasPendientesPorCliente(cliente);
}
/* (non-Javadoc)
* @see co.innovate.rentavoz.services.almacen.CuotaService#buscarRutaDeCuotasPorCobrador(co.innovate.rentavoz.model.Tercero)
*/
@Override
public List<Cuota> buscarRutaDeCuotasPorCobrador(Tercero cobrador) {
return cuotaDao.buscarRutaDeCuotasPorCobrador(cobrador);
}
/* (non-Javadoc)
* @see co.innovate.rentavoz.services.almacen.CuotaService#findByVenta(co.innovate.rentavoz.model.almacen.venta.Venta)
*/
@Override
public List<Cuota> findByVenta(Venta venta) {
return cuotaDao.findByVenta(venta);
}
/* (non-Javadoc)
* @see co.innovate.rentavoz.services.almacen.CuotaService#findDeudoresMorosos(java.util.Date)
*/
@Override
public List<Tercero> findDeudoresMorosos(Date fechaCierre) {
return cuotaDao.findDeudoresMorosos(fechaCierre);
}
}
| kaisenlean/rentavoz3 | src/main/java/co/innovate/rentavoz/services/almacen/impl/CuotaServiceImpl.java | Java | gpl-2.0 | 2,414 |
;(function() {
/** Used to access the Firebug Lite panel (set by `run`). */
var fbPanel;
/** Used as a safe reference for `undefined` in pre ES5 environments. */
var undefined;
/** Used as a reference to the global object. */
var root = typeof global == 'object' && global || this;
/** Method and object shortcuts. */
var phantom = root.phantom,
amd = root.define && define.amd,
argv = root.process && process.argv,
document = !phantom && root.document,
noop = function() {},
params = root.arguments,
system = root.system;
/** Add `console.log()` support for Narwhal, Rhino, and RingoJS. */
var console = root.console || (root.console = { 'log': root.print });
/** The file path of the Lo-Dash file to test. */
var filePath = (function() {
var min = 0,
result = [];
if (phantom) {
result = params = phantom.args;
} else if (system) {
min = 1;
result = params = system.args;
} else if (argv) {
min = 2;
result = params = argv;
} else if (params) {
result = params;
}
var last = result[result.length - 1];
result = (result.length > min && !/perf(?:\.js)?$/.test(last)) ? last : '../lodash.js';
if (!amd) {
try {
result = require('fs').realpathSync(result);
} catch(e) {}
try {
result = require.resolve(result);
} catch(e) {}
}
return result;
}());
/** Used to match path separators. */
var rePathSeparator = /[\/\\]/;
/** Used to detect primitive types. */
var rePrimitive = /^(?:boolean|number|string|undefined)$/;
/** Used to match RegExp special characters. */
var reSpecialChars = /[.*+?^=!:${}()|[\]\/\\]/g;
/** The `ui` object. */
var ui = root.ui || (root.ui = {
'buildPath': basename(filePath, '.js'),
'otherPath': 'underscore'
});
/** The Lo-Dash build basename. */
var buildName = root.buildName = basename(ui.buildPath, '.js');
/** The other library basename. */
var otherName = root.otherName = (function() {
var result = basename(ui.otherPath, '.js');
return result + (result == buildName ? ' (2)' : '');
}());
/** Used to score performance. */
var score = { 'a': [], 'b': [] };
/** Used to queue benchmark suites. */
var suites = [];
/** Used to resolve a value's internal [[Class]]. */
var toString = Object.prototype.toString;
/** Detect if in a browser environment. */
var isBrowser = isHostType(root, 'document') && isHostType(root, 'navigator');
/** Detect if in a Java environment. */
var isJava = !isBrowser && /Java/.test(toString.call(root.java));
/** Use a single "load" function. */
var load = (typeof require == 'function' && !amd)
? require
: (isJava && root.load) || noop;
/** Load Lo-Dash. */
var lodash = root.lodash || (root.lodash = (
lodash = load(filePath) || root._,
lodash = lodash._ || lodash,
(lodash.runInContext ? lodash.runInContext(root) : lodash),
lodash.noConflict()
));
/** Load Benchmark.js. */
var Benchmark = root.Benchmark || (root.Benchmark = (
Benchmark = load('../vendor/benchmark.js/benchmark.js') || root.Benchmark,
Benchmark = Benchmark.Benchmark || Benchmark,
Benchmark.runInContext(lodash.extend({}, root, { '_': lodash }))
));
/** Load Underscore. */
var _ = root._ || (root._ = (
_ = load('../vendor/underscore/underscore.js') || root._,
_._ || _
));
/*--------------------------------------------------------------------------*/
/**
* Gets the basename of the given `filePath`. If the file `extension` is passed,
* it will be removed from the basename.
*
* @private
* @param {string} path The file path to inspect.
* @param {string} extension The extension to remove.
* @returns {string} Returns the basename.
*/
function basename(filePath, extension) {
var result = (filePath || '').split(rePathSeparator).pop();
return (arguments.length < 2)
? result
: result.replace(RegExp(extension.replace(reSpecialChars, '\\$&') + '$'), '');
}
/**
* Computes the geometric mean (log-average) of an array of values.
* See http://en.wikipedia.org/wiki/Geometric_mean#Relationship_with_arithmetic_mean_of_logarithms.
*
* @private
* @param {Array} array The array of values.
* @returns {number} The geometric mean.
*/
function getGeometricMean(array) {
return Math.pow(Math.E, lodash.reduce(array, function(sum, x) {
return sum + Math.log(x);
}, 0) / array.length) || 0;
}
/**
* Gets the Hz, i.e. operations per second, of `bench` adjusted for the
* margin of error.
*
* @private
* @param {Object} bench The benchmark object.
* @returns {number} Returns the adjusted Hz.
*/
function getHz(bench) {
var result = 1 / (bench.stats.mean + bench.stats.moe);
return isFinite(result) ? result : 0;
}
/**
* Host objects can return type values that are different from their actual
* data type. The objects we are concerned with usually return non-primitive
* types of "object", "function", or "unknown".
*
* @private
* @param {*} object The owner of the property.
* @param {string} property The property to check.
* @returns {boolean} Returns `true` if the property value is a non-primitive, else `false`.
*/
function isHostType(object, property) {
if (object == null) {
return false;
}
var type = typeof object[property];
return !rePrimitive.test(type) && (type != 'object' || !!object[property]);
}
/**
* Logs text to the console.
*
* @private
* @param {string} text The text to log.
*/
function log(text) {
console.log(text + '');
if (fbPanel) {
// Scroll the Firebug Lite panel down.
fbPanel.scrollTop = fbPanel.scrollHeight;
}
}
/**
* Runs all benchmark suites.
*
* @private (@public in the browser)
*/
function run() {
fbPanel = (fbPanel = root.document && document.getElementById('FirebugUI')) &&
(fbPanel = (fbPanel = fbPanel.contentWindow || fbPanel.contentDocument).document || fbPanel) &&
fbPanel.getElementById('fbPanel1');
log('\nSit back and relax, this may take a while.');
suites[0].run({ 'async': !isJava });
}
/*--------------------------------------------------------------------------*/
lodash.extend(Benchmark.Suite.options, {
'onStart': function() {
log('\n' + this.name + ':');
},
'onCycle': function(event) {
log(event.target);
},
'onComplete': function() {
for (var index = 0, length = this.length; index < length; index++) {
var bench = this[index];
if (bench.error) {
var errored = true;
}
}
if (errored) {
log('There was a problem, skipping...');
}
else {
var formatNumber = Benchmark.formatNumber,
fastest = this.filter('fastest'),
fastestHz = getHz(fastest[0]),
slowest = this.filter('slowest'),
slowestHz = getHz(slowest[0]),
aHz = getHz(this[0]),
bHz = getHz(this[1]);
if (fastest.length > 1) {
log('It\'s too close to call.');
aHz = bHz = slowestHz;
}
else {
var percent = ((fastestHz / slowestHz) - 1) * 100;
log(
fastest[0].name + ' is ' +
formatNumber(percent < 1 ? percent.toFixed(2) : Math.round(percent)) +
'% faster.'
);
}
// Add score adjusted for margin of error.
score.a.push(aHz);
score.b.push(bHz);
}
// Remove current suite from queue.
suites.shift();
if (suites.length) {
// Run next suite.
suites[0].run({ 'async': !isJava });
}
else {
var aMeanHz = getGeometricMean(score.a),
bMeanHz = getGeometricMean(score.b),
fastestMeanHz = Math.max(aMeanHz, bMeanHz),
slowestMeanHz = Math.min(aMeanHz, bMeanHz),
xFaster = fastestMeanHz / slowestMeanHz,
percentFaster = formatNumber(Math.round((xFaster - 1) * 100)),
message = 'is ' + percentFaster + '% ' + (xFaster == 1 ? '' : '(' + formatNumber(xFaster.toFixed(2)) + 'x) ') + 'faster than';
// Report results.
if (aMeanHz >= bMeanHz) {
log('\n' + buildName + ' ' + message + ' ' + otherName + '.');
} else {
log('\n' + otherName + ' ' + message + ' ' + buildName + '.');
}
}
}
});
/*--------------------------------------------------------------------------*/
lodash.extend(Benchmark.options, {
'async': true,
'setup': '\
var _ = global._,\
lodash = global.lodash,\
belt = this.name == buildName ? lodash : _;\
\
var date = new Date,\
limit = 20,\
regexp = /x/,\
object = {},\
objects = Array(limit),\
numbers = Array(limit),\
fourNumbers = [5, 25, 10, 30],\
nestedNumbers = [1, [2], [3, [[4]]]],\
nestedObjects = [{}, [{}], [{}, [[{}]]]],\
twoNumbers = [12, 23];\
\
for (var index = 0; index < limit; index++) {\
numbers[index] = index;\
object["key" + index] = index;\
objects[index] = { "num": index };\
}\
var strNumbers = numbers + "";\
\
if (typeof bind != "undefined") {\
var thisArg = { "name": "fred" };\
\
var func = function(greeting, punctuation) {\
return (greeting || "hi") + " " + this.name + (punctuation || ".");\
};\
\
var _boundNormal = _.bind(func, thisArg),\
_boundMultiple = _boundNormal,\
_boundPartial = _.bind(func, thisArg, "hi");\
\
var lodashBoundNormal = lodash.bind(func, thisArg),\
lodashBoundMultiple = lodashBoundNormal,\
lodashBoundPartial = lodash.bind(func, thisArg, "hi");\
\
for (index = 0; index < 10; index++) {\
_boundMultiple = _.bind(_boundMultiple, { "name": "fred" + index });\
lodashBoundMultiple = lodash.bind(lodashBoundMultiple, { "name": "fred" + index });\
}\
}\
if (typeof bindAll != "undefined") {\
var bindAllCount = -1,\
bindAllObjects = Array(this.count);\
\
var funcNames = belt.reject(belt.functions(belt).slice(0, 40), function(funcName) {\
return /^_/.test(funcName);\
});\
\
// Potentially expensive.\n\
for (index = 0; index < this.count; index++) {\
bindAllObjects[index] = belt.reduce(funcNames, function(object, funcName) {\
object[funcName] = belt[funcName];\
return object;\
}, {});\
}\
}\
if (typeof chaining != "undefined") {\
var even = function(v) { return v % 2 == 0; },\
square = function(v) { return v * v; };\
\
var largeArray = belt.range(10000),\
_chaining = _.chain ? _(largeArray).chain() : _(largeArray),\
lodashChaining = lodash(largeArray);\
}\
if (typeof compact != "undefined") {\
var uncompacted = numbers.slice();\
uncompacted[2] = false;\
uncompacted[6] = null;\
uncompacted[18] = "";\
}\
if (typeof compose != "undefined") {\
var compAddOne = function(n) { return n + 1; },\
compAddTwo = function(n) { return n + 2; },\
compAddThree = function(n) { return n + 3; };\
\
var _composed = _.compose(compAddThree, compAddTwo, compAddOne),\
lodashComposed = lodash.compose(compAddThree, compAddTwo, compAddOne);\
}\
if (typeof countBy != "undefined" || typeof omit != "undefined") {\
var wordToNumber = {\
"one": 1,\
"two": 2,\
"three": 3,\
"four": 4,\
"five": 5,\
"six": 6,\
"seven": 7,\
"eight": 8,\
"nine": 9,\
"ten": 10,\
"eleven": 11,\
"twelve": 12,\
"thirteen": 13,\
"fourteen": 14,\
"fifteen": 15,\
"sixteen": 16,\
"seventeen": 17,\
"eighteen": 18,\
"nineteen": 19,\
"twenty": 20,\
"twenty-one": 21,\
"twenty-two": 22,\
"twenty-three": 23,\
"twenty-four": 24,\
"twenty-five": 25,\
"twenty-six": 26,\
"twenty-seven": 27,\
"twenty-eight": 28,\
"twenty-nine": 29,\
"thirty": 30,\
"thirty-one": 31,\
"thirty-two": 32,\
"thirty-three": 33,\
"thirty-four": 34,\
"thirty-five": 35,\
"thirty-six": 36,\
"thirty-seven": 37,\
"thirty-eight": 38,\
"thirty-nine": 39,\
"forty": 40\
};\
\
var words = belt.keys(wordToNumber).slice(0, limit);\
}\
if (typeof flatten != "undefined") {\
var _flattenDeep = _.flatten([[1]])[0] !== 1,\
lodashFlattenDeep = lodash.flatten([[1]]) !== 1;\
}\
if (typeof isEqual != "undefined") {\
var objectOfPrimitives = {\
"boolean": true,\
"number": 1,\
"string": "a"\
};\
\
var objectOfObjects = {\
"boolean": new Boolean(true),\
"number": new Number(1),\
"string": new String("a")\
};\
\
var objectOfObjects2 = {\
"boolean": new Boolean(true),\
"number": new Number(1),\
"string": new String("A")\
};\
\
var object2 = {},\
object3 = {},\
objects2 = Array(limit),\
objects3 = Array(limit),\
numbers2 = Array(limit),\
numbers3 = Array(limit),\
nestedNumbers2 = [1, [2], [3, [[4]]]],\
nestedNumbers3 = [1, [2], [3, [[6]]]];\
\
for (index = 0; index < limit; index++) {\
object2["key" + index] = index;\
object3["key" + index] = index;\
objects2[index] = { "num": index };\
objects3[index] = { "num": index };\
numbers2[index] = index;\
numbers3[index] = index;\
}\
object3["key" + (limit - 1)] = -1;\
objects3[limit - 1].num = -1;\
numbers3[limit - 1] = -1;\
}\
if (typeof matches != "undefined") {\
var source = { "num": 9 };\
\
var _findWhere = _.findWhere || _.find,\
_match = (_.matches || _.createCallback || _.noop)(source);\
\
var lodashFindWhere = lodash.findWhere || lodash.find,\
lodashMatch = (lodash.matches || lodash.createCallback || lodash.noop)(source);\
}\
if (typeof multiArrays != "undefined") {\
var twentyValues = belt.shuffle(belt.range(20)),\
fortyValues = belt.shuffle(belt.range(40)),\
hundredSortedValues = belt.range(100),\
hundredValues = belt.shuffle(hundredSortedValues),\
hundredValues2 = belt.shuffle(hundredValues),\
hundredTwentyValues = belt.shuffle(belt.range(120)),\
hundredTwentyValues2 = belt.shuffle(hundredTwentyValues),\
twoHundredValues = belt.shuffle(belt.range(200)),\
twoHundredValues2 = belt.shuffle(twoHundredValues);\
}\
if (typeof partial != "undefined") {\
var func = function(greeting, punctuation) {\
return greeting + " fred" + (punctuation || ".");\
};\
\
var _partial = _.partial(func, "hi"),\
lodashPartial = lodash.partial(func, "hi");\
}\
if (typeof template != "undefined") {\
var tplData = {\
"header1": "Header1",\
"header2": "Header2",\
"header3": "Header3",\
"header4": "Header4",\
"header5": "Header5",\
"header6": "Header6",\
"list": ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]\
};\
\
var tpl =\
"<div>" +\
"<h1 class=\'header1\'><%= header1 %></h1>" +\
"<h2 class=\'header2\'><%= header2 %></h2>" +\
"<h3 class=\'header3\'><%= header3 %></h3>" +\
"<h4 class=\'header4\'><%= header4 %></h4>" +\
"<h5 class=\'header5\'><%= header5 %></h5>" +\
"<h6 class=\'header6\'><%= header6 %></h6>" +\
"<ul class=\'list\'>" +\
"<% for (var index = 0, length = list.length; index < length; index++) { %>" +\
"<li class=\'item\'><%= list[index] %></li>" +\
"<% } %>" +\
"</ul>" +\
"</div>";\
\
var tplVerbose =\
"<div>" +\
"<h1 class=\'header1\'><%= data.header1 %></h1>" +\
"<h2 class=\'header2\'><%= data.header2 %></h2>" +\
"<h3 class=\'header3\'><%= data.header3 %></h3>" +\
"<h4 class=\'header4\'><%= data.header4 %></h4>" +\
"<h5 class=\'header5\'><%= data.header5 %></h5>" +\
"<h6 class=\'header6\'><%= data.header6 %></h6>" +\
"<ul class=\'list\'>" +\
"<% for (var index = 0, length = data.list.length; index < length; index++) { %>" +\
"<li class=\'item\'><%= data.list[index] %></li>" +\
"<% } %>" +\
"</ul>" +\
"</div>";\
\
var settingsObject = { "variable": "data" };\
\
var _tpl = _.template(tpl),\
_tplVerbose = _.template(tplVerbose, null, settingsObject);\
\
var lodashTpl = lodash.template(tpl),\
lodashTplVerbose = lodash.template(tplVerbose, null, settingsObject);\
}\
if (typeof wrap != "undefined") {\
var add = function(a, b) {\
return a + b;\
};\
\
var average = function(func, a, b) {\
return (func(a, b) / 2).toFixed(2);\
};\
\
var _wrapped = _.wrap(add, average);\
lodashWrapped = lodash.wrap(add, average);\
}\
if (typeof zip != "undefined") {\
var unzipped = [["a", "b", "c"], [1, 2, 3], [true, false, true]];\
}'
});
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_(...).map(...).filter(...).take(...).value()`')
.add(buildName, {
'fn': 'lodashChaining.map(square).filter(even).take(100).value()',
'teardown': 'function chaining(){}'
})
.add(otherName, {
'fn': '_chaining.map(square).filter(even).take(100).value()',
'teardown': 'function chaining(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.bind` (slow path)')
.add(buildName, {
'fn': 'lodash.bind(function() { return this.name; }, { "name": "fred" })',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_.bind(function() { return this.name; }, { "name": "fred" })',
'teardown': 'function bind(){}'
})
);
suites.push(
Benchmark.Suite('bound call with arguments')
.add(buildName, {
'fn': 'lodashBoundNormal("hi", "!")',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_boundNormal("hi", "!")',
'teardown': 'function bind(){}'
})
);
suites.push(
Benchmark.Suite('bound and partially applied call with arguments')
.add(buildName, {
'fn': 'lodashBoundPartial("!")',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_boundPartial("!")',
'teardown': 'function bind(){}'
})
);
suites.push(
Benchmark.Suite('bound multiple times')
.add(buildName, {
'fn': 'lodashBoundMultiple()',
'teardown': 'function bind(){}'
})
.add(otherName, {
'fn': '_boundMultiple()',
'teardown': 'function bind(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.bindAll` iterating arguments')
.add(buildName, {
'fn': 'lodash.bindAll.apply(lodash, [bindAllObjects[++bindAllCount]].concat(funcNames))',
'teardown': 'function bindAll(){}'
})
.add(otherName, {
'fn': '_.bindAll.apply(_, [bindAllObjects[++bindAllCount]].concat(funcNames))',
'teardown': 'function bindAll(){}'
})
);
suites.push(
Benchmark.Suite('`_.bindAll` iterating the `object`')
.add(buildName, {
'fn': 'lodash.bindAll(bindAllObjects[++bindAllCount])',
'teardown': 'function bindAll(){}'
})
.add(otherName, {
'fn': '_.bindAll(bindAllObjects[++bindAllCount])',
'teardown': 'function bindAll(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.clone` with an array')
.add(buildName, '\
lodash.clone(numbers)'
)
.add(otherName, '\
_.clone(numbers)'
)
);
suites.push(
Benchmark.Suite('`_.clone` with an object')
.add(buildName, '\
lodash.clone(object)'
)
.add(otherName, '\
_.clone(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.compact`')
.add(buildName, {
'fn': 'lodash.compact(uncompacted)',
'teardown': 'function compact(){}'
})
.add(otherName, {
'fn': '_.compact(uncompacted)',
'teardown': 'function compact(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.compose`')
.add(buildName, {
'fn': 'lodash.compose(compAddThree, compAddTwo, compAddOne)',
'teardown': 'function compose(){}'
})
.add(otherName, {
'fn': '_.compose(compAddThree, compAddTwo, compAddOne)',
'teardown': 'function compose(){}'
})
);
suites.push(
Benchmark.Suite('composed call')
.add(buildName, {
'fn': 'lodashComposed(0)',
'teardown': 'function compose(){}'
})
.add(otherName, {
'fn': '_composed(0)',
'teardown': 'function compose(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.countBy` with `callback` iterating an array')
.add(buildName, '\
lodash.countBy(numbers, function(num) { return num >> 1; })'
)
.add(otherName, '\
_.countBy(numbers, function(num) { return num >> 1; })'
)
);
suites.push(
Benchmark.Suite('`_.countBy` with `property` name iterating an array')
.add(buildName, {
'fn': 'lodash.countBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.countBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
suites.push(
Benchmark.Suite('`_.countBy` with `callback` iterating an object')
.add(buildName, {
'fn': 'lodash.countBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.countBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.defaults`')
.add(buildName, '\
lodash.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)'
)
.add(otherName, '\
_.defaults({ "key2": 2, "key6": 6, "key18": 18 }, object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.difference`')
.add(buildName, '\
lodash.difference(numbers, twoNumbers, fourNumbers)'
)
.add(otherName, '\
_.difference(numbers, twoNumbers, fourNumbers)'
)
);
suites.push(
Benchmark.Suite('`_.difference` iterating 200 elements')
.add(buildName, {
'fn': 'lodash.difference(twoHundredValues, twoHundredValues2)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.difference(twoHundredValues, twoHundredValues2)',
'teardown': 'function multiArrays(){}'
})
);
suites.push(
Benchmark.Suite('`_.difference` iterating 20 and 40 elements')
.add(buildName, {
'fn': 'lodash.difference(twentyValues, fortyValues)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.difference(twentyValues, fortyValues)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.each` iterating an array')
.add(buildName, '\
var result = [];\
lodash.each(numbers, function(num) {\
result.push(num * 2);\
})'
)
.add(otherName, '\
var result = [];\
_.each(numbers, function(num) {\
result.push(num * 2);\
})'
)
);
suites.push(
Benchmark.Suite('`_.each` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
var result = [];\
lodash.each(numbers, function(num, index) {\
result.push(num + this["key" + index]);\
}, object)'
)
.add(otherName, '\
var result = [];\
_.each(numbers, function(num, index) {\
result.push(num + this["key" + index]);\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.each` iterating an object')
.add(buildName, '\
var result = [];\
lodash.each(object, function(num) {\
result.push(num * 2);\
})'
)
.add(otherName, '\
var result = [];\
_.each(object, function(num) {\
result.push(num * 2);\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.every` iterating an array')
.add(buildName, '\
lodash.every(numbers, function(num) {\
return num < limit;\
})'
)
.add(otherName, '\
_.every(numbers, function(num) {\
return num < limit;\
})'
)
);
suites.push(
Benchmark.Suite('`_.every` iterating an object')
.add(buildName, '\
lodash.every(object, function(num) {\
return num < limit;\
})'
)
.add(otherName, '\
_.every(object, function(num) {\
return num < limit;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.extend`')
.add(buildName, '\
lodash.extend({}, object)'
)
.add(otherName, '\
_.extend({}, object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.filter` iterating an array')
.add(buildName, '\
lodash.filter(numbers, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.filter(numbers, function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.filter` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
lodash.filter(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
.add(otherName, '\
_.filter(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.filter` iterating an object')
.add(buildName, '\
lodash.filter(object, function(num) {\
return num % 2\
})'
)
.add(otherName, '\
_.filter(object, function(num) {\
return num % 2\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.find` iterating an array')
.add(buildName, '\
lodash.find(numbers, function(num) {\
return num === (limit - 1);\
})'
)
.add(otherName, '\
_.find(numbers, function(num) {\
return num === (limit - 1);\
})'
)
);
suites.push(
Benchmark.Suite('`_.find` iterating an object')
.add(buildName, '\
lodash.find(object, function(value, key) {\
return /\D9$/.test(key);\
})'
)
.add(otherName, '\
_.find(object, function(value, key) {\
return /\D9$/.test(key);\
})'
)
);
// Avoid Underscore induced `OutOfMemoryError` in Rhino, Narwhal, and Ringo.
if (!isJava) {
suites.push(
Benchmark.Suite('`_.find` with `properties`')
.add(buildName, {
'fn': 'lodashFindWhere(objects, source)',
'teardown': 'function matches(){}'
})
.add(otherName, {
'fn': '_findWhere(objects, source)',
'teardown': 'function matches(){}'
})
);
}
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.flatten`')
.add(buildName, {
'fn': 'lodash.flatten(nestedNumbers, !lodashFlattenDeep)',
'teardown': 'function flatten(){}'
})
.add(otherName, {
'fn': '_.flatten(nestedNumbers, !_flattenDeep)',
'teardown': 'function flatten(){}'
})
);
suites.push(
Benchmark.Suite('`_.flatten` nested arrays of numbers with `isDeep`')
.add(buildName, {
'fn': 'lodash.flatten(nestedNumbers, lodashFlattenDeep)',
'teardown': 'function flatten(){}'
})
.add(otherName, {
'fn': '_.flatten(nestedNumbers, _flattenDeep)',
'teardown': 'function flatten(){}'
})
);
suites.push(
Benchmark.Suite('`_.flatten` nest arrays of objects with `isDeep`')
.add(buildName, {
'fn': 'lodash.flatten(nestedObjects, lodashFlattenDeep)',
'teardown': 'function flatten(){}'
})
.add(otherName, {
'fn': '_.flatten(nestedObjects, _flattenDeep)',
'teardown': 'function flatten(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.functions`')
.add(buildName, '\
lodash.functions(lodash)'
)
.add(otherName, '\
_.functions(lodash)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.groupBy` with `callback` iterating an array')
.add(buildName, '\
lodash.groupBy(numbers, function(num) { return num >> 1; })'
)
.add(otherName, '\
_.groupBy(numbers, function(num) { return num >> 1; })'
)
);
suites.push(
Benchmark.Suite('`_.groupBy` with `property` name iterating an array')
.add(buildName, {
'fn': 'lodash.groupBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.groupBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
suites.push(
Benchmark.Suite('`_.groupBy` with `callback` iterating an object')
.add(buildName, {
'fn': 'lodash.groupBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.groupBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.include` iterating an array')
.add(buildName, '\
lodash.include(numbers, limit - 1)'
)
.add(otherName, '\
_.include(numbers, limit - 1)'
)
);
suites.push(
Benchmark.Suite('`_.include` iterating an object')
.add(buildName, '\
lodash.include(object, limit - 1)'
)
.add(otherName, '\
_.include(object, limit - 1)'
)
);
if (lodash.include('ab', 'ab') && _.include('ab', 'ab')) {
suites.push(
Benchmark.Suite('`_.include` iterating a string')
.add(buildName, '\
lodash.include(strNumbers, "," + (limit - 1))'
)
.add(otherName, '\
_.include(strNumbers, "," + (limit - 1))'
)
);
}
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.indexBy` with `callback` iterating an array')
.add(buildName, '\
lodash.indexBy(numbers, function(num) { return num >> 1; })'
)
.add(otherName, '\
_.indexBy(numbers, function(num) { return num >> 1; })'
)
);
suites.push(
Benchmark.Suite('`_.indexBy` with `property` name iterating an array')
.add(buildName, {
'fn': 'lodash.indexBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.indexBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
suites.push(
Benchmark.Suite('`_.indexBy` with `callback` iterating an object')
.add(buildName, {
'fn': 'lodash.indexBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.indexBy(wordToNumber, function(num) { return num >> 1; })',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.indexOf`')
.add(buildName, {
'fn': 'lodash.indexOf(hundredSortedValues, 99)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.indexOf(hundredSortedValues, 99)',
'teardown': 'function multiArrays(){}'
})
);
suites.push(
Benchmark.Suite('`_.indexOf` performing a binary search')
.add(buildName, {
'fn': 'lodash.indexOf(hundredSortedValues, 99, true)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.indexOf(hundredSortedValues, 99, true)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.intersection`')
.add(buildName, '\
lodash.intersection(numbers, twoNumbers, fourNumbers)'
)
.add(otherName, '\
_.intersection(numbers, twoNumbers, fourNumbers)'
)
);
suites.push(
Benchmark.Suite('`_.intersection` iterating 120 elements')
.add(buildName, {
'fn': 'lodash.intersection(hundredTwentyValues, hundredTwentyValues2)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.intersection(hundredTwentyValues, hundredTwentyValues2)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.invert`')
.add(buildName, '\
lodash.invert(object)'
)
.add(otherName, '\
_.invert(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.invoke` iterating an array')
.add(buildName, '\
lodash.invoke(numbers, "toFixed")'
)
.add(otherName, '\
_.invoke(numbers, "toFixed")'
)
);
suites.push(
Benchmark.Suite('`_.invoke` with arguments iterating an array')
.add(buildName, '\
lodash.invoke(numbers, "toFixed", 1)'
)
.add(otherName, '\
_.invoke(numbers, "toFixed", 1)'
)
);
suites.push(
Benchmark.Suite('`_.invoke` with a function for `methodName` iterating an array')
.add(buildName, '\
lodash.invoke(numbers, Number.prototype.toFixed, 1)'
)
.add(otherName, '\
_.invoke(numbers, Number.prototype.toFixed, 1)'
)
);
suites.push(
Benchmark.Suite('`_.invoke` iterating an object')
.add(buildName, '\
lodash.invoke(object, "toFixed", 1)'
)
.add(otherName, '\
_.invoke(object, "toFixed", 1)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.isEqual` comparing primitives')
.add(buildName, {
'fn': '\
lodash.isEqual(1, "1");\
lodash.isEqual(1, 1)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(1, "1");\
_.isEqual(1, 1);',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing primitives and their object counterparts (edge case)')
.add(buildName, {
'fn': '\
lodash.isEqual(objectOfPrimitives, objectOfObjects);\
lodash.isEqual(objectOfPrimitives, objectOfObjects2)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(objectOfPrimitives, objectOfObjects);\
_.isEqual(objectOfPrimitives, objectOfObjects2)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing arrays')
.add(buildName, {
'fn': '\
lodash.isEqual(numbers, numbers2);\
lodash.isEqual(numbers2, numbers3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(numbers, numbers2);\
_.isEqual(numbers2, numbers3)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing nested arrays')
.add(buildName, {
'fn': '\
lodash.isEqual(nestedNumbers, nestedNumbers2);\
lodash.isEqual(nestedNumbers2, nestedNumbers3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(nestedNumbers, nestedNumbers2);\
_.isEqual(nestedNumbers2, nestedNumbers3)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing arrays of objects')
.add(buildName, {
'fn': '\
lodash.isEqual(objects, objects2);\
lodash.isEqual(objects2, objects3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(objects, objects2);\
_.isEqual(objects2, objects3)',
'teardown': 'function isEqual(){}'
})
);
suites.push(
Benchmark.Suite('`_.isEqual` comparing objects')
.add(buildName, {
'fn': '\
lodash.isEqual(object, object2);\
lodash.isEqual(object2, object3)',
'teardown': 'function isEqual(){}'
})
.add(otherName, {
'fn': '\
_.isEqual(object, object2);\
_.isEqual(object2, object3)',
'teardown': 'function isEqual(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.isArguments`, `_.isDate`, `_.isFunction`, `_.isNumber`, `_.isObject`, `_.isRegExp`')
.add(buildName, '\
lodash.isArguments(arguments);\
lodash.isArguments(object);\
lodash.isDate(date);\
lodash.isDate(object);\
lodash.isFunction(lodash);\
lodash.isFunction(object);\
lodash.isNumber(1);\
lodash.isNumber(object);\
lodash.isObject(object);\
lodash.isObject(1);\
lodash.isRegExp(regexp);\
lodash.isRegExp(object)'
)
.add(otherName, '\
_.isArguments(arguments);\
_.isArguments(object);\
_.isDate(date);\
_.isDate(object);\
_.isFunction(_);\
_.isFunction(object);\
_.isNumber(1);\
_.isNumber(object);\
_.isObject(object);\
_.isObject(1);\
_.isRegExp(regexp);\
_.isRegExp(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.keys` (uses native `Object.keys` if available)')
.add(buildName, '\
lodash.keys(object)'
)
.add(otherName, '\
_.keys(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.lastIndexOf`')
.add(buildName, {
'fn': 'lodash.lastIndexOf(hundredSortedValues, 0)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.lastIndexOf(hundredSortedValues, 0)',
'teardown': 'function multiArrays(){}'
})
);
suites.push(
Benchmark.Suite('`_.lastIndexOf` performing a binary search')
.add(buildName, {
'fn': 'lodash.lastIndexOf(hundredSortedValues, 0, true)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.lastIndexOf(hundredSortedValues, 0, true)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.map` iterating an array')
.add(buildName, '\
lodash.map(objects, function(value) {\
return value.num;\
})'
)
.add(otherName, '\
_.map(objects, function(value) {\
return value.num;\
})'
)
);
suites.push(
Benchmark.Suite('`_.map` with `thisArg` iterating an array (slow path)')
.add(buildName, '\
lodash.map(objects, function(value, index) {\
return this["key" + index] + value.num;\
}, object)'
)
.add(otherName, '\
_.map(objects, function(value, index) {\
return this["key" + index] + value.num;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.map` iterating an object')
.add(buildName, '\
lodash.map(object, function(value) {\
return value;\
})'
)
.add(otherName, '\
_.map(object, function(value) {\
return value;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.matches` predicate')
.add(buildName, {
'fn': 'lodash.filter(objects, lodashMatch)',
'teardown': 'function matches(){}'
})
.add(otherName, {
'fn': '_.filter(objects, _match)',
'teardown': 'function matches(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.max`')
.add(buildName, '\
lodash.max(numbers)'
)
.add(otherName, '\
_.max(numbers)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.min`')
.add(buildName, '\
lodash.min(numbers)'
)
.add(otherName, '\
_.min(numbers)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.omit` iterating 20 properties, omitting 2 keys')
.add(buildName, '\
lodash.omit(object, "key6", "key13")'
)
.add(otherName, '\
_.omit(object, "key6", "key13")'
)
);
suites.push(
Benchmark.Suite('`_.omit` iterating 40 properties, omitting 20 keys')
.add(buildName, {
'fn': 'lodash.omit(wordToNumber, words)',
'teardown': 'function omit(){}'
})
.add(otherName, {
'fn': '_.omit(wordToNumber, words)',
'teardown': 'function omit(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.pairs`')
.add(buildName, '\
lodash.pairs(object)'
)
.add(otherName, '\
_.pairs(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.partial` (slow path)')
.add(buildName, {
'fn': 'lodash.partial(function(greeting) { return greeting + " " + this.name; }, "hi")',
'teardown': 'function partial(){}'
})
.add(otherName, {
'fn': '_.partial(function(greeting) { return greeting + " " + this.name; }, "hi")',
'teardown': 'function partial(){}'
})
);
suites.push(
Benchmark.Suite('partially applied call with arguments')
.add(buildName, {
'fn': 'lodashPartial("!")',
'teardown': 'function partial(){}'
})
.add(otherName, {
'fn': '_partial("!")',
'teardown': 'function partial(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.partition` iterating an array')
.add(buildName, '\
lodash.partition(numbers, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.partition(numbers, function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.partition` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
lodash.partition(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
.add(otherName, '\
_.partition(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.partition` iterating an object')
.add(buildName, '\
lodash.partition(object, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.partition(object, function(num) {\
return num % 2;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.pick`')
.add(buildName, '\
lodash.pick(object, "key6", "key13")'
)
.add(otherName, '\
_.pick(object, "key6", "key13")'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.pluck`')
.add(buildName, '\
lodash.pluck(objects, "num")'
)
.add(otherName, '\
_.pluck(objects, "num")'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.reduce` iterating an array')
.add(buildName, '\
lodash.reduce(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
.add(otherName, '\
_.reduce(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
);
suites.push(
Benchmark.Suite('`_.reduce` iterating an object')
.add(buildName, '\
lodash.reduce(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
.add(otherName, '\
_.reduce(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.reduceRight` iterating an array')
.add(buildName, '\
lodash.reduceRight(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
.add(otherName, '\
_.reduceRight(numbers, function(result, value, index) {\
result[index] = value;\
return result;\
}, {})'
)
);
suites.push(
Benchmark.Suite('`_.reduceRight` iterating an object')
.add(buildName, '\
lodash.reduceRight(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
.add(otherName, '\
_.reduceRight(object, function(result, value, key) {\
result.push(key, value);\
return result;\
}, [])'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.reject` iterating an array')
.add(buildName, '\
lodash.reject(numbers, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.reject(numbers, function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.reject` iterating an array with `thisArg` (slow path)')
.add(buildName, '\
lodash.reject(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
.add(otherName, '\
_.reject(numbers, function(num, index) {\
return this["key" + index] % 2;\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.reject` iterating an object')
.add(buildName, '\
lodash.reject(object, function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.reject(object, function(num) {\
return num % 2;\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.sample` with an `n`')
.add(buildName, '\
lodash.sample(numbers, limit / 2)'
)
.add(otherName, '\
_.sample(numbers, limit / 2)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.shuffle`')
.add(buildName, '\
lodash.shuffle(numbers)'
)
.add(otherName, '\
_.shuffle(numbers)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.size` with an object')
.add(buildName, '\
lodash.size(object)'
)
.add(otherName, '\
_.size(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.some` iterating an array')
.add(buildName, '\
lodash.some(numbers, function(num) {\
return num == (limit - 1);\
})'
)
.add(otherName, '\
_.some(numbers, function(num) {\
return num == (limit - 1);\
})'
)
);
suites.push(
Benchmark.Suite('`_.some` with `thisArg` iterating an array (slow path)')
.add(buildName, '\
lodash.some(objects, function(value, index) {\
return this["key" + index] == (limit - 1);\
}, object)'
)
.add(otherName, '\
_.some(objects, function(value, index) {\
return this["key" + index] == (limit - 1);\
}, object)'
)
);
suites.push(
Benchmark.Suite('`_.some` iterating an object')
.add(buildName, '\
lodash.some(object, function(num) {\
return num == (limit - 1);\
})'
)
.add(otherName, '\
_.some(object, function(num) {\
return num == (limit - 1);\
})'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.sortBy` with `callback`')
.add(buildName, '\
lodash.sortBy(numbers, function(num) { return Math.sin(num); })'
)
.add(otherName, '\
_.sortBy(numbers, function(num) { return Math.sin(num); })'
)
);
suites.push(
Benchmark.Suite('`_.sortBy` with `callback` and `thisArg` (slow path)')
.add(buildName, '\
lodash.sortBy(numbers, function(num) { return this.sin(num); }, Math)'
)
.add(otherName, '\
_.sortBy(numbers, function(num) { return this.sin(num); }, Math)'
)
);
suites.push(
Benchmark.Suite('`_.sortBy` with `property` name')
.add(buildName, {
'fn': 'lodash.sortBy(words, "length")',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '_.sortBy(words, "length")',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.sortedIndex` with `callback`')
.add(buildName, {
'fn': '\
lodash.sortedIndex(words, "twenty-five", function(value) {\
return wordToNumber[value];\
})',
'teardown': 'function countBy(){}'
})
.add(otherName, {
'fn': '\
_.sortedIndex(words, "twenty-five", function(value) {\
return wordToNumber[value];\
})',
'teardown': 'function countBy(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.template` (slow path)')
.add(buildName, {
'fn': 'lodash.template(tpl)(tplData)',
'teardown': 'function template(){}'
})
.add(otherName, {
'fn': '_.template(tpl)(tplData)',
'teardown': 'function template(){}'
})
);
suites.push(
Benchmark.Suite('compiled template')
.add(buildName, {
'fn': 'lodashTpl(tplData)',
'teardown': 'function template(){}'
})
.add(otherName, {
'fn': '_tpl(tplData)',
'teardown': 'function template(){}'
})
);
suites.push(
Benchmark.Suite('compiled template without a with-statement')
.add(buildName, {
'fn': 'lodashTplVerbose(tplData)',
'teardown': 'function template(){}'
})
.add(otherName, {
'fn': '_tplVerbose(tplData)',
'teardown': 'function template(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.times`')
.add(buildName, '\
var result = [];\
lodash.times(limit, function(n) { result.push(n); })'
)
.add(otherName, '\
var result = [];\
_.times(limit, function(n) { result.push(n); })'
)
);
suites.push(
Benchmark.Suite('`_.times` with `thisArg` (slow path)')
.add(buildName, '\
var result = [];\
lodash.times(limit, function(n) { result.push(this.sin(n)); }, Math)'
)
.add(otherName, '\
var result = [];\
_.times(limit, function(n) { result.push(this.sin(n)); }, Math)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.toArray` with an array (edge case)')
.add(buildName, '\
lodash.toArray(numbers)'
)
.add(otherName, '\
_.toArray(numbers)'
)
);
suites.push(
Benchmark.Suite('`_.toArray` with an object')
.add(buildName, '\
lodash.toArray(object)'
)
.add(otherName, '\
_.toArray(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.unescape` string without html entities')
.add(buildName, '\
lodash.unescape("`&`, `<`, `>`, `\\"`, and `\'`")'
)
.add(otherName, '\
_.unescape("`&`, `<`, `>`, `\\"`, and `\'`")'
)
);
suites.push(
Benchmark.Suite('`_.unescape` string with html entities')
.add(buildName, '\
lodash.unescape("`&`, `<`, `>`, `"`, and `'`")'
)
.add(otherName, '\
_.unescape("`&`, `<`, `>`, `"`, and `'`")'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.union`')
.add(buildName, '\
lodash.union(numbers, twoNumbers, fourNumbers)'
)
.add(otherName, '\
_.union(numbers, twoNumbers, fourNumbers)'
)
);
suites.push(
Benchmark.Suite('`_.union` iterating an array of 200 elements')
.add(buildName, {
'fn': 'lodash.union(hundredValues, hundredValues2)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.union(hundredValues, hundredValues2)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.uniq`')
.add(buildName, '\
lodash.uniq(numbers.concat(twoNumbers, fourNumbers))'
)
.add(otherName, '\
_.uniq(numbers.concat(twoNumbers, fourNumbers))'
)
);
suites.push(
Benchmark.Suite('`_.uniq` with `callback`')
.add(buildName, '\
lodash.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\
return num % 2;\
})'
)
.add(otherName, '\
_.uniq(numbers.concat(twoNumbers, fourNumbers), function(num) {\
return num % 2;\
})'
)
);
suites.push(
Benchmark.Suite('`_.uniq` iterating an array of 200 elements')
.add(buildName, {
'fn': 'lodash.uniq(twoHundredValues)',
'teardown': 'function multiArrays(){}'
})
.add(otherName, {
'fn': '_.uniq(twoHundredValues)',
'teardown': 'function multiArrays(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.values`')
.add(buildName, '\
lodash.values(object)'
)
.add(otherName, '\
_.values(object)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.where`')
.add(buildName, {
'fn': 'lodash.where(objects, source)',
'teardown': 'function matches(){}'
})
.add(otherName, {
'fn': '_.where(objects, source)',
'teardown': 'function matches(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.without`')
.add(buildName, '\
lodash.without(numbers, 9, 12, 14, 15)'
)
.add(otherName, '\
_.without(numbers, 9, 12, 14, 15)'
)
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.wrap` result called')
.add(buildName, {
'fn': 'lodashWrapped(2, 5)',
'teardown': 'function wrap(){}'
})
.add(otherName, {
'fn': '_wrapped(2, 5)',
'teardown': 'function wrap(){}'
})
);
/*--------------------------------------------------------------------------*/
suites.push(
Benchmark.Suite('`_.zip`')
.add(buildName, {
'fn': 'lodash.zip.apply(lodash, unzipped)',
'teardown': 'function zip(){}'
})
.add(otherName, {
'fn': '_.zip.apply(_, unzipped)',
'teardown': 'function zip(){}'
})
);
/*--------------------------------------------------------------------------*/
if (Benchmark.platform + '') {
log(Benchmark.platform);
}
// Expose `run` to be called later when executing in a browser.
if (document) {
root.run = run;
} else {
run();
}
}.call(this));
| Great-Bee/NVWA-Client | js/bower_components/lodash/perf/perf.js | JavaScript | gpl-2.0 | 60,255 |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace Git.Storage.Common
{
public enum EEquipmentStatus
{
/// <summary>
/// 闲置
/// </summary>
[Description("闲置")]
Unused = 1,
/// <summary>
/// 正在使用
/// </summary>
[Description("正在使用")]
IsUsing = 2,
/// <summary>
/// 报修
/// </summary>
[Description("报修")]
Repair = 3,
/// <summary>
/// 报损
/// </summary>
[Description("报损")]
Breakage = 4,
/// <summary>
/// 遗失
/// </summary>
[Description("遗失")]
Lost = 5,
}
}
| hechenqingyuan/gitwms | Git.Storage.Common/EEquipmentStatus.cs | C# | gpl-2.0 | 794 |
/*
Behaviour v1.1 by Ben Nolan, June 2005. Based largely on the work
of Simon Willison (see comments by Simon below).
Small fixes by J.Dobrowolski for Front Accounting May 2008
Description:
Uses css selectors to apply javascript behaviours to enable
unobtrusive javascript in html documents.
Usage:
var myrules = {
'b.someclass' : function(element){
element.onclick = function(){
alert(this.innerHTML);
}
},
'#someid u' : function(element){
element.onmouseover = function(){
this.innerHTML = "BLAH!";
}
}
};
Behaviour.register(myrules);
// Call Behaviour.apply() to re-apply the rules (if you
// update the dom, etc).
License:
This file is entirely BSD licensed.
More information:
http://ripcord.co.nz/behaviour/
*/
var Behaviour = {
list : new Array,
register : function(sheet){
Behaviour.list.push(sheet);
},
start : function(){
Behaviour.addLoadEvent(function(){
Behaviour.apply();
});
},
apply : function(){
for (h=0;sheet=Behaviour.list[h];h++){
for (selector in sheet){
var sels = selector.split(',');
for (var n = 0; n < sels.length; n++) {
list = document.getElementsBySelector(sels[n]);
if (!list){
continue;
}
for (i=0;element=list[i];i++){
sheet[selector](element);
}
}
}
}
},
addLoadEvent : function(func){
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
}
Behaviour.start();
/*
The following code is Copyright (C) Simon Willison 2004.
document.getElementsBySelector(selector)
- returns an array of element objects from the current document
matching the CSS selector. Selectors can contain element names,
class names and ids and can be nested. For example:
elements = document.getElementsBySelect('div#main p a.external')
Will return an array of all 'a' elements with 'external' in their
class attribute that are contained inside 'p' elements that are
contained inside the 'div' element which has id="main"
New in version 0.4: Support for CSS2 and CSS3 attribute selectors:
See http://www.w3.org/TR/css3-selectors/#attribute-selectors
Version 0.4 - Simon Willison, March 25th 2003
-- Works in Phoenix 0.5, Mozilla 1.3, Opera 7, Internet Explorer 6, Internet Explorer 5 on Windows
-- Opera 7 fails
*/
function getAllChildren(e) {
// Returns all children of element. Workaround required for IE5/Windows. Ugh.
return e.all ? e.all : e.getElementsByTagName('*');
}
document.getElementsBySelector = function(selector) {
// Attempt to fail gracefully in lesser browsers
if (!document.getElementsByTagName) {
return new Array();
}
// Split selector in to tokens
var tokens = selector.split(' ');
var currentContext = new Array(document);
for (var i = 0; i < tokens.length; i++) {
token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');;
if (token.indexOf('#') > -1) {
// Token is an ID selector
var bits = token.split('#');
var tagName = bits[0];
var id = bits[1];
var element = document.getElementById(id);
if (tagName && element.nodeName.toLowerCase() != tagName) {
// tag with that ID not found, return false
return new Array();
}
// Set currentContext to contain just this element
currentContext = new Array(element);
continue; // Skip to next token
}
if (token.indexOf('.') > -1) {
// Token contains a class selector
var bits = token.split('.');
var tagName = bits[0];
var className = bits[1];
if (!tagName) {
tagName = '*';
}
// Get elements matching tag, filter them for class selector
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = getAllChildren(currentContext[h]);
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = new Array;
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b'))) {
currentContext[currentContextIndex++] = found[k];
}
}
continue; // Skip to next token
}
// Code to deal with attribute selectors
/* Original reg expression /^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
was replaced by new RegExp() cuz compressor fault */
if (token.match(new RegExp('^(\\w*)\\[(\\w+)([=~\\|\\^\\$\\*]?)=?"?([^\\]"]*)"?\\]$'))) {
var tagName = RegExp.$1;
var attrName = RegExp.$2;
var attrOperator = RegExp.$3;
var attrValue = RegExp.$4;
if (!tagName) {
tagName = '*';
}
// Grab all of the tagName elements within current context
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements;
if (tagName == '*') {
elements = getAllChildren(currentContext[h]);
} else {
elements = currentContext[h].getElementsByTagName(tagName);
}
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = new Array;
var currentContextIndex = 0;
var checkFunction; // This function will be used to filter the elements
switch (attrOperator) {
case '=': // Equality
checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
break;
case '~': // Match one of space seperated words
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('\\b'+attrValue+'\\b'))); };
break;
case '|': // Match start with value followed by optional hyphen
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.match(new RegExp('^'+attrValue+'-?'))); };
break;
case '^': // Match starts with value
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) == 0); };
break;
case '$': // Match ends with value - fails with "Warning" in Opera 7
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
break;
case '*': // Match contains value
checkFunction = function(e) { var a=e.getAttribute(attrName); return (a && a.indexOf(attrValue) > -1); };
break;
default :
// Just test for existence of attribute
checkFunction = function(e) { return e.getAttribute(attrName); };
}
currentContext = new Array;
var currentContextIndex = 0;
for (var k = 0; k < found.length; k++) {
if (checkFunction(found[k])) {
currentContext[currentContextIndex++] = found[k];
}
}
// alert('Attribute Selector: '+tagName+' '+attrName+' '+attrOperator+' '+attrValue);
continue; // Skip to next token
}
if (!currentContext[0]){
return;
}
// If we get here, token is JUST an element (not a class or ID selector)
tagName = token;
var found = new Array;
var foundCount = 0;
for (var h = 0; h < currentContext.length; h++) {
var elements = currentContext[h].getElementsByTagName(tagName);
for (var j = 0; j < elements.length; j++) {
found[foundCount++] = elements[j];
}
}
currentContext = found;
}
return currentContext;
}
/* That revolting regular expression explained
/^(\w+)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/
\---/ \---/\-------------/ \-------/
| | | |
| | | The value
| | ~,|,^,$,* or =
| Attribute
Tag
*/
| w2pc/front_accounting | js/behaviour.js | JavaScript | gpl-2.0 | 8,278 |
package oo.Prototype;
/*
* A Symbol Loader to register all prototype instance
*/
import java.util.*;
public class SymbolLoader {
private Hashtable symbols = new Hashtable();
public SymbolLoader() {
symbols.put("Line", new LineSymbol());
symbols.put("Note", new NoteSymbol());
}
public Hashtable getSymbols() {
return symbols;
}
} | longluo/DesignPatterns | src/oo/Prototype/SymbolLoader.java | Java | gpl-2.0 | 385 |
package com.djtu.signExam.util;
import java.io.IOException;
import com.djtu.signExam.model.support.EntityGenerator;
/**
* use this class to bootstrap the project.
* There is no need for developers to write model classes themselves.
* Once there are some updates or modified parts in the database,
* Please run this class as JavaApplication to update Modal class files.
*
* @author lihe
*
*/
public class Bootstrap {
public static void main(String[] args){
EntityGenerator generator = new EntityGenerator();
try {
generator.generateModel();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| doomdagger/CompetitionHub | src/main/java/com/djtu/signExam/util/Bootstrap.java | Java | gpl-2.0 | 625 |
<?php
/*
* acf_get_setting
*
* This function will return a value from the settings array found in the acf object
*
* @type function
* @date 28/09/13
* @since 5.0.0
*
* @param $name (string) the setting name to return
* @return (mixed)
*/
function acf_get_setting( $name, $default = null ) {
// vars
$settings = acf()->settings;
// find setting
$setting = acf_maybe_get( $settings, $name, $default );
// filter for 3rd party customization
$setting = apply_filters( "acf/settings/{$name}", $setting );
// return
return $setting;
}
/*
* acf_get_compatibility
*
* This function will return true or false for a given compatibility setting
*
* @type function
* @date 20/01/2015
* @since 5.1.5
*
* @param $name (string)
* @return (boolean)
*/
function acf_get_compatibility( $name ) {
return apply_filters( "acf/compatibility/{$name}", false );
}
/*
* acf_update_setting
*
* This function will update a value into the settings array found in the acf object
*
* @type function
* @date 28/09/13
* @since 5.0.0
*
* @param $name (string)
* @param $value (mixed)
* @return n/a
*/
function acf_update_setting( $name, $value ) {
acf()->settings[ $name ] = $value;
}
/*
* acf_append_setting
*
* This function will add a value into the settings array found in the acf object
*
* @type function
* @date 28/09/13
* @since 5.0.0
*
* @param $name (string)
* @param $value (mixed)
* @return n/a
*/
function acf_append_setting( $name, $value ) {
// createa array if needed
if( !isset(acf()->settings[ $name ]) ) {
acf()->settings[ $name ] = array();
}
// append to array
acf()->settings[ $name ][] = $value;
}
/*
* acf_get_path
*
* This function will return the path to a file within the ACF plugin folder
*
* @type function
* @date 28/09/13
* @since 5.0.0
*
* @param $path (string) the relative path from the root of the ACF plugin folder
* @return (string)
*/
function acf_get_path( $path ) {
return acf_get_setting('path') . $path;
}
/*
* acf_get_dir
*
* This function will return the url to a file within the ACF plugin folder
*
* @type function
* @date 28/09/13
* @since 5.0.0
*
* @param $path (string) the relative path from the root of the ACF plugin folder
* @return (string)
*/
function acf_get_dir( $path ) {
return acf_get_setting('dir') . $path;
}
/*
* acf_include
*
* This function will include a file
*
* @type function
* @date 10/03/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_include( $file ) {
$path = acf_get_path( $file );
if( file_exists($path) ) {
include_once( $path );
}
}
/*
* acf_parse_args
*
* This function will merge together 2 arrays and also convert any numeric values to ints
*
* @type function
* @date 18/10/13
* @since 5.0.0
*
* @param $args (array)
* @param $defaults (array)
* @return $args (array)
*/
function acf_parse_args( $args, $defaults = array() ) {
// $args may not be na array!
if( !is_array($args) ) {
$args = array();
}
// parse args
$args = wp_parse_args( $args, $defaults );
// parse types
$args = acf_parse_types( $args );
// return
return $args;
}
/*
* acf_parse_types
*
* This function will convert any numeric values to int and trim strings
*
* @type function
* @date 18/10/13
* @since 5.0.0
*
* @param $var (mixed)
* @return $var (mixed)
*/
function acf_parse_types( $array ) {
// some keys are restricted
$restricted = array(
'label',
'name',
'value',
'instructions',
'nonce'
);
// loop
foreach( array_keys($array) as $k ) {
// parse type if not restricted
if( !in_array($k, $restricted, true) ) {
$array[ $k ] = acf_parse_type( $array[ $k ] );
}
}
// return
return $array;
}
/*
* acf_parse_type
*
* description
*
* @type function
* @date 11/11/2014
* @since 5.0.9
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_parse_type( $v ) {
// test for array
if( is_array($v) ) {
return acf_parse_types($v);
}
// bail early if not string
if( !is_string($v) ) {
return $v;
}
// trim
$v = trim($v);
// numbers
if( is_numeric($v) && strval((int)$v) === $v ) {
$v = intval( $v );
}
// return
return $v;
}
/*
* acf_get_view
*
* This function will load in a file from the 'admin/views' folder and allow variables to be passed through
*
* @type function
* @date 28/09/13
* @since 5.0.0
*
* @param $view_name (string)
* @param $args (array)
* @return n/a
*/
function acf_get_view( $view_name = '', $args = array() ) {
// vars
$path = acf_get_path("admin/views/{$view_name}.php");
if( file_exists($path) ) {
include( $path );
}
}
/*
* acf_merge_atts
*
* description
*
* @type function
* @date 2/11/2014
* @since 5.0.9
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_merge_atts( $atts, $extra = array() ) {
// bail ealry if no $extra
if( empty($extra) ) {
return $atts;
}
// merge in new atts
foreach( $extra as $k => $v ) {
if( $k == 'class' || $k == 'style' ) {
if( $v === '' ) {
continue;
}
$v = $atts[ $k ] . ' ' . $v;
}
$atts[ $k ] = $v;
}
// return
return $atts;
}
/*
* acf_esc_attr
*
* This function will return a render of an array of attributes to be used in markup
*
* @type function
* @date 1/10/13
* @since 5.0.0
*
* @param $atts (array)
* @return n/a
*/
function acf_esc_attr( $atts ) {
// is string?
if( is_string($atts) ) {
$atts = trim( $atts );
return esc_attr( $atts );
}
// validate
if( empty($atts) ) {
return '';
}
// vars
$e = array();
// loop through and render
foreach( $atts as $k => $v ) {
// object
if( is_array($v) || is_object($v) ) {
$v = json_encode($v);
// boolean
} elseif( is_bool($v) ) {
$v = $v ? 1 : 0;
// string
} elseif( is_string($v) ) {
$v = trim($v);
}
// append
$e[] = $k . '="' . esc_attr( $v ) . '"';
}
// echo
return implode(' ', $e);
}
function acf_esc_attr_e( $atts ) {
echo acf_esc_attr( $atts );
}
/*
* acf_hidden_input
*
* description
*
* @type function
* @date 3/02/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_get_hidden_input( $atts ) {
$atts['type'] = 'hidden';
return '<input ' . acf_esc_attr( $atts ) . ' />';
}
function acf_hidden_input( $atts ) {
echo acf_get_hidden_input( $atts );
}
/*
* acf_extract_var
*
* This function will remove the var from the array, and return the var
*
* @type function
* @date 2/10/13
* @since 5.0.0
*
* @param $array (array)
* @param $key (string)
* @return (mixed)
*/
function acf_extract_var( &$array, $key ) {
// check if exists
if( is_array($array) && array_key_exists($key, $array) ) {
// store value
$v = $array[ $key ];
// unset
unset( $array[ $key ] );
// return
return $v;
}
// return
return null;
}
/*
* acf_extract_vars
*
* This function will remove the vars from the array, and return the vars
*
* @type function
* @date 8/10/13
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_extract_vars( &$array, $keys ) {
$r = array();
foreach( $keys as $key ) {
$r[ $key ] = acf_extract_var( $array, $key );
}
return $r;
}
/*
* acf_get_post_types
*
* This function will return an array of available post types
*
* @type function
* @date 7/10/13
* @since 5.0.0
*
* @param $exclude (array)
* @param $include (array)
* @return (array)
*/
function acf_get_post_types( $exclude = array(), $include = array() ) {
// get all custom post types
$post_types = get_post_types();
// core exclude
$exclude = wp_parse_args( $exclude, array('acf-field', 'acf-field-group', 'revision', 'nav_menu_item') );
// include
if( !empty($include) ) {
foreach( array_keys($include) as $i ) {
$post_type = $include[ $i ];
if( post_type_exists($post_type) ) {
$post_types[ $post_type ] = $post_type;
}
}
}
// exclude
foreach( array_values($exclude) as $i ) {
unset( $post_types[ $i ] );
}
// simplify keys
$post_types = array_values($post_types);
// return
return $post_types;
}
function acf_get_pretty_post_types( $post_types = array() ) {
// get post types
if( empty($post_types) ) {
// get all custom post types
$post_types = acf_get_post_types();
}
// get labels
$ref = array();
$r = array();
foreach( $post_types as $post_type ) {
// vars
$label = $post_type;
// check that object exists (case exists when importing field group from another install and post type does not exist)
if( post_type_exists($post_type) ) {
$obj = get_post_type_object($post_type);
$label = $obj->labels->singular_name;
}
// append to r
$r[ $post_type ] = $label;
// increase counter
if( !isset($ref[ $label ]) ) {
$ref[ $label ] = 0;
}
$ref[ $label ]++;
}
// get slugs
foreach( array_keys($r) as $i ) {
// vars
$post_type = $r[ $i ];
if( $ref[ $post_type ] > 1 ) {
$r[ $i ] .= ' (' . $i . ')';
}
}
// return
return $r;
}
/*
* acf_verify_nonce
*
* This function will look at the $_POST['_acfnonce'] value and return true or false
*
* @type function
* @date 15/10/13
* @since 5.0.0
*
* @param $nonce (string)
* @return (boolean)
*/
function acf_verify_nonce( $value, $post_id = 0 ) {
// vars
$nonce = acf_maybe_get( $_POST, '_acfnonce' );
// bail early if no nonce or if nonce does not match (post|user|comment|term)
if( !$nonce || !wp_verify_nonce($nonce, $value) ) {
return false;
}
// if saving specific post
if( $post_id ) {
// vars
$form_post_id = (int) acf_maybe_get( $_POST, 'post_ID' );
$post_parent = wp_is_post_revision( $post_id );
// 1. no $_POST['post_id'] (shopp plugin)
if( !$form_post_id ) {
// do nothing (don't remove this if statement!)
// 2. direct match (this is the post we were editing)
} elseif( $post_id === $form_post_id ) {
// do nothing (don't remove this if statement!)
// 3. revision (this post is a revision of the post we were editing)
} elseif( $post_parent === $form_post_id ) {
// return true early and prevent $_POST['_acfnonce'] from being reset
// this will allow another save_post to save the real post
return true;
// 4. no match (this post is a custom created one during the save proccess via either WP or 3rd party)
} else {
// return false early and prevent $_POST['_acfnonce'] from being reset
// this will allow another save_post to save the real post
return false;
}
}
// reset nonce (only allow 1 save)
$_POST['_acfnonce'] = false;
// return
return true;
}
/*
* acf_verify_ajax
*
* This function will return true if the current AJAX request is valid
* It's action will also allow WPML to set the lang and avoid AJAX get_posts issues
*
* @type function
* @date 7/08/2015
* @since 5.2.3
*
* @param n/a
* @return (boolean)
*/
function acf_verify_ajax() {
// bail early if not acf action
if( empty($_POST['action']) || substr($_POST['action'], 0, 3) !== 'acf' ) {
return false;
}
// bail early if not acf nonce
if( empty($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'acf_nonce') ) {
return false;
}
// action for 3rd party customization
do_action('acf/verify_ajax');
// return
return true;
}
/*
* acf_add_admin_notice
*
* This function will add the notice data to a setting in the acf object for the admin_notices action to use
*
* @type function
* @date 17/10/13
* @since 5.0.0
*
* @param $text (string)
* @param $class (string)
* @return (int) message ID (array position)
*/
function acf_add_admin_notice( $text, $class = '', $wrap = 'p' )
{
// vars
$admin_notices = acf_get_admin_notices();
// add to array
$admin_notices[] = array(
'text' => $text,
'class' => "updated {$class}",
'wrap' => $wrap
);
// update
acf_update_setting( 'admin_notices', $admin_notices );
// return
return ( count( $admin_notices ) - 1 );
}
/*
* acf_get_admin_notices
*
* This function will return an array containing any admin notices
*
* @type function
* @date 17/10/13
* @since 5.0.0
*
* @param n/a
* @return (array)
*/
function acf_get_admin_notices()
{
// vars
$admin_notices = acf_get_setting( 'admin_notices' );
// validate
if( !$admin_notices )
{
$admin_notices = array();
}
// return
return $admin_notices;
}
/*
* acf_get_image_sizes
*
* This function will return an array of available image sizes
*
* @type function
* @date 23/10/13
* @since 5.0.0
*
* @param n/a
* @return (array)
*/
function acf_get_image_sizes() {
// global
global $_wp_additional_image_sizes;
// vars
$sizes = array(
'thumbnail' => __("Thumbnail",'acf'),
'medium' => __("Medium",'acf'),
'large' => __("Large",'acf')
);
// find all sizes
$all_sizes = get_intermediate_image_sizes();
// add extra registered sizes
if( !empty($all_sizes) ) {
foreach( $all_sizes as $size ) {
// bail early if already in array
if( isset($sizes[ $size ]) ) {
continue;
}
// append to array
$label = str_replace('-', ' ', $size);
$label = ucwords( $label );
$sizes[ $size ] = $label;
}
}
// add sizes
foreach( array_keys($sizes) as $s ) {
// vars
$w = isset($_wp_additional_image_sizes[$s]['width']) ? $_wp_additional_image_sizes[$s]['width'] : get_option( "{$s}_size_w" );
$h = isset($_wp_additional_image_sizes[$s]['height']) ? $_wp_additional_image_sizes[$s]['height'] : get_option( "{$s}_size_h" );
if( $w && $h ) {
$sizes[ $s ] .= " ({$w} x {$h})";
}
}
// add full end
$sizes['full'] = __("Full Size",'acf');
// filter for 3rd party customization
$sizes = apply_filters( 'acf/get_image_sizes', $sizes );
// return
return $sizes;
}
/*
* acf_get_taxonomies
*
* This function will return an array of available taxonomies
*
* @type function
* @date 7/10/13
* @since 5.0.0
*
* @param n/a
* @return (array)
*/
function acf_get_taxonomies() {
// get all taxonomies
$taxonomies = get_taxonomies( false, 'objects' );
$ignore = array( 'nav_menu', 'link_category' );
$r = array();
// populate $r
foreach( $taxonomies as $taxonomy )
{
if( in_array($taxonomy->name, $ignore) )
{
continue;
}
$r[ $taxonomy->name ] = $taxonomy->name; //"{$taxonomy->labels->singular_name}"; // ({$taxonomy->name})
}
// return
return $r;
}
function acf_get_pretty_taxonomies( $taxonomies = array() ) {
// get post types
if( empty($taxonomies) ) {
// get all custom post types
$taxonomies = acf_get_taxonomies();
}
// get labels
$ref = array();
$r = array();
foreach( array_keys($taxonomies) as $i ) {
// vars
$taxonomy = acf_extract_var( $taxonomies, $i);
$obj = get_taxonomy( $taxonomy );
$name = $obj->labels->singular_name;
// append to r
$r[ $taxonomy ] = $name;
// increase counter
if( !isset($ref[ $name ]) ) {
$ref[ $name ] = 0;
}
$ref[ $name ]++;
}
// get slugs
foreach( array_keys($r) as $i ) {
// vars
$taxonomy = $r[ $i ];
if( $ref[ $taxonomy ] > 1 ) {
$r[ $i ] .= ' (' . $i . ')';
}
}
// return
return $r;
}
/*
* acf_get_taxonomy_terms
*
* This function will return an array of available taxonomy terms
*
* @type function
* @date 7/10/13
* @since 5.0.0
*
* @param $taxonomies (array)
* @return (array)
*/
function acf_get_taxonomy_terms( $taxonomies = array() ) {
// force array
$taxonomies = acf_get_array( $taxonomies );
// get pretty taxonomy names
$taxonomies = acf_get_pretty_taxonomies( $taxonomies );
// vars
$r = array();
// populate $r
foreach( array_keys($taxonomies) as $taxonomy ) {
// vars
$label = $taxonomies[ $taxonomy ];
$terms = get_terms( $taxonomy, array( 'hide_empty' => false ) );
if( !empty($terms) ) {
$r[ $label ] = array();
foreach( $terms as $term ) {
$k = "{$taxonomy}:{$term->slug}";
$r[ $label ][ $k ] = $term->name;
}
}
}
// return
return $r;
}
/*
* acf_decode_taxonomy_terms
*
* This function decodes the $taxonomy:$term strings into a nested array
*
* @type function
* @date 27/02/2014
* @since 5.0.0
*
* @param $terms (array)
* @return (array)
*/
function acf_decode_taxonomy_terms( $terms = false ) {
// load all taxonomies if not specified in args
if( !$terms ) {
$terms = acf_get_taxonomy_terms();
}
// vars
$r = array();
foreach( $terms as $term ) {
// vars
$data = acf_decode_taxonomy_term( $term );
// create empty array
if( !array_key_exists($data['taxonomy'], $r) )
{
$r[ $data['taxonomy'] ] = array();
}
// append to taxonomy
$r[ $data['taxonomy'] ][] = $data['term'];
}
// return
return $r;
}
/*
* acf_decode_taxonomy_term
*
* This function will convert a term string into an array of term data
*
* @type function
* @date 31/03/2014
* @since 5.0.0
*
* @param $string (string)
* @return (array)
*/
function acf_decode_taxonomy_term( $string ) {
// vars
$r = array();
// vars
$data = explode(':', $string);
$taxonomy = 'category';
$term = '';
// check data
if( isset($data[1]) ) {
$taxonomy = $data[0];
$term = $data[1];
}
// add data to $r
$r['taxonomy'] = $taxonomy;
$r['term'] = $term;
// return
return $r;
}
/*
* acf_cache_get
*
* This function is a wrapper for the wp_cache_get to allow for 3rd party customization
*
* @type function
* @date 4/12/2013
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
/*
function acf_cache_get( $key, &$found ) {
// vars
$group = 'acf';
$force = false;
// load from cache
$cache = wp_cache_get( $key, $group, $force, $found );
// allow 3rd party customization if cache was not found
if( !$found )
{
$custom = apply_filters("acf/get_cache/{$key}", $cache);
if( $custom !== $cache )
{
$cache = $custom;
$found = true;
}
}
// return
return $cache;
}
*/
/*
* acf_get_array
*
* This function will force a variable to become an array
*
* @type function
* @date 4/02/2014
* @since 5.0.0
*
* @param $var (mixed)
* @return (array)
*/
function acf_get_array( $var = false, $delimiter = ',' ) {
// is array?
if( is_array($var) ) {
return $var;
}
// bail early if empty
if( empty($var) && !is_numeric($var) ) {
return array();
}
// string
if( is_string($var) && $delimiter ) {
return explode($delimiter, $var);
}
// place in array
return array( $var );
}
/*
* acf_get_posts
*
* This function will return an array of posts making sure the order is correct
*
* @type function
* @date 3/03/2015
* @since 5.1.5
*
* @param $args (array)
* @return (array)
*/
function acf_get_posts( $args = array() ) {
// vars
$posts = array();
// defaults
// leave suppress_filters as true becuase we don't want any plugins to modify the query as we know exactly what
$args = acf_parse_args( $args, array(
'posts_per_page' => -1,
'post_type' => '',
'post_status' => 'any'
));
// post type
if( empty($args['post_type']) ) {
$args['post_type'] = acf_get_post_types();
}
// validate post__in
if( $args['post__in'] ) {
// force value to array
$args['post__in'] = acf_get_array( $args['post__in'] );
// convert to int
$args['post__in'] = array_map('intval', $args['post__in']);
// add filter to remove post_type
// use 'query' filter so that 'suppress_filters' can remain true
//add_filter('query', '_acf_query_remove_post_type');
// order by post__in
$args['orderby'] = 'post__in';
}
// load posts in 1 query to save multiple DB calls from following code
$posts = get_posts($args);
// remove this filter (only once)
//remove_filter('query', '_acf_query_remove_post_type');
// validate order
if( $posts && $args['post__in'] ) {
// vars
$order = array();
// generate sort order
foreach( $posts as $i => $post ) {
$order[ $i ] = array_search($post->ID, $args['post__in']);
}
// sort
array_multisort($order, $posts);
}
// return
return $posts;
}
/*
* _acf_query_remove_post_type
*
* This function will remove the 'wp_posts.post_type' WHERE clause completely
* When using 'post__in', this clause is unneccessary and slow.
*
* @type function
* @date 4/03/2015
* @since 5.1.5
*
* @param $sql (string)
* @return $sql
*/
function _acf_query_remove_post_type( $sql ) {
// global
global $wpdb;
// bail ealry if no 'wp_posts.ID IN'
if( strpos($sql, "$wpdb->posts.ID IN") === false ) {
return $sql;
}
// get bits
$glue = 'AND';
$bits = explode($glue, $sql);
// loop through $where and remove any post_type queries
foreach( $bits as $i => $bit ) {
if( strpos($bit, "$wpdb->posts.post_type") !== false ) {
unset( $bits[ $i ] );
}
}
// join $where back together
$sql = implode($glue, $bits);
// return
return $sql;
}
/*
* acf_get_grouped_posts
*
* This function will return all posts grouped by post_type
* This is handy for select settings
*
* @type function
* @date 27/02/2014
* @since 5.0.0
*
* @param $args (array)
* @return (array)
*/
function acf_get_grouped_posts( $args ) {
// vars
$r = array();
// defaults
$args = acf_parse_args( $args, array(
'posts_per_page' => -1,
'paged' => 0,
'post_type' => 'post',
'orderby' => 'menu_order title',
'order' => 'ASC',
'post_status' => 'any',
'suppress_filters' => false,
'update_post_meta_cache' => false,
));
// find array of post_type
$post_types = acf_get_array( $args['post_type'] );
$post_types_labels = acf_get_pretty_post_types($post_types);
// attachment doesn't work if it is the only item in an array
if( count($post_types) == 1 ) {
$args['post_type'] = current($post_types);
}
// add filter to orderby post type
add_filter('posts_orderby', '_acf_orderby_post_type', 10, 2);
// get posts
$posts = get_posts( $args );
// remove this filter (only once)
remove_filter('posts_orderby', '_acf_orderby_post_type');
// loop
foreach( $post_types as $post_type ) {
// vars
$this_posts = array();
$this_group = array();
// populate $this_posts
foreach( array_keys($posts) as $key ) {
if( $posts[ $key ]->post_type == $post_type ) {
$this_posts[] = acf_extract_var( $posts, $key );
}
}
// bail early if no posts for this post type
if( empty($this_posts) ) {
continue;
}
// sort into hierachial order!
// this will fail if a search has taken place because parents wont exist
if( is_post_type_hierarchical($post_type) && empty($args['s'])) {
// vars
$match_id = $this_posts[ 0 ]->ID;
$offset = 0;
$length = count($this_posts);
$parent = acf_maybe_get( $args, 'post_parent', 0 );
// reset $this_posts
$this_posts = array();
// get all posts
$all_args = array_merge($args, array(
'posts_per_page' => -1,
'paged' => 0,
'post_type' => $post_type
));
$all_posts = get_posts( $all_args );
// loop over posts and update $offset
foreach( $all_posts as $offset => $p ) {
if( $p->ID == $match_id ) {
break;
}
}
// order posts
$all_posts = get_page_children( $parent, $all_posts );
// append
for( $i = $offset; $i < ($offset + $length); $i++ ) {
$this_posts[] = acf_extract_var( $all_posts, $i);
}
}
// populate $this_posts
foreach( array_keys($this_posts) as $key ) {
// extract post
$post = acf_extract_var( $this_posts, $key );
// add to group
$this_group[ $post->ID ] = $post;
}
// group by post type
$post_type_name = $post_types_labels[ $post_type ];
$r[ $post_type_name ] = $this_group;
}
// return
return $r;
}
function _acf_orderby_post_type( $ordeby, $wp_query ) {
// global
global $wpdb;
// get post types
$post_types = $wp_query->get('post_type');
// prepend SQL
if( is_array($post_types) ) {
$post_types = implode("','", $post_types);
$ordeby = "FIELD({$wpdb->posts}.post_type,'$post_types')," . $ordeby;
}
// return
return $ordeby;
}
function acf_get_post_title( $post = 0 ) {
// load post if given an ID
if( is_numeric($post) ) {
$post = get_post($post);
}
// title
$title = get_the_title( $post->ID );
// empty
if( $title === '' ) {
$title = __('(no title)', 'acf');
}
// ancestors
if( $post->post_type != 'attachment' ) {
$ancestors = get_ancestors( $post->ID, $post->post_type );
$title = str_repeat('- ', count($ancestors)) . $title;
}
// status
if( get_post_status( $post->ID ) != "publish" ) {
$title .= ' (' . get_post_status( $post->ID ) . ')';
}
// return
return $title;
}
function acf_order_by_search( $array, $search ) {
// vars
$weights = array();
$needle = strtolower( $search );
// add key prefix
foreach( array_keys($array) as $k ) {
$array[ '_' . $k ] = acf_extract_var( $array, $k );
}
// add search weight
foreach( $array as $k => $v ) {
// vars
$weight = 0;
$haystack = strtolower( $v );
$strpos = strpos( $haystack, $needle );
// detect search match
if( $strpos !== false ) {
// set eright to length of match
$weight = strlen( $search );
// increase weight if match starts at begining of string
if( $strpos == 0 ) {
$weight++;
}
}
// append to wights
$weights[ $k ] = $weight;
}
// sort the array with menu_order ascending
array_multisort( $weights, SORT_DESC, $array );
// remove key prefix
foreach( array_keys($array) as $k ) {
$array[ substr($k,1) ] = acf_extract_var( $array, $k );
}
// return
return $array;
}
/*
* acf_json_encode
*
* This function will return pretty JSON for all PHP versions
*
* @type function
* @date 6/03/2014
* @since 5.0.0
*
* @param $json (array)
* @return (string)
*/
function acf_json_encode( $json ) {
// PHP at least 5.4
if( version_compare(PHP_VERSION, '5.4.0', '>=') ) {
return json_encode($json, JSON_PRETTY_PRINT);
}
// PHP less than 5.4
$json = json_encode($json);
// http://snipplr.com/view.php?codeview&id=60559
$result = '';
$pos = 0;
$strLen = strlen($json);
$indentStr = " ";
$newLine = "\n";
$prevChar = '';
$outOfQuotes = true;
for ($i=0; $i<=$strLen; $i++) {
// Grab the next character in the string.
$char = substr($json, $i, 1);
// Are we inside a quoted string?
if ($char == '"' && $prevChar != '\\') {
$outOfQuotes = !$outOfQuotes;
// If this character is the end of an element,
// output a new line and indent the next line.
} else if(($char == '}' || $char == ']') && $outOfQuotes) {
$result .= $newLine;
$pos --;
for ($j=0; $j<$pos; $j++) {
$result .= $indentStr;
}
}
// Add the character to the result string.
$result .= $char;
// If this character is ':' adda space after it
if($char == ':' && $outOfQuotes) {
$result .= ' ';
}
// If the last character was the beginning of an element,
// output a new line and indent the next line.
if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
$result .= $newLine;
if ($char == '{' || $char == '[') {
$pos ++;
}
for ($j = 0; $j < $pos; $j++) {
$result .= $indentStr;
}
}
$prevChar = $char;
}
// return
return $result;
}
/*
* acf_str_exists
*
* This function will return true if a sub string is found
*
* @type function
* @date 1/05/2014
* @since 5.0.0
*
* @param $needle (string)
* @param $haystack (string)
* @return (boolean)
*/
function acf_str_exists( $needle, $haystack ) {
// return true if $haystack contains the $needle
if( is_string($haystack) && strpos($haystack, $needle) !== false ) {
return true;
}
// return
return false;
}
/*
* acf_debug
*
* description
*
* @type function
* @date 2/05/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_debug() {
// vars
$args = func_get_args();
$s = array_shift($args);
$o = '';
$nl = "\r\n";
// start script
$o .= '<script type="text/javascript">' . $nl;
$o .= 'console.log("' . $s . '"';
if( !empty($args) ) {
foreach( $args as $arg ) {
if( is_object($arg) || is_array($arg) ) {
$arg = json_encode($arg);
} elseif( is_bool($arg) ) {
$arg = $arg ? 'true' : 'false';
}elseif( is_string($arg) ) {
$arg = '"' . $arg . '"';
}
$o .= ', ' . $arg;
}
}
$o .= ');' . $nl;
// end script
$o .= '</script>' . $nl;
// echo
echo $o;
}
function acf_debug_start() {
acf_update_setting( 'debug_start', memory_get_usage());
}
function acf_debug_end() {
$start = acf_get_setting( 'debug_start' );
$end = memory_get_usage();
return $end - $start;
}
/*
* acf_get_updates
*
* This function will reutrn all or relevant updates for ACF
*
* @type function
* @date 12/05/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_get_updates() {
// vars
$updates = array();
$plugin_version = acf_get_setting('version');
$acf_version = get_option('acf_version');
$path = acf_get_path('admin/updates');
// bail early if no version (not activated)
if( !$acf_version ) {
return false;
}
// check that path exists
if( !file_exists( $path ) ) {
return false;
}
$dir = opendir( $path );
while(false !== ( $file = readdir($dir)) ) {
// only php files
if( substr($file, -4) !== '.php' ) {
continue;
}
// get version number
$update_version = substr($file, 0, -4);
// ignore if update is for a future version. May exist for testing
if( version_compare( $update_version, $plugin_version, '>') ) {
continue;
}
// ignore if update has already been run
if( version_compare( $update_version, $acf_version, '<=') ) {
continue;
}
// append
$updates[] = $update_version;
}
// return
return $updates;
}
/*
* acf_encode_choices
*
* description
*
* @type function
* @date 4/06/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_encode_choices( $array = array() ) {
// bail early if not array
if( !is_array($array) ) {
return $array;
}
// vars
$string = '';
if( !empty($array) ) {
foreach( $array as $k => $v ) {
if( $k !== $v ) {
$array[ $k ] = $k . ' : ' . $v;
}
}
$string = implode("\n", $array);
}
// return
return $string;
}
function acf_decode_choices( $string = '' ) {
// validate
if( $string === '') {
return array();
// force array on single numeric values
} elseif( is_numeric($string) ) {
return array( $string );
// bail early if not a a string
} elseif( !is_string($string) ) {
return $string;
}
// vars
$array = array();
// explode
$lines = explode("\n", $string);
// key => value
foreach( $lines as $line ) {
// vars
$k = trim($line);
$v = trim($line);
// look for ' : '
if( acf_str_exists(' : ', $line) ) {
$line = explode(' : ', $line);
$k = trim($line[0]);
$v = trim($line[1]);
}
// append
$array[ $k ] = $v;
}
// return
return $array;
}
/*
* acf_convert_date_to_php
*
* This fucntion converts a date format string from JS to PHP
*
* @type function
* @date 20/06/2014
* @since 5.0.0
*
* @param $date (string)
* @return $date (string)
*/
acf_update_setting('php_to_js_date_formats', array(
// Year
'Y' => 'yy', // Numeric, 4 digits 1999, 2003
'y' => 'y', // Numeric, 2 digits 99, 03
// Month
'm' => 'mm', // Numeric, with leading zeros 01–12
'n' => 'm', // Numeric, without leading zeros 1–12
'F' => 'MM', // Textual full January – December
'M' => 'M', // Textual three letters Jan - Dec
// Weekday
'l' => 'DD', // Full name (lowercase 'L') Sunday – Saturday
'D' => 'D', // Three letter name Mon – Sun
// Day of Month
'd' => 'dd', // Numeric, with leading zeros 01–31
'j' => 'd', // Numeric, without leading zeros 1–31
'S' => '', // The English suffix for the day of the month st, nd or th in the 1st, 2nd or 15th.
));
function acf_convert_date_to_php( $date ) {
// vars
$ignore = array();
// conversion
$php_to_js = acf_get_setting('php_to_js_date_formats');
// loop over conversions
foreach( $php_to_js as $replace => $search ) {
// ignore this replace?
if( in_array($search, $ignore) ) {
continue;
}
// replace
$date = str_replace($search, $replace, $date);
// append to ignore
$ignore[] = $replace;
}
// return
return $date;
}
/*
* acf_convert_date_to_js
*
* This fucntion converts a date format string from PHP to JS
*
* @type function
* @date 20/06/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_convert_date_to_js( $date ) {
// vars
$ignore = array();
// conversion
$php_to_js = acf_get_setting('php_to_js_date_formats');
// loop over conversions
foreach( $php_to_js as $search => $replace ) {
// ignore this replace?
if( in_array($search, $ignore) ) {
continue;
}
// replace
$date = str_replace($search, $replace, $date);
// append to ignore
$ignore[] = $replace;
}
// return
return $date;
}
/*
* acf_update_user_setting
*
* description
*
* @type function
* @date 15/07/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_update_user_setting( $name, $value ) {
// get current user id
$user_id = get_current_user_id();
// get user settings
$settings = get_user_meta( $user_id, 'acf_user_settings', false );
// find settings
if( isset($settings[0]) ) {
$settings = $settings[0];
} else {
$settings = array();
}
// append setting
$settings[ $name ] = $value;
// update user data
return update_metadata('user', $user_id, 'acf_user_settings', $settings);
}
/*
* acf_get_user_setting
*
* description
*
* @type function
* @date 15/07/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_get_user_setting( $name = '', $default = false ) {
// get current user id
$user_id = get_current_user_id();
// get user settings
$settings = get_user_meta( $user_id, 'acf_user_settings', false );
// bail arly if no settings
if( empty($settings[0][$name]) ) {
return $default;
}
// return
return $settings[0][$name];
}
/*
* acf_in_array
*
* description
*
* @type function
* @date 22/07/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_in_array( $value, $array ) {
// bail early if not array
if( !is_array($array) ) {
return false;
}
// find value in array
return in_array($value, $array);
}
/*
* acf_get_valid_post_id
*
* This function will return a valid post_id based on the current screen / parameter
*
* @type function
* @date 8/12/2013
* @since 5.0.0
*
* @param $post_id (mixed)
* @return $post_id (mixed)
*/
function acf_get_valid_post_id( $post_id = 0 ) {
// set post_id to global
if( !$post_id ) {
$post_id = (int) get_the_ID();
}
// allow for option == options
if( $post_id == 'option' ) {
$post_id = 'options';
}
// $post_id may be an object
if( is_object($post_id) ) {
if( isset($post_id->roles, $post_id->ID) ) {
$post_id = 'user_' . $post_id->ID;
} elseif( isset($post_id->taxonomy, $post_id->term_id) ) {
$post_id = $post_id->taxonomy . '_' . $post_id->term_id;
} elseif( isset($post_id->comment_ID) ) {
$post_id = 'comment_' . $post_id->comment_ID;
} elseif( isset($post_id->ID) ) {
$post_id = $post_id->ID;
}
}
// append language code
if( $post_id == 'options' ) {
$dl = acf_get_setting('default_language');
$cl = acf_get_setting('current_language');
if( $cl && $cl !== $dl ) {
$post_id .= '_' . $cl;
}
}
/*
* Override for preview
*
* If the $_GET['preview_id'] is set, then the user wants to see the preview data.
* There is also the case of previewing a page with post_id = 1, but using get_field
* to load data from another post_id.
* In this case, we need to make sure that the autosave revision is actually related
* to the $post_id variable. If they match, then the autosave data will be used, otherwise,
* the user wants to load data from a completely different post_id
*/
if( isset($_GET['preview_id']) ) {
$autosave = wp_get_post_autosave( $_GET['preview_id'] );
if( $autosave && $autosave->post_parent == $post_id ) {
$post_id = (int) $autosave->ID;
}
}
// return
return $post_id;
}
/*
* acf_upload_files
*
* This function will walk througfh the $_FILES data and upload each found
*
* @type function
* @date 25/10/2014
* @since 5.0.9
*
* @param $ancestors (array) an internal parameter, not required
* @return n/a
*/
function acf_upload_files( $ancestors = array() ) {
// vars
$file = array(
'name' => '',
'type' => '',
'tmp_name' => '',
'error' => '',
'size' => ''
);
// populate with $_FILES data
foreach( array_keys($file) as $k ) {
$file[ $k ] = $_FILES['acf'][ $k ];
}
// walk through ancestors
if( !empty($ancestors) ) {
foreach( $ancestors as $a ) {
foreach( array_keys($file) as $k ) {
$file[ $k ] = $file[ $k ][ $a ];
}
}
}
// is array?
if( is_array($file['name']) ) {
foreach( array_keys($file['name']) as $k ) {
$_ancestors = array_merge($ancestors, array($k));
acf_upload_files( $_ancestors );
}
return;
}
// bail ealry if file has error (no file uploaded)
if( $file['error'] ) {
return;
}
// assign global _acfuploader for media validation
$_POST['_acfuploader'] = end($ancestors);
// file found!
$attachment_id = acf_upload_file( $file );
// update $_POST
array_unshift($ancestors, 'acf');
acf_update_nested_array( $_POST, $ancestors, $attachment_id );
}
/*
* acf_upload_file
*
* This function will uploade a $_FILE
*
* @type function
* @date 27/10/2014
* @since 5.0.9
*
* @param $uploaded_file (array) array found from $_FILE data
* @return $id (int) new attachment ID
*/
function acf_upload_file( $uploaded_file ) {
// required
require_once(ABSPATH . "/wp-load.php");
require_once(ABSPATH . "/wp-admin/includes/file.php");
require_once(ABSPATH . "/wp-admin/includes/image.php");
// required for wp_handle_upload() to upload the file
$upload_overrides = array( 'test_form' => false );
// upload
$file = wp_handle_upload( $uploaded_file, $upload_overrides );
// bail ealry if upload failed
if( isset($file['error']) ) {
return $file['error'];
}
// vars
$url = $file['url'];
$type = $file['type'];
$file = $file['file'];
$filename = basename($file);
// Construct the object array
$object = array(
'post_title' => $filename,
'post_mime_type' => $type,
'guid' => $url,
'context' => 'acf-upload'
);
// Save the data
$id = wp_insert_attachment($object, $file);
// Add the meta-data
wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $file ) );
/** This action is documented in wp-admin/custom-header.php */
do_action( 'wp_create_file_in_uploads', $file, $id ); // For replication
// return new ID
return $id;
}
/*
* acf_update_nested_array
*
* This function will update a nested array value. Useful for modifying the $_POST array
*
* @type function
* @date 27/10/2014
* @since 5.0.9
*
* @param $array (array) target array to be updated
* @param $ancestors (array) array of keys to navigate through to find the child
* @param $value (mixed) The new value
* @return (boolean)
*/
function acf_update_nested_array( &$array, $ancestors, $value ) {
// if no more ancestors, update the current var
if( empty($ancestors) ) {
$array = $value;
// return
return true;
}
// shift the next ancestor from the array
$k = array_shift( $ancestors );
// if exists
if( isset($array[ $k ]) ) {
return acf_update_nested_array( $array[ $k ], $ancestors, $value );
}
// return
return false;
}
/*
* acf_is_screen
*
* This function will return true if all args are matched for the current screen
*
* @type function
* @date 9/12/2014
* @since 5.1.5
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_is_screen( $id = '' ) {
// vars
$current_screen = get_current_screen();
// return
return ($id === $current_screen->id);
}
/*
* acf_maybe_get
*
* This function will return a var if it exists in an array
*
* @type function
* @date 9/12/2014
* @since 5.1.5
*
* @param $array (array) the array to look within
* @param $key (key) the array key to look for. Nested values may be found using '/'
* @param $default (mixed) the value returned if not found
* @return $post_id (int)
*/
function acf_maybe_get( $array, $key, $default = null ) {
// vars
$keys = explode('/', $key);
// loop through keys
foreach( $keys as $k ) {
// return default if does not exist
if( !isset($array[ $k ]) ) {
return $default;
}
// update $array
$array = $array[ $k ];
}
// return
return $array;
}
/*
* acf_get_attachment
*
* This function will return an array of attachment data
*
* @type function
* @date 5/01/2015
* @since 5.1.5
*
* @param $post (mixed) either post ID or post object
* @return (array)
*/
function acf_get_attachment( $post ) {
// get post
if ( !$post = get_post( $post ) ) {
return false;
}
// vars
$thumb_id = 0;
$id = $post->ID;
$a = array(
'ID' => $id,
'id' => $id,
'title' => $post->post_title,
'filename' => wp_basename( $post->guid ),
'url' => wp_get_attachment_url( $id ),
'alt' => get_post_meta($id, '_wp_attachment_image_alt', true),
'author' => $post->post_author,
'description' => $post->post_content,
'caption' => $post->post_excerpt,
'name' => $post->post_name,
'date' => $post->post_date_gmt,
'modified' => $post->post_modified_gmt,
'mime_type' => $post->post_mime_type,
'type' => acf_maybe_get( explode('/', $post->post_mime_type), 0, '' ),
'icon' => wp_mime_type_icon( $id )
);
// video may use featured image
if( $a['type'] === 'image' ) {
$thumb_id = $id;
$src = wp_get_attachment_image_src( $id, 'full' );
$a['url'] = $src[0];
$a['width'] = $src[1];
$a['height'] = $src[2];
} elseif( $a['type'] === 'audio' || $a['type'] === 'video' ) {
// video dimentions
if( $a['type'] == 'video' ) {
$meta = wp_get_attachment_metadata( $id );
$a['width'] = acf_maybe_get($meta, 'width', 0);
$a['height'] = acf_maybe_get($meta, 'height', 0);
}
// feature image
if( $featured_id = get_post_thumbnail_id($id) ) {
$thumb_id = $featured_id;
}
}
// sizes
if( $thumb_id ) {
// find all image sizes
if( $sizes = get_intermediate_image_sizes() ) {
$a['sizes'] = array();
foreach( $sizes as $size ) {
// url
$src = wp_get_attachment_image_src( $thumb_id, $size );
// add src
$a['sizes'][ $size ] = $src[0];
$a['sizes'][ $size . '-width' ] = $src[1];
$a['sizes'][ $size . '-height' ] = $src[2];
}
}
}
// return
return $a;
}
/*
* acf_get_truncated
*
* This function will truncate and return a string
*
* @type function
* @date 8/08/2014
* @since 5.0.0
*
* @param $text (string)
* @param $length (int)
* @return (string)
*/
function acf_get_truncated( $text, $length = 64 ) {
// vars
$text = trim($text);
$the_length = strlen( $text );
// cut
$return = substr( $text, 0, ($length - 3) );
// ...
if( $the_length > ($length - 3) ) {
$return .= '...';
}
// return
return $return;
}
/*
* acf_get_current_url
*
* This function will return the current URL
*
* @type function
* @date 23/01/2015
* @since 5.1.5
*
* @param n/a
* @return (string)
*/
function acf_get_current_url() {
// vars
$home = home_url();
$url = home_url($_SERVER['REQUEST_URI']);
// test
//$home = 'http://acf5/dev/wp-admin';
//$url = $home . '/dev/wp-admin/api-template/acf_form';
// explode url (4th bit is the sub folder)
$bits = explode('/', $home, 4);
/*
Array (
[0] => http:
[1] =>
[2] => acf5
[3] => dev
)
*/
// handle sub folder
if( !empty($bits[3]) ) {
$find = '/' . $bits[3];
$pos = strpos($url, $find);
$length = strlen($find);
if( $pos !== false ) {
$url = substr_replace($url, '', $pos, $length);
}
}
// return
return $url;
}
/*
* acf_current_user_can_admin
*
* This function will return true if the current user can administrate the ACF field groups
*
* @type function
* @date 9/02/2015
* @since 5.1.5
*
* @param $post_id (int)
* @return $post_id (int)
*/
function acf_current_user_can_admin() {
if( acf_get_setting('show_admin') && current_user_can(acf_get_setting('capability')) ) {
return true;
}
// return
return false;
}
/*
* acf_get_filesize
*
* This function will return a numeric value of bytes for a given filesize string
*
* @type function
* @date 18/02/2015
* @since 5.1.5
*
* @param $size (mixed)
* @return (int)
*/
function acf_get_filesize( $size = 1 ) {
// vars
$unit = 'MB';
$units = array(
'TB' => 4,
'GB' => 3,
'MB' => 2,
'KB' => 1,
);
// look for $unit within the $size parameter (123 KB)
if( is_string($size) ) {
// vars
$custom = strtoupper( substr($size, -2) );
foreach( $units as $k => $v ) {
if( $custom === $k ) {
$unit = $k;
$size = substr($size, 0, -2);
}
}
}
// calc bytes
$bytes = floatval($size) * pow(1024, $units[$unit]);
// return
return $bytes;
}
/*
* acf_format_filesize
*
* This function will return a formatted string containing the filesize and unit
*
* @type function
* @date 18/02/2015
* @since 5.1.5
*
* @param $size (mixed)
* @return (int)
*/
function acf_format_filesize( $size = 1 ) {
// convert
$bytes = acf_get_filesize( $size );
// vars
$units = array(
'TB' => 4,
'GB' => 3,
'MB' => 2,
'KB' => 1,
);
// loop through units
foreach( $units as $k => $v ) {
$result = $bytes / pow(1024, $v);
if( $result >= 1 ) {
return $result . ' ' . $k;
}
}
// return
return $bytes . ' B';
}
/*
* acf_get_valid_terms
*
* This function will replace old terms with new split term ids
*
* @type function
* @date 27/02/2015
* @since 5.1.5
*
* @param $terms (int|array)
* @param $taxonomy (string)
* @return $terms
*/
function acf_get_valid_terms( $terms = false, $taxonomy = 'category' ) {
// bail early if function does not yet exist or
if( !function_exists('wp_get_split_term') || empty($terms) ) {
return $terms;
}
// vars
$is_array = is_array($terms);
// force into array
$terms = acf_get_array( $terms );
// force ints
$terms = array_map('intval', $terms);
// attempt to find new terms
foreach( $terms as $i => $term_id ) {
$new_term_id = wp_get_split_term($term_id, $taxonomy);
if( $new_term_id ) {
$terms[ $i ] = $new_term_id;
}
}
// revert array if needed
if( !$is_array ) {
$terms = $terms[0];
}
// return
return $terms;
}
/*
* acf_esc_html_deep
*
* Navigates through an array and escapes html from the values.
*
* @type function
* @date 10/06/2015
* @since 5.2.7
*
* @param $value (mixed)
* @return $value
*/
/*
function acf_esc_html_deep( $value ) {
// array
if( is_array($value) ) {
$value = array_map('acf_esc_html_deep', $value);
// object
} elseif( is_object($value) ) {
$vars = get_object_vars( $value );
foreach( $vars as $k => $v ) {
$value->{$k} = acf_esc_html_deep( $v );
}
// string
} elseif( is_string($value) ) {
$value = esc_html($value);
}
// return
return $value;
}
*/
/*
* acf_validate_attachment
*
* This function will validate an attachment based on a field's resrictions and return an array of errors
*
* @type function
* @date 3/07/2015
* @since 5.2.3
*
* @param $attachment (array) attachment data. Cahnges based on context
* @param $field (array) field settings containing restrictions
* @param $context (string) $file is different when uploading / preparing
* @return $errors (array)
*/
function acf_validate_attachment( $attachment, $field, $context = 'prepare' ) {
// vars
$errors = array();
$file = array(
'type' => '',
'width' => 0,
'height' => 0,
'size' => 0
);
// upload
if( $context == 'upload' ) {
// vars
$file['type'] = pathinfo($attachment['name'], PATHINFO_EXTENSION);
$file['size'] = filesize($attachment['tmp_name']);
if( strpos($attachment['type'], 'image') !== false ) {
$size = getimagesize($attachment['tmp_name']);
$file['width'] = acf_maybe_get($size, 0);
$file['height'] = acf_maybe_get($size, 1);
}
// prepare
} elseif( $context == 'prepare' ) {
$file['type'] = pathinfo($attachment['url'], PATHINFO_EXTENSION);
$file['size'] = acf_maybe_get($attachment, 'filesizeInBytes', 0);
$file['width'] = acf_maybe_get($attachment, 'width', 0);
$file['height'] = acf_maybe_get($attachment, 'height', 0);
// custom
} else {
$file = wp_parse_args($file, $attachment);
}
// image
if( $file['width'] || $file['height'] ) {
// width
$min_width = (int) acf_maybe_get($field, 'min_width', 0);
$max_width = (int) acf_maybe_get($field, 'max_width', 0);
if( $file['width'] ) {
if( $min_width && $file['width'] < $min_width ) {
// min width
$errors['min_width'] = sprintf(__('Image width must be at least %dpx.', 'acf'), $min_width );
} elseif( $max_width && $file['width'] > $max_width ) {
// min width
$errors['max_width'] = sprintf(__('Image width must not exceed %dpx.', 'acf'), $max_width );
}
}
// height
$min_height = (int) acf_maybe_get($field, 'min_height', 0);
$max_height = (int) acf_maybe_get($field, 'max_height', 0);
if( $file['height'] ) {
if( $min_height && $file['height'] < $min_height ) {
// min height
$errors['min_height'] = sprintf(__('Image height must be at least %dpx.', 'acf'), $min_height );
} elseif( $max_height && $file['height'] > $max_height ) {
// min height
$errors['max_height'] = sprintf(__('Image height must not exceed %dpx.', 'acf'), $max_height );
}
}
}
// file size
if( $file['size'] ) {
$min_size = acf_maybe_get($field, 'min_size', 0);
$max_size = acf_maybe_get($field, 'max_size', 0);
if( $min_size && $file['size'] < acf_get_filesize($min_size) ) {
// min width
$errors['min_size'] = sprintf(__('File size must be at least %s.', 'acf'), acf_format_filesize($min_size) );
} elseif( $max_size && $file['size'] > acf_get_filesize($max_size) ) {
// min width
$errors['max_size'] = sprintf(__('File size must must not exceed %s.', 'acf'), acf_format_filesize($max_size) );
}
}
// file type
if( $file['type'] ) {
$mime_types = acf_maybe_get($field, 'mime_types', '');
// lower case
$file['type'] = strtolower($file['type']);
$mime_types = strtolower($mime_types);
// explode
$mime_types = str_replace(array(' ', '.'), '', $mime_types);
$mime_types = explode(',', $mime_types); // split pieces
$mime_types = array_filter($mime_types); // remove empty pieces
if( !empty($mime_types) && !in_array($file['type'], $mime_types) ) {
// glue together last 2 types
if( count($mime_types) > 1 ) {
$last1 = array_pop($mime_types);
$last2 = array_pop($mime_types);
$mime_types[] = $last2 . ' ' . __('or', 'acf') . ' ' . $last1;
}
$errors['mime_types'] = sprintf(__('File type must be %s.', 'acf'), implode(', ', $mime_types) );
}
}
// filter for 3rd party customization
$errors = apply_filters("acf/validate_attachment", $errors, $file, $attachment, $field);
$errors = apply_filters("acf/validate_attachment/type={$field['type']}", $errors, $file, $attachment, $field );
$errors = apply_filters("acf/validate_attachment/name={$field['name']}", $errors, $file, $attachment, $field );
$errors = apply_filters("acf/validate_attachment/key={$field['key']}", $errors, $file, $attachment, $field );
// return
return $errors;
}
/*
* _acf_settings_uploader
*
* Dynamic logic for uploader setting
*
* @type function
* @date 7/05/2015
* @since 5.2.3
*
* @param $uploader (string)
* @return $uploader
*/
add_filter('acf/settings/uploader', '_acf_settings_uploader');
function _acf_settings_uploader( $uploader ) {
// if can't upload files
if( !current_user_can('upload_files') ) {
$uploader = 'basic';
}
// return
return $uploader;
}
/*
* Hacks
*
* description
*
* @type function
* @date 17/01/2014
* @since 5.0.0
*
* @param $post_id (int)
* @return $post_id (int)
*/
add_filter("acf/settings/slug", '_acf_settings_slug');
function _acf_settings_slug( $v ) {
$basename = acf_get_setting('basename');
$slug = explode('/', $basename);
$slug = current($slug);
return $slug;
}
?>
| thomasbodin/baltazare-test | wp-content/plugins/advanced-custom-fields-pro/api/api-helpers.php | PHP | gpl-2.0 | 54,778 |
<?xml version="1.0" encoding="UTF-8" ?>
<!--
If you are working with a multi language form keep the order!
<option lang="de">Deutschland</option>
<option lang="de">Groß Britannien</option>
<option lang="en">Germany</option>
<option lang="en">United Kingdom</option>
If you don't keep the order and the user switches the country you
will have a wrong translation!
-->
<select_countries>
<option lang="de">Deutschland</option>
<option lang="de">Groß Britannien</option>
<option lang="de">Frankreich</option>
<option lang="de">Österreich</option>
<option lang="en">Germany</option>
<option lang="en">United Kingdom</option>
<option lang="en">France</option>
<option lang="en">Austria</option>
</select_countries> | bjoernmainz/simple-contact-form | config/select_countries.xml.php | PHP | gpl-2.0 | 755 |
import { Query } from "../services";
export interface QueryState {
queries?: Query[];
loading?: boolean;
error?: String;
visibilityFilter?: string;
}
| mickem/nscp | web/src/state/query.state.ts | TypeScript | gpl-2.0 | 161 |
<?php
/**
* Plugin Installer List Table class.
*
* @package WordPress
* @subpackage List_Table
* @since 3.1.0
* @access private
*/
class WP_Plugin_Install_List_Table extends WP_List_Table {
function ajax_user_can() {
return current_user_can('install_plugins');
}
function prepare_items() {
include( ABSPATH . 'wp-admin/includes/plugin-install.php' );
global $tabs, $tab, $paged, $type, $term;
wp_reset_vars( array( 'tab' ) );
$paged = $this->get_pagenum();
$per_page = 30;
// These are the tabs which are shown on the page
$tabs = array();
$tabs['dashboard'] = __( 'Поиск' );
if ( 'search' == $tab )
$tabs['search'] = __( 'Search Results' );
$tabs['upload'] = __( 'Upload' );
$tabs['featured'] = _x( 'Featured','Plugin Installer' );
$tabs['popular'] = _x( 'Popular','Plugin Installer' );
$tabs['new'] = _x( 'Newest','Plugin Installer' );
$nonmenu_tabs = array( 'plugin-information' ); //Valid actions to perform which do not have a Menu item.
$tabs = apply_filters( 'install_plugins_tabs', $tabs );
$nonmenu_tabs = apply_filters( 'install_plugins_nonmenu_tabs', $nonmenu_tabs );
// If a non-valid menu tab has been selected, And its not a non-menu action.
if ( empty( $tab ) || ( !isset( $tabs[ $tab ] ) && !in_array( $tab, (array) $nonmenu_tabs ) ) )
$tab = key( $tabs );
$args = array( 'page' => $paged, 'per_page' => $per_page );
switch ( $tab ) {
case 'search':
$type = isset( $_REQUEST['type'] ) ? stripslashes( $_REQUEST['type'] ) : 'term';
$term = isset( $_REQUEST['s'] ) ? stripslashes( $_REQUEST['s'] ) : '';
switch ( $type ) {
case 'tag':
$args['tag'] = sanitize_title_with_dashes( $term );
break;
case 'term':
$args['search'] = $term;
break;
case 'author':
$args['author'] = $term;
break;
}
add_action( 'install_plugins_table_header', 'install_search_form', 10, 0 );
break;
case 'featured':
case 'popular':
case 'new':
$args['browse'] = $tab;
break;
default:
$args = false;
}
if ( !$args )
return;
$api = plugins_api( 'query_plugins', $args );
if ( is_wp_error( $api ) )
wp_die( $api->get_error_message() . '</p> <p class="hide-if-no-js"><a href="#" onclick="document.location.reload(); return false;">' . __( 'Try again' ) . '</a>' );
$this->items = $api->plugins;
$this->set_pagination_args( array(
'total_items' => $api->info['results'],
'per_page' => $per_page,
) );
}
function no_items() {
_e( 'No plugins match your request.' );
}
function get_views() {
global $tabs, $tab;
$display_tabs = array();
foreach ( (array) $tabs as $action => $text ) {
$class = ( $action == $tab ) ? ' class="current"' : '';
$href = self_admin_url('plugin-install.php?tab=' . $action);
$display_tabs['plugin-install-'.$action] = "<a href='$href'$class>$text</a>";
}
return $display_tabs;
}
function display_tablenav( $which ) {
if ( 'top' == $which ) { ?>
<div class="tablenav top">
<div class="alignleft actions">
<?php do_action( 'install_plugins_table_header' ); ?>
</div>
<?php $this->pagination( $which ); ?>
<img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" class="ajax-loading list-ajax-loading" alt="" />
<br class="clear" />
</div>
<?php } else { ?>
<div class="tablenav bottom">
<?php $this->pagination( $which ); ?>
<img src="<?php echo esc_url( admin_url( 'images/wpspin_light.gif' ) ); ?>" class="ajax-loading list-ajax-loading" alt="" />
<br class="clear" />
</div>
<?php
}
}
function get_table_classes() {
extract( $this->_args );
return array( 'widefat', $plural );
}
function get_columns() {
return array(
'name' => _x( 'Name', 'plugin name' ),
'version' => __( 'Version' ),
'rating' => __( 'Rating' ),
'description' => __( 'Description' ),
);
}
function display_rows() {
$plugins_allowedtags = array(
'a' => array( 'href' => array(),'title' => array(), 'target' => array() ),
'abbr' => array( 'title' => array() ),'acronym' => array( 'title' => array() ),
'code' => array(), 'pre' => array(), 'em' => array(),'strong' => array(),
'ul' => array(), 'ol' => array(), 'li' => array(), 'p' => array(), 'br' => array()
);
list( $columns, $hidden ) = $this->get_column_info();
$style = array();
foreach ( $columns as $column_name => $column_display_name ) {
$style[ $column_name ] = in_array( $column_name, $hidden ) ? 'style="display:none;"' : '';
}
foreach ( (array) $this->items as $plugin ) {
if ( is_object( $plugin ) )
$plugin = (array) $plugin;
$title = wp_kses( $plugin['name'], $plugins_allowedtags );
//Limit description to 400char, and remove any HTML.
$description = strip_tags( $plugin['description'] );
if ( strlen( $description ) > 400 )
$description = mb_substr( $description, 0, 400 ) . '…';
//remove any trailing entities
$description = preg_replace( '/&[^;\s]{0,6}$/', '', $description );
//strip leading/trailing & multiple consecutive lines
$description = trim( $description );
$description = preg_replace( "|(\r?\n)+|", "\n", $description );
//\n => <br>
$description = nl2br( $description );
$version = wp_kses( $plugin['version'], $plugins_allowedtags );
$name = strip_tags( $title . ' ' . $version );
$author = $plugin['author'];
if ( ! empty( $plugin['author'] ) )
$author = ' <cite>' . sprintf( __( 'By %s' ), $author ) . '.</cite>';
$author = wp_kses( $author, $plugins_allowedtags );
$action_links = array();
$action_links[] = '<a href="' . self_admin_url( 'plugin-install.php?tab=plugin-information&plugin=' . $plugin['slug'] .
'&TB_iframe=true&width=600&height=550' ) . '" class="thickbox" title="' .
esc_attr( sprintf( __( 'More information about %s' ), $name ) ) . '">' . __( 'Details' ) . '</a>';
if ( current_user_can( 'install_plugins' ) || current_user_can( 'update_plugins' ) ) {
$status = install_plugin_install_status( $plugin );
switch ( $status['status'] ) {
case 'install':
if ( $status['url'] )
$action_links[] = '<a class="install-now" href="' . $status['url'] . '" title="' . esc_attr( sprintf( __( 'Install %s' ), $name ) ) . '">' . __( 'Install Now' ) . '</a>';
break;
case 'update_available':
if ( $status['url'] )
$action_links[] = '<a href="' . $status['url'] . '" title="' . esc_attr( sprintf( __( 'Update to version %s' ), $status['version'] ) ) . '">' . sprintf( __( 'Update Now' ), $status['version'] ) . '</a>';
break;
case 'latest_installed':
case 'newer_installed':
$action_links[] = '<span title="' . esc_attr__( 'This plugin is already installed and is up to date' ) . ' ">' . _x( 'Installed', 'plugin' ) . '</span>';
break;
}
}
$action_links = apply_filters( 'plugin_install_action_links', $action_links, $plugin );
?>
<tr>
<td class="name column-name"<?php echo $style['name']; ?>><strong><?php echo $title; ?></strong>
<div class="action-links"><?php if ( !empty( $action_links ) ) echo implode( ' | ', $action_links ); ?></div>
</td>
<td class="vers column-version"<?php echo $style['version']; ?>><?php echo $version; ?></td>
<td class="vers column-rating"<?php echo $style['rating']; ?>>
<div class="star-holder" title="<?php printf( _n( '(based on %s rating)', '(based on %s ratings)', $plugin['num_ratings'] ), number_format_i18n( $plugin['num_ratings'] ) ) ?>">
<div class="star star-rating" style="width: <?php echo esc_attr( str_replace( ',', '.', $plugin['rating'] ) ); ?>px"></div>
</div>
</td>
<td class="desc column-description"<?php echo $style['description']; ?>><?php echo $description, $author; ?></td>
</tr>
<?php
}
}
}
| igum/www.gamer31.ru | wp-admin/includes/class-wp-plugin-install-list-table.php | PHP | gpl-2.0 | 7,870 |
package com.ues21.ferreteria.login;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.ues21.ferreteria.productos.Productos;
import com.ues21.ferreteria.productos.ProductosDAO;
import com.ues21.ferreteria.usuarios.Usuarios;
import com.ues21.ferreteria.usuarios.UsuariosDAO;
@Controller
public class LoginController {
@Autowired private LoginDAO loginDAO;
@Autowired private UsuariosDAO usuariosDAO;
/*
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String listaHome(Model model) {
model.addAttribute("login", null);
return "login";
}
*/
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String viewRegistration(Map<String, Object> model) {
Login userForm = new Login();
model.put("userForm", userForm);
return "login";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String processRegistration(@ModelAttribute("userForm") Login user,
Model model, HttpSession session) {
// implement your own registration logic here...
Login login = loginDAO.verificarUsuario(user);
// for testing purpose:
System.out.println("username: " + user.getDni());
System.out.println("password: " + user.getContrasena());
if (login==null){
model.addAttribute("loginError", "Error logging in. Please try again");
return "index";
}
else {
Usuarios usuario = usuariosDAO.getUsuario(user.getDni());
session.setAttribute("loggedInUser", usuario);
return "home";
}
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpSession session){
session.removeAttribute("loggedInUser");
return "index";
}
}
| srubbiolo/SYSO | src/main/java/com/ues21/ferreteria/login/LoginController.java | Java | gpl-2.0 | 2,293 |
<?php
/**
* The Sidebar containing the primary and secondary widget areas.
*
* @package WordPress
* @subpackage Twenty_Ten
* @since Twenty Ten 1.0
*/
?>
<div id="primary" class="widget-area" role="complementary">
<ul class="xoxo">
<?php
/* When we call the dynamic_sidebar() function, it'll spit out
* the widgets for that widget area. If it instead returns false,
* then the sidebar simply doesn't exist, so we'll hard-code in
* some default sidebar stuff just in case.
*/
if ( ! dynamic_sidebar( 'primary-widget-area-en' ) ) : ?>
<?php endif; // end primary widget area ?>
</ul>
</div><!-- #primary .widget-area -->
| ddksaku/twis | wp-content/themes/twis/sidebar-en.php | PHP | gpl-2.0 | 654 |
<?php
load_libraries(array('fields/passwordfield'));
PhangoVar::$model['user_group']=new Webmodel('user_group');
PhangoVar::$model['user_group']->set_component('name', 'CharField', array(255));
PhangoVar::$model['user_group']->set_component('permissions', 'SerializeField', array());
PhangoVar::$model['user']=new Webmodel('user');
PhangoVar::$model['user']->set_component('username', 'CharField', array(25));
PhangoVar::$model['user']->set_component('password', 'PasswordField', array(25));
PhangoVar::$model['user']->set_component('email', 'EmailField', array(255));
PhangoVar::$model['user']->set_component('group', 'ForeignKeyField', array('user_group'));
PhangoVar::$model['user']->set_component('token_client', 'CharField', array(255), 1);
PhangoVar::$model['user']->set_component('token_recovery', 'CharField', array(255), 1);
PhangoVar::$model['login_tried']=new Webmodel('login_tried');
PhangoVar::$model['login_tried']->components['ip']=new CharField(255);
PhangoVar::$model['login_tried']->components['num_tried']=new IntegerField(11);
PhangoVar::$model['login_tried']->components['time']=new IntegerField(11);
?> | webtsys/phango2 | modules/users/models/models_users.php | PHP | gpl-2.0 | 1,137 |
<?php
/**
* @file
* Contains \Drupal\migrate_drupal\Tests\MigrateFullDrupalTestBase.
*/
namespace Drupal\migrate_drupal\Tests;
use Drupal\migrate\MigrateExecutable;
use Drupal\simpletest\TestBase;
/**
* Test helper for running a complete Drupal migration.
*/
abstract class MigrateFullDrupalTestBase extends MigrateDrupalTestBase {
/**
* The test class which discovered migration tests must extend in order to be
* included in this test run.
*/
const BASE_TEST_CLASS = 'Drupal\migrate_drupal\Tests\MigrateDrupalTestBase';
/**
* A list of fully-qualified test classes which should be ignored.
*
* @var string[]
*/
protected static $blacklist = [];
/**
* Get the test classes that needs to be run for this test.
*
* @return array
* The list of fully-classified test class names.
*/
protected function getTestClassesList() {
$classes = [];
$discovery = \Drupal::getContainer()->get('test_discovery');
foreach (static::$modules as $module) {
foreach ($discovery->getTestClasses($module) as $group) {
foreach (array_keys($group) as $class) {
if (is_subclass_of($class, static::BASE_TEST_CLASS)) {
$classes[] = $class;
}
}
}
}
// Exclude blacklisted classes.
return array_diff($classes, static::$blacklist);
}
/**
* {@inheritdoc}
*/
protected function tearDown() {
// Move the results of every class under ours. This is solely for
// reporting, the filename will guide developers.
self::getDatabaseConnection()
->update('simpletest')
->fields(array('test_class' => get_class($this)))
->condition('test_id', $this->testId)
->execute();
parent::tearDown();
}
/**
* Test the complete Drupal migration.
*/
public function testDrupal() {
$classes = $this->getTestClassesList();
foreach ($classes as $class) {
if (is_subclass_of($class, '\Drupal\migrate\Tests\MigrateDumpAlterInterface')) {
$class::migrateDumpAlter($this);
}
}
// Run every migration in the order specified by the storage controller.
foreach (entity_load_multiple('migration', static::$migrations) as $migration) {
(new MigrateExecutable($migration, $this))->import();
}
foreach ($classes as $class) {
$test_object = new $class($this->testId);
$test_object->databasePrefix = $this->databasePrefix;
$test_object->container = $this->container;
// run() does a lot of setup and tear down work which we don't need:
// it would setup a new database connection and wouldn't find the
// Drupal dump. Also by skipping the setUp() methods there are no id
// mappings or entities prepared. The tests run against solely migrated
// data.
foreach (get_class_methods($test_object) as $method) {
if (strtolower(substr($method, 0, 4)) == 'test') {
// Insert a fail record. This will be deleted on completion to ensure
// that testing completed.
$method_info = new \ReflectionMethod($class, $method);
$caller = array(
'file' => $method_info->getFileName(),
'line' => $method_info->getStartLine(),
'function' => $class . '->' . $method . '()',
);
$completion_check_id = TestBase::insertAssert($this->testId, $class, FALSE, 'The test did not complete due to a fatal error.', 'Completion check', $caller);
// Run the test method.
try {
$test_object->$method();
}
catch (\Exception $e) {
$this->exceptionHandler($e);
}
// Remove the completion check record.
TestBase::deleteAssert($completion_check_id);
}
}
// Add the pass/fail/exception/debug results.
foreach ($this->results as $key => &$value) {
$value += $test_object->results[$key];
}
}
}
}
| havran/Drupal.sk | docroot/drupal/core/modules/migrate_drupal/src/Tests/MigrateFullDrupalTestBase.php | PHP | gpl-2.0 | 3,949 |
<?php
/**
* @package Joomla.UnitTest
* @subpackage Filesystem
*
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
JLoader::register('JPath', JPATH_PLATFORM . '/joomla/filesystem/path.php');
/**
* Tests for the JPath class.
*
* @package Joomla.UnitTest
* @subpackage Filesystem
* @since 12.2
*/
class JPathTest extends TestCase
{
/**
* Data provider for testClean() method.
*
* @return array
*
* @since 12.2
*/
public function getCleanData()
{
return array(
// Input Path, Directory Separator, Expected Output
'Nothing to do.' => array('/var/www/foo/bar/baz', '/', '/var/www/foo/bar/baz'),
'One backslash.' => array('/var/www/foo\\bar/baz', '/', '/var/www/foo/bar/baz'),
'Two and one backslashes.' => array('/var/www\\\\foo\\bar/baz', '/', '/var/www/foo/bar/baz'),
'Mixed backslashes and double forward slashes.' => array('/var\\/www//foo\\bar/baz', '/', '/var/www/foo/bar/baz'),
'UNC path.' => array('\\\\www\\docroot', '\\', '\\\\www\\docroot'),
'UNC path with forward slash.' => array('\\\\www/docroot', '\\', '\\\\www\\docroot'),
'UNC path with UNIX directory separator.' => array('\\\\www/docroot', '/', '/www/docroot'),
);
}
/**
* Test...
*
* @todo Implement testCanChmod().
*
* @return void
*/
public function testCanChmod()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete('This test has not been implemented yet.');
}
/**
* Test...
*
* @todo Implement testSetPermissions().
*
* @return void
*/
public function testSetPermissions()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete('This test has not been implemented yet.');
}
/**
* Test...
*
* @todo Implement testGetPermissions().
*
* @return void
*/
public function testGetPermissions()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete('This test has not been implemented yet.');
}
/**
* Test...
*
* @todo Implement testCheck().
*
* @return void
*/
public function testCheck()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete('This test has not been implemented yet.');
}
/**
* Tests the clean method.
*
* @param string $input @todo
* @param string $ds @todo
* @param string $expected @todo
*
* @return void
*
* @covers JPath::clean
* @dataProvider getCleanData
* @since 12.2
*/
public function testClean($input, $ds, $expected)
{
$this->assertEquals(
$expected,
JPath::clean($input, $ds)
);
}
/**
* Test...
*
* @todo Implement testIsOwner().
*
* @return void
*/
public function testIsOwner()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete('This test has not been implemented yet.');
}
/**
* Test...
*
* @todo Implement testFind().
*
* @return void
*/
public function testFind()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete('This test has not been implemented yet.');
}
}
| vothequang113/Joomla | tests/suites/unit/joomla/filesystem/JPathTest.php | PHP | gpl-2.0 | 3,267 |
/* This code is part of Freenet. It is distributed under the GNU General
* Public License, version 2 (or at your option any later version). See
* http://www.gnu.org/ for further details of the GPL. */
/* Freenet 0.7 node. */
package freenet.node;
import static freenet.node.stats.DataStoreKeyType.CHK;
import static freenet.node.stats.DataStoreKeyType.PUB_KEY;
import static freenet.node.stats.DataStoreKeyType.SSK;
import static freenet.node.stats.DataStoreType.CACHE;
import static freenet.node.stats.DataStoreType.CLIENT;
import static freenet.node.stats.DataStoreType.SLASHDOT;
import static freenet.node.stats.DataStoreType.STORE;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.MINUTES;
import static java.util.concurrent.TimeUnit.SECONDS;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.Random;
import java.util.Set;
import freenet.config.*;
import freenet.node.useralerts.*;
import org.tanukisoftware.wrapper.WrapperManager;
import freenet.client.FetchContext;
import freenet.clients.fcp.FCPMessage;
import freenet.clients.fcp.FeedMessage;
import freenet.clients.http.SecurityLevelsToadlet;
import freenet.clients.http.SimpleToadletServer;
import freenet.crypt.DSAPublicKey;
import freenet.crypt.ECDH;
import freenet.crypt.MasterSecret;
import freenet.crypt.PersistentRandomSource;
import freenet.crypt.RandomSource;
import freenet.crypt.Yarrow;
import freenet.io.comm.DMT;
import freenet.io.comm.DisconnectedException;
import freenet.io.comm.FreenetInetAddress;
import freenet.io.comm.IOStatisticCollector;
import freenet.io.comm.Message;
import freenet.io.comm.MessageCore;
import freenet.io.comm.MessageFilter;
import freenet.io.comm.Peer;
import freenet.io.comm.PeerParseException;
import freenet.io.comm.ReferenceSignatureVerificationException;
import freenet.io.comm.TrafficClass;
import freenet.io.comm.UdpSocketHandler;
import freenet.io.xfer.PartiallyReceivedBlock;
import freenet.keys.CHKBlock;
import freenet.keys.CHKVerifyException;
import freenet.keys.ClientCHK;
import freenet.keys.ClientCHKBlock;
import freenet.keys.ClientKey;
import freenet.keys.ClientKeyBlock;
import freenet.keys.ClientSSK;
import freenet.keys.ClientSSKBlock;
import freenet.keys.Key;
import freenet.keys.KeyBlock;
import freenet.keys.KeyVerifyException;
import freenet.keys.NodeCHK;
import freenet.keys.NodeSSK;
import freenet.keys.SSKBlock;
import freenet.keys.SSKVerifyException;
import freenet.l10n.BaseL10n;
import freenet.l10n.NodeL10n;
import freenet.node.DarknetPeerNode.FRIEND_TRUST;
import freenet.node.DarknetPeerNode.FRIEND_VISIBILITY;
import freenet.node.NodeDispatcher.NodeDispatcherCallback;
import freenet.node.OpennetManager.ConnectionType;
import freenet.node.SecurityLevels.NETWORK_THREAT_LEVEL;
import freenet.node.SecurityLevels.PHYSICAL_THREAT_LEVEL;
import freenet.node.probe.Listener;
import freenet.node.probe.Type;
import freenet.node.stats.DataStoreInstanceType;
import freenet.node.stats.DataStoreStats;
import freenet.node.stats.NotAvailNodeStoreStats;
import freenet.node.stats.StoreCallbackStats;
import freenet.node.updater.NodeUpdateManager;
import freenet.pluginmanager.ForwardPort;
import freenet.pluginmanager.PluginDownLoaderOfficialHTTPS;
import freenet.pluginmanager.PluginManager;
import freenet.store.BlockMetadata;
import freenet.store.CHKStore;
import freenet.store.FreenetStore;
import freenet.store.KeyCollisionException;
import freenet.store.NullFreenetStore;
import freenet.store.PubkeyStore;
import freenet.store.RAMFreenetStore;
import freenet.store.SSKStore;
import freenet.store.SlashdotStore;
import freenet.store.StorableBlock;
import freenet.store.StoreCallback;
import freenet.store.caching.CachingFreenetStore;
import freenet.store.caching.CachingFreenetStoreTracker;
import freenet.store.saltedhash.ResizablePersistentIntBuffer;
import freenet.store.saltedhash.SaltedHashFreenetStore;
import freenet.support.Executor;
import freenet.support.Fields;
import freenet.support.HTMLNode;
import freenet.support.HexUtil;
import freenet.support.JVMVersion;
import freenet.support.LogThresholdCallback;
import freenet.support.Logger;
import freenet.support.Logger.LogLevel;
import freenet.support.PooledExecutor;
import freenet.support.PrioritizedTicker;
import freenet.support.ShortBuffer;
import freenet.support.SimpleFieldSet;
import freenet.support.Ticker;
import freenet.support.TokenBucket;
import freenet.support.api.BooleanCallback;
import freenet.support.api.IntCallback;
import freenet.support.api.LongCallback;
import freenet.support.api.ShortCallback;
import freenet.support.api.StringCallback;
import freenet.support.io.ArrayBucketFactory;
import freenet.support.io.Closer;
import freenet.support.io.FileUtil;
import freenet.support.io.NativeThread;
import freenet.support.math.MersenneTwister;
import freenet.support.transport.ip.HostnameSyntaxException;
/**
* @author amphibian
*/
public class Node implements TimeSkewDetectorCallback {
public class MigrateOldStoreData implements Runnable {
private final boolean clientCache;
public MigrateOldStoreData(boolean clientCache) {
this.clientCache = clientCache;
if(clientCache) {
oldCHKClientCache = chkClientcache;
oldPKClientCache = pubKeyClientcache;
oldSSKClientCache = sskClientcache;
} else {
oldCHK = chkDatastore;
oldPK = pubKeyDatastore;
oldSSK = sskDatastore;
oldCHKCache = chkDatastore;
oldPKCache = pubKeyDatastore;
oldSSKCache = sskDatastore;
}
}
@Override
public void run() {
System.err.println("Migrating old "+(clientCache ? "client cache" : "datastore"));
if(clientCache) {
migrateOldStore(oldCHKClientCache, chkClientcache, true);
StoreCallback<? extends StorableBlock> old;
synchronized(Node.this) {
old = oldCHKClientCache;
oldCHKClientCache = null;
}
closeOldStore(old);
migrateOldStore(oldPKClientCache, pubKeyClientcache, true);
synchronized(Node.this) {
old = oldPKClientCache;
oldPKClientCache = null;
}
closeOldStore(old);
migrateOldStore(oldSSKClientCache, sskClientcache, true);
synchronized(Node.this) {
old = oldSSKClientCache;
oldSSKClientCache = null;
}
closeOldStore(old);
} else {
migrateOldStore(oldCHK, chkDatastore, false);
oldCHK = null;
migrateOldStore(oldPK, pubKeyDatastore, false);
oldPK = null;
migrateOldStore(oldSSK, sskDatastore, false);
oldSSK = null;
migrateOldStore(oldCHKCache, chkDatacache, false);
oldCHKCache = null;
migrateOldStore(oldPKCache, pubKeyDatacache, false);
oldPKCache = null;
migrateOldStore(oldSSKCache, sskDatacache, false);
oldSSKCache = null;
}
System.err.println("Finished migrating old "+(clientCache ? "client cache" : "datastore"));
}
}
volatile CHKStore oldCHK;
volatile PubkeyStore oldPK;
volatile SSKStore oldSSK;
volatile CHKStore oldCHKCache;
volatile PubkeyStore oldPKCache;
volatile SSKStore oldSSKCache;
volatile CHKStore oldCHKClientCache;
volatile PubkeyStore oldPKClientCache;
volatile SSKStore oldSSKClientCache;
private <T extends StorableBlock> void migrateOldStore(StoreCallback<T> old, StoreCallback<T> newStore, boolean canReadClientCache) {
FreenetStore<T> store = old.getStore();
if(store instanceof RAMFreenetStore) {
RAMFreenetStore<T> ramstore = (RAMFreenetStore<T>)store;
try {
ramstore.migrateTo(newStore, canReadClientCache);
} catch (IOException e) {
Logger.error(this, "Caught migrating old store: "+e, e);
}
ramstore.clear();
} else if(store instanceof SaltedHashFreenetStore) {
Logger.error(this, "Migrating from from a saltedhashstore not fully supported yet: will not keep old keys");
}
}
public <T extends StorableBlock> void closeOldStore(StoreCallback<T> old) {
FreenetStore<T> store = old.getStore();
if(store instanceof SaltedHashFreenetStore) {
SaltedHashFreenetStore<T> saltstore = (SaltedHashFreenetStore<T>) store;
saltstore.close();
saltstore.destruct();
}
}
private static volatile boolean logMINOR;
private static volatile boolean logDEBUG;
static {
Logger.registerLogThresholdCallback(new LogThresholdCallback(){
@Override
public void shouldUpdate(){
logMINOR = Logger.shouldLog(LogLevel.MINOR, this);
logDEBUG = Logger.shouldLog(LogLevel.DEBUG, this);
}
});
}
private static MeaningfulNodeNameUserAlert nodeNameUserAlert;
private static TimeSkewDetectedUserAlert timeSkewDetectedUserAlert;
public class NodeNameCallback extends StringCallback {
NodeNameCallback() {
}
@Override
public String get() {
String name;
synchronized(this) {
name = myName;
}
if(name.startsWith("Node id|")|| name.equals("MyFirstFreenetNode") || name.startsWith("Freenet node with no name #")){
clientCore.alerts.register(nodeNameUserAlert);
}else{
clientCore.alerts.unregister(nodeNameUserAlert);
}
return name;
}
@Override
public void set(String val) throws InvalidConfigValueException {
if(get().equals(val)) return;
else if(val.length() > 128)
throw new InvalidConfigValueException("The given node name is too long ("+val+')');
else if("".equals(val))
val = "~none~";
synchronized(this) {
myName = val;
}
// We'll broadcast the new name to our connected darknet peers via a differential node reference
SimpleFieldSet fs = new SimpleFieldSet(true);
fs.putSingle("myName", myName);
peers.locallyBroadcastDiffNodeRef(fs, true, false);
// We call the callback once again to ensure MeaningfulNodeNameUserAlert
// has been unregistered ... see #1595
get();
}
}
private class StoreTypeCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
synchronized(Node.this) {
return storeType;
}
}
@Override
public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException {
boolean found = false;
for (String p : getPossibleValues()) {
if (p.equals(val)) {
found = true;
break;
}
}
if (!found)
throw new InvalidConfigValueException("Invalid store type");
String type;
synchronized(Node.this) {
type = storeType;
}
if(type.equals("ram")) {
synchronized(this) { // Serialise this part.
makeStore(val);
}
} else {
synchronized(Node.this) {
storeType = val;
}
throw new NodeNeedRestartException("Store type cannot be changed on the fly");
}
}
@Override
public String[] getPossibleValues() {
return new String[] { "salt-hash", "ram" };
}
}
private class ClientCacheTypeCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
synchronized(Node.this) {
return clientCacheType;
}
}
@Override
public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException {
boolean found = false;
for (String p : getPossibleValues()) {
if (p.equals(val)) {
found = true;
break;
}
}
if (!found)
throw new InvalidConfigValueException("Invalid store type");
synchronized(this) { // Serialise this part.
String suffix = getStoreSuffix();
if (val.equals("salt-hash")) {
byte[] key;
try {
synchronized(Node.this) {
if(keys == null) throw new MasterKeysWrongPasswordException();
key = keys.clientCacheMasterKey;
clientCacheType = val;
}
} catch (MasterKeysWrongPasswordException e1) {
setClientCacheAwaitingPassword();
throw new InvalidConfigValueException("You must enter the password");
}
try {
initSaltHashClientCacheFS(suffix, true, key);
} catch (NodeInitException e) {
Logger.error(this, "Unable to create new store", e);
System.err.println("Unable to create new store: "+e);
e.printStackTrace();
// FIXME l10n both on the NodeInitException and the wrapper message
throw new InvalidConfigValueException("Unable to create new store: "+e);
}
} else if(val.equals("ram")) {
initRAMClientCacheFS();
} else /*if(val.equals("none")) */{
initNoClientCacheFS();
}
synchronized(Node.this) {
clientCacheType = val;
}
}
}
@Override
public String[] getPossibleValues() {
return new String[] { "salt-hash", "ram", "none" };
}
}
private static class L10nCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
return NodeL10n.getBase().getSelectedLanguage().fullName;
}
@Override
public void set(String val) throws InvalidConfigValueException {
if(val == null || get().equalsIgnoreCase(val)) return;
try {
NodeL10n.getBase().setLanguage(BaseL10n.LANGUAGE.mapToLanguage(val));
} catch (MissingResourceException e) {
throw new InvalidConfigValueException(e.getLocalizedMessage());
}
PluginManager.setLanguage(NodeL10n.getBase().getSelectedLanguage());
}
@Override
public String[] getPossibleValues() {
return BaseL10n.LANGUAGE.valuesWithFullNames();
}
}
/** Encryption key for client.dat.crypt or client.dat.bak.crypt */
private DatabaseKey databaseKey;
/** Encryption keys, if loaded, null if waiting for a password. We must be able to write them,
* and they're all used elsewhere anyway, so there's no point trying not to keep them in memory. */
private MasterKeys keys;
/** Stats */
public final NodeStats nodeStats;
/** Config object for the whole node. */
public final PersistentConfig config;
// Static stuff related to logger
/** Directory to log to */
static File logDir;
/** Maximum size of gzipped logfiles */
static long maxLogSize;
/** Log config handler */
public static LoggingConfigHandler logConfigHandler;
public static final int PACKETS_IN_BLOCK = 32;
public static final int PACKET_SIZE = 1024;
public static final double DECREMENT_AT_MIN_PROB = 0.25;
public static final double DECREMENT_AT_MAX_PROB = 0.5;
// Send keepalives every 7-14 seconds. Will be acked and if necessary resent.
// Old behaviour was keepalives every 14-28. Even that was adequate for a 30 second
// timeout. Most nodes don't need to send keepalives because they are constantly busy,
// this is only an issue for disabled darknet connections, very quiet private networks
// etc.
public static final long KEEPALIVE_INTERVAL = SECONDS.toMillis(7);
// If no activity for 30 seconds, node is dead
// 35 seconds allows plenty of time for resends etc even if above is 14 sec as it is on older nodes.
public static final long MAX_PEER_INACTIVITY = SECONDS.toMillis(35);
/** Time after which a handshake is assumed to have failed. */
public static final int HANDSHAKE_TIMEOUT = (int) MILLISECONDS.toMillis(4800); // Keep the below within the 30 second assumed timeout.
// Inter-handshake time must be at least 2x handshake timeout
public static final int MIN_TIME_BETWEEN_HANDSHAKE_SENDS = HANDSHAKE_TIMEOUT*2; // 10-20 secs
public static final int RANDOMIZED_TIME_BETWEEN_HANDSHAKE_SENDS = HANDSHAKE_TIMEOUT*2; // avoid overlap when the two handshakes are at the same time
public static final int MIN_TIME_BETWEEN_VERSION_PROBES = HANDSHAKE_TIMEOUT*4;
public static final int RANDOMIZED_TIME_BETWEEN_VERSION_PROBES = HANDSHAKE_TIMEOUT*2; // 20-30 secs
public static final int MIN_TIME_BETWEEN_VERSION_SENDS = HANDSHAKE_TIMEOUT*4;
public static final int RANDOMIZED_TIME_BETWEEN_VERSION_SENDS = HANDSHAKE_TIMEOUT*2; // 20-30 secs
public static final int MIN_TIME_BETWEEN_BURSTING_HANDSHAKE_BURSTS = HANDSHAKE_TIMEOUT*24; // 2-5 minutes
public static final int RANDOMIZED_TIME_BETWEEN_BURSTING_HANDSHAKE_BURSTS = HANDSHAKE_TIMEOUT*36;
public static final int MIN_BURSTING_HANDSHAKE_BURST_SIZE = 1; // 1-4 handshake sends per burst
public static final int RANDOMIZED_BURSTING_HANDSHAKE_BURST_SIZE = 3;
// If we don't receive any packets at all in this period, from any node, tell the user
public static final long ALARM_TIME = MINUTES.toMillis(1);
static final long MIN_INTERVAL_BETWEEN_INCOMING_SWAP_REQUESTS = MILLISECONDS.toMillis(900);
static final long MIN_INTERVAL_BETWEEN_INCOMING_PROBE_REQUESTS = MILLISECONDS.toMillis(1000);
public static final int SYMMETRIC_KEY_LENGTH = 32; // 256 bits - note that this isn't used everywhere to determine it
/** Datastore directory */
private final ProgramDirectory storeDir;
/** Datastore properties */
private String storeType;
private boolean storeUseSlotFilters;
private boolean storeSaltHashResizeOnStart;
/** Minimum total datastore size */
static final long MIN_STORE_SIZE = 32 * 1024 * 1024;
/** Default datastore size (must be at least MIN_STORE_SIZE) */
static final long DEFAULT_STORE_SIZE = 32 * 1024 * 1024;
/** Minimum client cache size */
static final long MIN_CLIENT_CACHE_SIZE = 0;
/** Default client cache size (must be at least MIN_CLIENT_CACHE_SIZE) */
static final long DEFAULT_CLIENT_CACHE_SIZE = 10 * 1024 * 1024;
/** Minimum slashdot cache size */
static final long MIN_SLASHDOT_CACHE_SIZE = 0;
/** Default slashdot cache size (must be at least MIN_SLASHDOT_CACHE_SIZE) */
static final long DEFAULT_SLASHDOT_CACHE_SIZE = 10 * 1024 * 1024;
/** The number of bytes per key total in all the different datastores. All the datastores
* are always the same size in number of keys. */
public static final int sizePerKey = CHKBlock.DATA_LENGTH + CHKBlock.TOTAL_HEADERS_LENGTH +
DSAPublicKey.PADDED_SIZE + SSKBlock.DATA_LENGTH + SSKBlock.TOTAL_HEADERS_LENGTH;
/** The maximum number of keys stored in each of the datastores, cache and store combined. */
private long maxTotalKeys;
long maxCacheKeys;
long maxStoreKeys;
/** The maximum size of the datastore. Kept to avoid rounding turning 5G into 5368698672 */
private long maxTotalDatastoreSize;
/** If true, store shrinks occur immediately even if they are over 10% of the store size. If false,
* we just set the storeSize and do an offline shrink on the next startup. Online shrinks do not
* preserve the most recently used data so are not recommended. */
private boolean storeForceBigShrinks;
private final SemiOrderedShutdownHook shutdownHook;
/** The CHK datastore. Long term storage; data should only be inserted here if
* this node is the closest location on the chain so far, and it is on an
* insert (because inserts will always reach the most specialized node; if we
* allow requests to store here, then we get pollution by inserts for keys not
* close to our specialization). These conclusions derived from Oskar's simulations. */
private CHKStore chkDatastore;
/** The SSK datastore. See description for chkDatastore. */
private SSKStore sskDatastore;
/** The store of DSAPublicKeys (by hash). See description for chkDatastore. */
private PubkeyStore pubKeyDatastore;
/** Client cache store type */
private String clientCacheType;
/** Client cache could not be opened so is a RAMFS until the correct password is entered */
private boolean clientCacheAwaitingPassword;
private boolean databaseAwaitingPassword;
/** Client cache maximum cached keys for each type */
long maxClientCacheKeys;
/** Maximum size of the client cache. Kept to avoid rounding problems. */
private long maxTotalClientCacheSize;
/** The CHK datacache. Short term cache which stores everything that passes
* through this node. */
private CHKStore chkDatacache;
/** The SSK datacache. Short term cache which stores everything that passes
* through this node. */
private SSKStore sskDatacache;
/** The public key datacache (by hash). Short term cache which stores
* everything that passes through this node. */
private PubkeyStore pubKeyDatacache;
/** The CHK client cache. Caches local requests only. */
private CHKStore chkClientcache;
/** The SSK client cache. Caches local requests only. */
private SSKStore sskClientcache;
/** The pubkey client cache. Caches local requests only. */
private PubkeyStore pubKeyClientcache;
// These only cache keys for 30 minutes.
// FIXME make the first two configurable
private long maxSlashdotCacheSize;
private int maxSlashdotCacheKeys;
static final long PURGE_INTERVAL = SECONDS.toMillis(60);
private CHKStore chkSlashdotcache;
private SlashdotStore<CHKBlock> chkSlashdotcacheStore;
private SSKStore sskSlashdotcache;
private SlashdotStore<SSKBlock> sskSlashdotcacheStore;
private PubkeyStore pubKeySlashdotcache;
private SlashdotStore<DSAPublicKey> pubKeySlashdotcacheStore;
/** If false, only ULPRs will use the slashdot cache. If true, everything does. */
private boolean useSlashdotCache;
/** If true, we write stuff to the datastore even though we shouldn't because the HTL is
* too high. However it is flagged as old so it won't be included in the Bloom filter for
* sharing purposes. */
private boolean writeLocalToDatastore;
final NodeGetPubkey getPubKey;
/** FetchContext for ARKs */
public final FetchContext arkFetcherContext;
/** IP detector */
public final NodeIPDetector ipDetector;
/** For debugging/testing, set this to true to stop the
* probabilistic decrement at the edges of the HTLs. */
boolean disableProbabilisticHTLs;
public final RequestTracker tracker;
/** Semi-unique ID for swap requests. Used to identify us so that the
* topology can be reconstructed. */
public long swapIdentifier;
private String myName;
public final LocationManager lm;
/** My peers */
public final PeerManager peers;
/** Node-reference directory (node identity, peers, etc) */
final ProgramDirectory nodeDir;
/** Config directory (l10n overrides, etc) */
final ProgramDirectory cfgDir;
/** User data directory (bookmarks, download lists, etc) */
final ProgramDirectory userDir;
/** Run-time state directory (bootID, PRNG seed, etc) */
final ProgramDirectory runDir;
/** Plugin directory */
final ProgramDirectory pluginDir;
/** File to write crypto master keys into, possibly passworded */
final File masterKeysFile;
/** Directory to put extra peer data into */
final File extraPeerDataDir;
private volatile boolean hasPanicked;
/** Strong RNG */
public final RandomSource random;
/** JCA-compliant strong RNG. WARNING: DO NOT CALL THIS ON THE MAIN NETWORK
* HANDLING THREADS! In some configurations it can block, potentially
* forever, on nextBytes()! */
public final SecureRandom secureRandom;
/** Weak but fast RNG */
public final Random fastWeakRandom;
/** The object which handles incoming messages and allows us to wait for them */
final MessageCore usm;
// Darknet stuff
NodeCrypto darknetCrypto;
// Back compat
private boolean showFriendsVisibilityAlert;
// Opennet stuff
private final NodeCryptoConfig opennetCryptoConfig;
OpennetManager opennet;
private volatile boolean isAllowedToConnectToSeednodes;
private int maxOpennetPeers;
private boolean acceptSeedConnections;
private boolean passOpennetRefsThroughDarknet;
// General stuff
public final Executor executor;
public final PacketSender ps;
public final PrioritizedTicker ticker;
final DNSRequester dnsr;
final NodeDispatcher dispatcher;
public final UptimeEstimator uptime;
public final TokenBucket outputThrottle;
public boolean throttleLocalData;
private int outputBandwidthLimit;
private int inputBandwidthLimit;
private long amountOfDataToCheckCompressionRatio;
private int minimumCompressionPercentage;
private int maxTimeForSingleCompressor;
private boolean connectionSpeedDetection;
boolean inputLimitDefault;
final boolean enableARKs;
final boolean enablePerNodeFailureTables;
final boolean enableULPRDataPropagation;
final boolean enableSwapping;
private volatile boolean publishOurPeersLocation;
private volatile boolean routeAccordingToOurPeersLocation;
boolean enableSwapQueueing;
boolean enablePacketCoalescing;
public static final short DEFAULT_MAX_HTL = (short)18;
private short maxHTL;
private boolean skipWrapperWarning;
private int maxPacketSize;
/** Should inserts ignore low backoff times by default? */
public static final boolean IGNORE_LOW_BACKOFF_DEFAULT = false;
/** Definition of "low backoff times" for above. */
public static final long LOW_BACKOFF = SECONDS.toMillis(30);
/** Should inserts be fairly blatently prioritised on accept by default? */
public static final boolean PREFER_INSERT_DEFAULT = false;
/** Should inserts fork when the HTL reaches cacheability? */
public static final boolean FORK_ON_CACHEABLE_DEFAULT = true;
public final IOStatisticCollector collector;
/** Type identifier for fproxy node to node messages, as sent on DMT.nodeToNodeMessage's */
public static final int N2N_MESSAGE_TYPE_FPROXY = 1;
/** Type identifier for differential node reference messages, as sent on DMT.nodeToNodeMessage's */
public static final int N2N_MESSAGE_TYPE_DIFFNODEREF = 2;
/** Identifier within fproxy messages for simple, short text messages to be displayed on the homepage as useralerts */
public static final int N2N_TEXT_MESSAGE_TYPE_USERALERT = 1;
/** Identifier within fproxy messages for an offer to transfer a file */
public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER = 2;
/** Identifier within fproxy messages for accepting an offer to transfer a file */
public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED = 3;
/** Identifier within fproxy messages for rejecting an offer to transfer a file */
public static final int N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED = 4;
/** Identified within friend feed for the recommendation of a bookmark */
public static final int N2N_TEXT_MESSAGE_TYPE_BOOKMARK = 5;
/** Identified within friend feed for the recommendation of a file */
public static final int N2N_TEXT_MESSAGE_TYPE_DOWNLOAD = 6;
public static final int EXTRA_PEER_DATA_TYPE_N2NTM = 1;
public static final int EXTRA_PEER_DATA_TYPE_PEER_NOTE = 2;
public static final int EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM = 3;
public static final int EXTRA_PEER_DATA_TYPE_BOOKMARK = 4;
public static final int EXTRA_PEER_DATA_TYPE_DOWNLOAD = 5;
public static final int PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT = 1;
/** The bootID of the last time the node booted up. Or -1 if we don't know due to
* permissions problems, or we suspect that the node has been booted and not
* written the file e.g. if we can't write it. So if we want to compare data
* gathered in the last session and only recorded to disk on a clean shutdown
* to data we have now, we just include the lastBootID. */
public final long lastBootID;
public final long bootID;
public final long startupTime;
private SimpleToadletServer toadlets;
public final NodeClientCore clientCore;
// ULPRs, RecentlyFailed, per node failure tables, are all managed by FailureTable.
final FailureTable failureTable;
// The version we were before we restarted.
public int lastVersion;
/** NodeUpdater **/
public final NodeUpdateManager nodeUpdater;
public final SecurityLevels securityLevels;
// Things that's needed to keep track of
public final PluginManager pluginManager;
// Helpers
public final InetAddress localhostAddress;
public final FreenetInetAddress fLocalhostAddress;
// The node starter
private static NodeStarter nodeStarter;
// The watchdog will be silenced until it's true
private boolean hasStarted;
private boolean isStopping = false;
/**
* Minimum uptime for us to consider a node an acceptable place to store a key. We store a key
* to the datastore only if it's from an insert, and we are a sink, but when calculating whether
* we are a sink we ignore nodes which have less uptime (percentage) than this parameter.
*/
static final int MIN_UPTIME_STORE_KEY = 40;
private volatile boolean isPRNGReady = false;
private boolean storePreallocate;
private boolean enableRoutedPing;
private boolean peersOffersDismissed;
/**
* Minimum bandwidth limit in bytes considered usable: 10 KiB. If there is an attempt to set a limit below this -
* excluding the reserved -1 for input bandwidth - the callback will throw. See the callbacks for
* outputBandwidthLimit and inputBandwidthLimit. 10 KiB are equivalent to 50 GiB traffic per month.
*/
private static final int minimumBandwidth = 10 * 1024;
/** Quality of Service mark we will use for all outgoing packets (opennet/darknet) */
private TrafficClass trafficClass;
public TrafficClass getTrafficClass() {
return trafficClass;
}
/*
* Gets minimum bandwidth in bytes considered usable.
*
* @see #minimumBandwidth
*/
public static int getMinimumBandwidth() {
return minimumBandwidth;
}
/**
* Dispatches a probe request with the specified settings
* @see freenet.node.probe.Probe#start(byte, long, Type, Listener)
*/
public void startProbe(final byte htl, final long uid, final Type type, final Listener listener) {
dispatcher.probe.start(htl, uid, type, listener);
}
/**
* Read all storable settings (identity etc) from the node file.
* @param filename The name of the file to read from.
* @throws IOException throw when I/O error occur
*/
private void readNodeFile(String filename) throws IOException {
// REDFLAG: Any way to share this code with NodePeer?
FileInputStream fis = new FileInputStream(filename);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
SimpleFieldSet fs = new SimpleFieldSet(br, false, true);
br.close();
// Read contents
String[] udp = fs.getAll("physical.udp");
if((udp != null) && (udp.length > 0)) {
for(String udpAddr : udp) {
// Just keep the first one with the correct port number.
Peer p;
try {
p = new Peer(udpAddr, false, true);
} catch (HostnameSyntaxException e) {
Logger.error(this, "Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr);
System.err.println("Invalid hostname or IP Address syntax error while parsing our darknet node reference: "+udpAddr);
continue;
} catch (PeerParseException e) {
throw (IOException)new IOException().initCause(e);
}
if(p.getPort() == getDarknetPortNumber()) {
// DNSRequester doesn't deal with our own node
ipDetector.setOldIPAddress(p.getFreenetAddress());
break;
}
}
}
darknetCrypto.readCrypto(fs);
swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash);
String loc = fs.get("location");
double locD = Location.getLocation(loc);
if (locD == -1.0)
throw new IOException("Invalid location: " + loc);
lm.setLocation(locD);
myName = fs.get("myName");
if(myName == null) {
myName = newName();
}
String verString = fs.get("version");
if(verString == null) {
Logger.error(this, "No version!");
System.err.println("No version!");
} else {
lastVersion = Version.getArbitraryBuildNumber(verString, -1);
}
}
public void makeStore(String val) throws InvalidConfigValueException {
String suffix = getStoreSuffix();
if (val.equals("salt-hash")) {
try {
initSaltHashFS(suffix, true, null);
} catch (NodeInitException e) {
Logger.error(this, "Unable to create new store", e);
System.err.println("Unable to create new store: "+e);
e.printStackTrace();
// FIXME l10n both on the NodeInitException and the wrapper message
throw new InvalidConfigValueException("Unable to create new store: "+e);
}
} else {
initRAMFS();
}
synchronized(Node.this) {
storeType = val;
}
}
private String newName() {
return "Freenet node with no name #"+random.nextLong();
}
private final Object writeNodeFileSync = new Object();
public void writeNodeFile() {
synchronized(writeNodeFileSync) {
writeNodeFile(nodeDir.file("node-"+getDarknetPortNumber()), nodeDir.file("node-"+getDarknetPortNumber()+".bak"));
}
}
public void writeOpennetFile() {
OpennetManager om = opennet;
if(om != null) om.writeFile();
}
private void writeNodeFile(File orig, File backup) {
SimpleFieldSet fs = darknetCrypto.exportPrivateFieldSet();
if(orig.exists()) backup.delete();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(backup);
fs.writeTo(fos);
fos.close();
fos = null;
FileUtil.renameTo(backup, orig);
} catch (IOException ioe) {
Logger.error(this, "IOE :"+ioe.getMessage(), ioe);
return;
} finally {
Closer.close(fos);
}
}
private void initNodeFileSettings() {
Logger.normal(this, "Creating new node file from scratch");
// Don't need to set getDarknetPortNumber()
// FIXME use a real IP!
darknetCrypto.initCrypto();
swapIdentifier = Fields.bytesToLong(darknetCrypto.identityHashHash);
myName = newName();
}
/**
* Read the config file from the arguments.
* Then create a node.
* Anything that needs static init should ideally be in here.
* @param args
*/
public static void main(String[] args) throws IOException {
NodeStarter.main(args);
}
public boolean isUsingWrapper(){
if(nodeStarter!=null && WrapperManager.isControlledByNativeWrapper())
return true;
else
return false;
}
public NodeStarter getNodeStarter(){
return nodeStarter;
}
/**
* Create a Node from a Config object.
* @param config The Config object for this node.
* @param r The random number generator for this node. Passed in because we may want
* to use a non-secure RNG for e.g. one-JVM live-code simulations. Should be a Yarrow in
* a production node. Yarrow will be used if that parameter is null
* @param weakRandom The fast random number generator the node will use. If null a MT
* instance will be used, seeded from the secure PRNG.
* @param lc logging config Handler
* @param ns NodeStarter
* @param executor Executor
* @throws NodeInitException If the node initialization fails.
*/
Node(PersistentConfig config, RandomSource r, RandomSource weakRandom, LoggingConfigHandler lc, NodeStarter ns, Executor executor) throws NodeInitException {
this.shutdownHook = SemiOrderedShutdownHook.get();
// Easy stuff
String tmp = "Initializing Node using Freenet Build #"+Version.buildNumber()+" r"+Version.cvsRevision()+" and freenet-ext Build #"+NodeStarter.extBuildNumber+" r"+NodeStarter.extRevisionNumber+" with "+System.getProperty("java.vendor")+" JVM version "+System.getProperty("java.version")+" running on "+System.getProperty("os.arch")+' '+System.getProperty("os.name")+' '+System.getProperty("os.version");
fixCertsFiles();
Logger.normal(this, tmp);
System.out.println(tmp);
collector = new IOStatisticCollector();
this.executor = executor;
nodeStarter=ns;
if(logConfigHandler != lc)
logConfigHandler=lc;
getPubKey = new NodeGetPubkey(this);
startupTime = System.currentTimeMillis();
SimpleFieldSet oldConfig = config.getSimpleFieldSet();
// Setup node-specific configuration
final SubConfig nodeConfig = config.createSubConfig("node");
final SubConfig installConfig = config.createSubConfig("node.install");
int sortOrder = 0;
// Directory for node-related files other than store
this.userDir = setupProgramDir(installConfig, "userDir", ".",
"Node.userDir", "Node.userDirLong", nodeConfig);
this.cfgDir = setupProgramDir(installConfig, "cfgDir", getUserDir().toString(),
"Node.cfgDir", "Node.cfgDirLong", nodeConfig);
this.nodeDir = setupProgramDir(installConfig, "nodeDir", getUserDir().toString(),
"Node.nodeDir", "Node.nodeDirLong", nodeConfig);
this.runDir = setupProgramDir(installConfig, "runDir", getUserDir().toString(),
"Node.runDir", "Node.runDirLong", nodeConfig);
this.pluginDir = setupProgramDir(installConfig, "pluginDir", userDir().file("plugins").toString(),
"Node.pluginDir", "Node.pluginDirLong", nodeConfig);
// l10n stuffs
nodeConfig.register("l10n", Locale.getDefault().getLanguage().toLowerCase(), sortOrder++, false, true,
"Node.l10nLanguage",
"Node.l10nLanguageLong",
new L10nCallback());
try {
new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getString("l10n")), getCfgDir());
} catch (MissingResourceException e) {
try {
new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(nodeConfig.getOption("l10n").getDefault()), getCfgDir());
} catch (MissingResourceException e1) {
new NodeL10n(BaseL10n.LANGUAGE.mapToLanguage(BaseL10n.LANGUAGE.getDefault().shortCode), getCfgDir());
}
}
// FProxy config needs to be here too
SubConfig fproxyConfig = config.createSubConfig("fproxy");
try {
toadlets = new SimpleToadletServer(fproxyConfig, new ArrayBucketFactory(), executor, this);
fproxyConfig.finishedInitialization();
toadlets.start();
} catch (IOException e4) {
Logger.error(this, "Could not start web interface: "+e4, e4);
System.err.println("Could not start web interface: "+e4);
e4.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_FPROXY, "Could not start FProxy: "+e4);
} catch (InvalidConfigValueException e4) {
System.err.println("Invalid config value, cannot start web interface: "+e4);
e4.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_FPROXY, "Could not start FProxy: "+e4);
}
final NativeThread entropyGatheringThread = new NativeThread(new Runnable() {
long tLastAdded = -1;
private void recurse(File f) {
if(isPRNGReady)
return;
extendTimeouts();
File[] subDirs = f.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
return pathname.exists() && pathname.canRead() && pathname.isDirectory();
}
});
// @see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5086412
if(subDirs != null)
for(File currentDir : subDirs)
recurse(currentDir);
}
@Override
public void run() {
try {
// Delay entropy generation helper hack if enough entropy available
Thread.sleep(100);
} catch (InterruptedException e) {
}
if(isPRNGReady)
return;
System.out.println("Not enough entropy available.");
System.out.println("Trying to gather entropy (randomness) by reading the disk...");
if(File.separatorChar == '/') {
if(new File("/dev/hwrng").exists())
System.out.println("/dev/hwrng exists - have you installed rng-tools?");
else
System.out.println("You should consider installing a better random number generator e.g. haveged.");
}
extendTimeouts();
for(File root : File.listRoots()) {
if(isPRNGReady)
return;
recurse(root);
}
}
/** This is ridiculous, but for some users it can take more than an hour, and timing out sucks
* a few bytes and then times out again. :( */
static final int EXTEND_BY = 60*60*1000;
private void extendTimeouts() {
long now = System.currentTimeMillis();
if(now - tLastAdded < EXTEND_BY/2) return;
long target = tLastAdded + EXTEND_BY;
while(target < now)
target += EXTEND_BY;
long extend = target - now;
assert(extend < Integer.MAX_VALUE);
assert(extend > 0);
WrapperManager.signalStarting((int)extend);
tLastAdded = now;
}
}, "Entropy Gathering Thread", NativeThread.MIN_PRIORITY, true);
// Setup RNG if needed : DO NOT USE IT BEFORE THAT POINT!
if (r == null) {
// Preload required freenet.crypt.Util and freenet.crypt.Rijndael classes (selftest can delay Yarrow startup and trigger false lack-of-enthropy message)
freenet.crypt.Util.mdProviders.size();
freenet.crypt.ciphers.Rijndael.getProviderName();
File seed = userDir.file("prng.seed");
FileUtil.setOwnerRW(seed);
entropyGatheringThread.start();
// Can block.
this.random = new Yarrow(seed);
// http://bugs.sun.com/view_bug.do;jsessionid=ff625daf459fdffffffffcd54f1c775299e0?bug_id=4705093
// This might block on /dev/random while doing new SecureRandom(). Once it's created, it won't block.
ECDH.blockingInit();
} else {
this.random = r;
// if it's not null it's because we are running in the simulator
}
// This can block too.
this.secureRandom = NodeStarter.getGlobalSecureRandom();
isPRNGReady = true;
toadlets.getStartupToadlet().setIsPRNGReady();
if(weakRandom == null) {
byte buffer[] = new byte[16];
random.nextBytes(buffer);
this.fastWeakRandom = new MersenneTwister(buffer);
}else
this.fastWeakRandom = weakRandom;
nodeNameUserAlert = new MeaningfulNodeNameUserAlert(this);
this.config = config;
lm = new LocationManager(random, this);
try {
localhostAddress = InetAddress.getByName("127.0.0.1");
} catch (UnknownHostException e3) {
// Does not do a reverse lookup, so this is impossible
throw new Error(e3);
}
fLocalhostAddress = new FreenetInetAddress(localhostAddress);
this.securityLevels = new SecurityLevels(this, config);
// Location of master key
nodeConfig.register("masterKeyFile", "master.keys", sortOrder++, true, true, "Node.masterKeyFile", "Node.masterKeyFileLong",
new StringCallback() {
@Override
public String get() {
if(masterKeysFile == null) return "none";
else return masterKeysFile.getPath();
}
@Override
public void set(String val) throws InvalidConfigValueException, NodeNeedRestartException {
// FIXME l10n
// FIXME wipe the old one and move
throw new InvalidConfigValueException("Node.masterKeyFile cannot be changed on the fly, you must shutdown, wipe the old file and reconfigure");
}
});
String value = nodeConfig.getString("masterKeyFile");
File f;
if (value.equalsIgnoreCase("none")) {
f = null;
} else {
f = new File(value);
if(f.exists() && !(f.canWrite() && f.canRead()))
throw new NodeInitException(NodeInitException.EXIT_CANT_WRITE_MASTER_KEYS, "Cannot read from and write to master keys file "+f);
}
masterKeysFile = f;
FileUtil.setOwnerRW(masterKeysFile);
nodeConfig.register("showFriendsVisibilityAlert", false, sortOrder++, true, false, "Node.showFriendsVisibilityAlert", "Node.showFriendsVisibilityAlert", new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return showFriendsVisibilityAlert;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(this) {
if(val == showFriendsVisibilityAlert) return;
if(val) return;
}
unregisterFriendsVisibilityAlert();
}
});
showFriendsVisibilityAlert = nodeConfig.getBoolean("showFriendsVisibilityAlert");
byte[] clientCacheKey = null;
MasterSecret persistentSecret = null;
for(int i=0;i<2; i++) {
try {
if(securityLevels.physicalThreatLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) {
keys = MasterKeys.createRandom(secureRandom);
} else {
keys = MasterKeys.read(masterKeysFile, secureRandom, "");
}
clientCacheKey = keys.clientCacheMasterKey;
persistentSecret = keys.getPersistentMasterSecret();
databaseKey = keys.createDatabaseKey(secureRandom);
if(securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.HIGH) {
System.err.println("Physical threat level is set to HIGH but no password, resetting to NORMAL - probably timing glitch");
securityLevels.resetPhysicalThreatLevel(PHYSICAL_THREAT_LEVEL.NORMAL);
}
break;
} catch (MasterKeysWrongPasswordException e) {
break;
} catch (MasterKeysFileSizeException e) {
System.err.println("Impossible: master keys file "+masterKeysFile+" too " + e.sizeToString() + "! Deleting to enable startup, but you will lose your client cache.");
masterKeysFile.delete();
} catch (IOException e) {
break;
}
}
// Boot ID
bootID = random.nextLong();
// Fixed length file containing boot ID. Accessed with random access file. So hopefully it will always be
// written. Note that we set lastBootID to -1 if we can't _write_ our ID as well as if we can't read it,
// because if we can't write it then we probably couldn't write it on the last bootup either.
File bootIDFile = runDir.file("bootID");
int BOOT_FILE_LENGTH = 64 / 4; // A long in padded hex bytes
long oldBootID = -1;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(bootIDFile, "rw");
if(raf.length() < BOOT_FILE_LENGTH) {
oldBootID = -1;
} else {
byte[] buf = new byte[BOOT_FILE_LENGTH];
raf.readFully(buf);
String s = new String(buf, "ISO-8859-1");
try {
oldBootID = Fields.bytesToLong(HexUtil.hexToBytes(s));
} catch (NumberFormatException e) {
oldBootID = -1;
}
raf.seek(0);
}
String s = HexUtil.bytesToHex(Fields.longToBytes(bootID));
byte[] buf = s.getBytes("ISO-8859-1");
if(buf.length != BOOT_FILE_LENGTH)
System.err.println("Not 16 bytes for boot ID "+bootID+" - WTF??");
raf.write(buf);
} catch (IOException e) {
oldBootID = -1;
// If we have an error in reading, *or in writing*, we don't reliably know the last boot ID.
} finally {
Closer.close(raf);
}
lastBootID = oldBootID;
nodeConfig.register("disableProbabilisticHTLs", false, sortOrder++, true, false, "Node.disablePHTLS", "Node.disablePHTLSLong",
new BooleanCallback() {
@Override
public Boolean get() {
return disableProbabilisticHTLs;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
disableProbabilisticHTLs = val;
}
});
disableProbabilisticHTLs = nodeConfig.getBoolean("disableProbabilisticHTLs");
nodeConfig.register("maxHTL", DEFAULT_MAX_HTL, sortOrder++, true, false, "Node.maxHTL", "Node.maxHTLLong", new ShortCallback() {
@Override
public Short get() {
return maxHTL;
}
@Override
public void set(Short val) throws InvalidConfigValueException {
if(val < 0) throw new InvalidConfigValueException("Impossible max HTL");
maxHTL = val;
}
}, false);
maxHTL = nodeConfig.getShort("maxHTL");
class TrafficClassCallback extends StringCallback implements EnumerableOptionCallback {
@Override
public String get() {
return trafficClass.name();
}
@Override
public void set(String tcName) throws InvalidConfigValueException, NodeNeedRestartException {
try {
trafficClass = TrafficClass.fromNameOrValue(tcName);
} catch (IllegalArgumentException e) {
throw new InvalidConfigValueException(e);
}
throw new NodeNeedRestartException("TrafficClass cannot change on the fly");
}
@Override
public String[] getPossibleValues() {
ArrayList<String> array = new ArrayList<String>();
for (TrafficClass tc : TrafficClass.values())
array.add(tc.name());
return array.toArray(new String[0]);
}
}
nodeConfig.register("trafficClass", TrafficClass.getDefault().name(), sortOrder++, true, false,
"Node.trafficClass", "Node.trafficClassLong",
new TrafficClassCallback());
String trafficClassValue = nodeConfig.getString("trafficClass");
try {
trafficClass = TrafficClass.fromNameOrValue(trafficClassValue);
} catch (IllegalArgumentException e) {
Logger.error(this, "Invalid trafficClass:"+trafficClassValue+" resetting the value to default.", e);
trafficClass = TrafficClass.getDefault();
}
// FIXME maybe these should persist? They need to be private.
decrementAtMax = random.nextDouble() <= DECREMENT_AT_MAX_PROB;
decrementAtMin = random.nextDouble() <= DECREMENT_AT_MIN_PROB;
// Determine where to bind to
usm = new MessageCore(executor);
// FIXME maybe these configs should actually be under a node.ip subconfig?
ipDetector = new NodeIPDetector(this);
sortOrder = ipDetector.registerConfigs(nodeConfig, sortOrder);
// ARKs enabled?
nodeConfig.register("enableARKs", true, sortOrder++, true, false, "Node.enableARKs", "Node.enableARKsLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableARKs;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enableARKs = nodeConfig.getBoolean("enableARKs");
nodeConfig.register("enablePerNodeFailureTables", true, sortOrder++, true, false, "Node.enablePerNodeFailureTables", "Node.enablePerNodeFailureTablesLong", new BooleanCallback() {
@Override
public Boolean get() {
return enablePerNodeFailureTables;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enablePerNodeFailureTables = nodeConfig.getBoolean("enablePerNodeFailureTables");
nodeConfig.register("enableULPRDataPropagation", true, sortOrder++, true, false, "Node.enableULPRDataPropagation", "Node.enableULPRDataPropagationLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableULPRDataPropagation;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enableULPRDataPropagation = nodeConfig.getBoolean("enableULPRDataPropagation");
nodeConfig.register("enableSwapping", true, sortOrder++, true, false, "Node.enableSwapping", "Node.enableSwappingLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableSwapping;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throw new InvalidConfigValueException("Cannot change on the fly");
}
@Override
public boolean isReadOnly() {
return true;
}
});
enableSwapping = nodeConfig.getBoolean("enableSwapping");
/*
* Publish our peers' locations is enabled, even in MAXIMUM network security and/or HIGH friends security,
* because a node which doesn't publish its peers' locations will get dramatically less traffic.
*
* Publishing our peers' locations does make us slightly more vulnerable to some attacks, but I don't think
* it's a big difference: swapping reveals the same information, it just doesn't update as quickly. This
* may help slightly, but probably not dramatically against a clever attacker.
*
* FIXME review this decision.
*/
nodeConfig.register("publishOurPeersLocation", true, sortOrder++, true, false, "Node.publishOurPeersLocation", "Node.publishOurPeersLocationLong", new BooleanCallback() {
@Override
public Boolean get() {
return publishOurPeersLocation;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
publishOurPeersLocation = val;
}
});
publishOurPeersLocation = nodeConfig.getBoolean("publishOurPeersLocation");
nodeConfig.register("routeAccordingToOurPeersLocation", true, sortOrder++, true, false, "Node.routeAccordingToOurPeersLocation", "Node.routeAccordingToOurPeersLocation", new BooleanCallback() {
@Override
public Boolean get() {
return routeAccordingToOurPeersLocation;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
routeAccordingToOurPeersLocation = val;
}
});
routeAccordingToOurPeersLocation = nodeConfig.getBoolean("routeAccordingToOurPeersLocation");
nodeConfig.register("enableSwapQueueing", true, sortOrder++, true, false, "Node.enableSwapQueueing", "Node.enableSwapQueueingLong", new BooleanCallback() {
@Override
public Boolean get() {
return enableSwapQueueing;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
enableSwapQueueing = val;
}
});
enableSwapQueueing = nodeConfig.getBoolean("enableSwapQueueing");
nodeConfig.register("enablePacketCoalescing", true, sortOrder++, true, false, "Node.enablePacketCoalescing", "Node.enablePacketCoalescingLong", new BooleanCallback() {
@Override
public Boolean get() {
return enablePacketCoalescing;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
enablePacketCoalescing = val;
}
});
enablePacketCoalescing = nodeConfig.getBoolean("enablePacketCoalescing");
// Determine the port number
// @see #191
if(oldConfig != null && "-1".equals(oldConfig.get("node.listenPort")))
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_BIND_USM, "Your freenet.ini file is corrupted! 'listenPort=-1'");
NodeCryptoConfig darknetConfig = new NodeCryptoConfig(nodeConfig, sortOrder++, false, securityLevels);
sortOrder += NodeCryptoConfig.OPTION_COUNT;
darknetCrypto = new NodeCrypto(this, false, darknetConfig, startupTime, enableARKs);
// Must be created after darknetCrypto
dnsr = new DNSRequester(this);
ps = new PacketSender(this);
ticker = new PrioritizedTicker(executor, getDarknetPortNumber());
if(executor instanceof PooledExecutor)
((PooledExecutor)executor).setTicker(ticker);
Logger.normal(Node.class, "Creating node...");
shutdownHook.addEarlyJob(new Thread() {
@Override
public void run() {
if (opennet != null)
opennet.stop(false);
}
});
shutdownHook.addEarlyJob(new Thread() {
@Override
public void run() {
darknetCrypto.stop();
}
});
// Bandwidth limit
nodeConfig.register("outputBandwidthLimit", "15K", sortOrder++, false, true, "Node.outBWLimit", "Node.outBWLimitLong", new IntCallback() {
@Override
public Integer get() {
//return BlockTransmitter.getHardBandwidthLimit();
return outputBandwidthLimit;
}
@Override
public void set(Integer obwLimit) throws InvalidConfigValueException {
BandwidthManager.checkOutputBandwidthLimit(obwLimit);
try {
outputThrottle.changeNanosAndBucketSize(SECONDS.toNanos(1) / obwLimit, obwLimit/2);
} catch (IllegalArgumentException e) {
throw new InvalidConfigValueException(e);
}
synchronized(Node.this) {
outputBandwidthLimit = obwLimit;
}
}
});
int obwLimit = nodeConfig.getInt("outputBandwidthLimit");
if (obwLimit < minimumBandwidth) {
obwLimit = minimumBandwidth; // upgrade slow nodes automatically
Logger.normal(Node.class, "Output bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth.");
}
outputBandwidthLimit = obwLimit;
try {
BandwidthManager.checkOutputBandwidthLimit(outputBandwidthLimit);
} catch (InvalidConfigValueException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage());
}
// Bucket size of 0.5 seconds' worth of bytes.
// Add them at a rate determined by the obwLimit.
// Maximum forced bytes 80%, in other words, 20% of the bandwidth is reserved for
// block transfers, so we will use that 20% for block transfers even if more than 80% of the limit is used for non-limited data (resends etc).
int bucketSize = obwLimit/2;
// Must have at least space for ONE PACKET.
// FIXME: make compatible with alternate transports.
bucketSize = Math.max(bucketSize, 2048);
try {
outputThrottle = new TokenBucket(bucketSize, SECONDS.toNanos(1) / obwLimit, obwLimit/2);
} catch (IllegalArgumentException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage());
}
nodeConfig.register("inputBandwidthLimit", "-1", sortOrder++, false, true, "Node.inBWLimit", "Node.inBWLimitLong", new IntCallback() {
@Override
public Integer get() {
if(inputLimitDefault) return -1;
return inputBandwidthLimit;
}
@Override
public void set(Integer ibwLimit) throws InvalidConfigValueException {
synchronized(Node.this) {
BandwidthManager.checkInputBandwidthLimit(ibwLimit);
if(ibwLimit == -1) {
inputLimitDefault = true;
ibwLimit = outputBandwidthLimit * 4;
} else {
inputLimitDefault = false;
}
inputBandwidthLimit = ibwLimit;
}
}
});
int ibwLimit = nodeConfig.getInt("inputBandwidthLimit");
if(ibwLimit == -1) {
inputLimitDefault = true;
ibwLimit = obwLimit * 4;
}
else if (ibwLimit < minimumBandwidth) {
ibwLimit = minimumBandwidth; // upgrade slow nodes automatically
Logger.normal(Node.class, "Input bandwidth was lower than minimum bandwidth. Increased to minimum bandwidth.");
}
inputBandwidthLimit = ibwLimit;
try {
BandwidthManager.checkInputBandwidthLimit(inputBandwidthLimit);
} catch (InvalidConfigValueException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_BWLIMIT, e.getMessage());
}
nodeConfig.register("amountOfDataToCheckCompressionRatio", "8MiB", sortOrder++,
true, true, "Node.amountOfDataToCheckCompressionRatio",
"Node.amountOfDataToCheckCompressionRatioLong", new LongCallback() {
@Override
public Long get() {
return amountOfDataToCheckCompressionRatio;
}
@Override
public void set(Long amountOfDataToCheckCompressionRatio) {
synchronized(Node.this) {
Node.this.amountOfDataToCheckCompressionRatio = amountOfDataToCheckCompressionRatio;
}
}
}, true);
amountOfDataToCheckCompressionRatio = nodeConfig.getLong("amountOfDataToCheckCompressionRatio");
nodeConfig.register("minimumCompressionPercentage", "10", sortOrder++,
true, true, "Node.minimumCompressionPercentage",
"Node.minimumCompressionPercentageLong", new IntCallback() {
@Override
public Integer get() {
return minimumCompressionPercentage;
}
@Override
public void set(Integer minimumCompressionPercentage) {
synchronized(Node.this) {
if (minimumCompressionPercentage < 0 || minimumCompressionPercentage > 100) {
Logger.normal(Node.class, "Wrong minimum compression percentage" + minimumCompressionPercentage);
return;
}
Node.this.minimumCompressionPercentage = minimumCompressionPercentage;
}
}
}, Dimension.NOT);
minimumCompressionPercentage = nodeConfig.getInt("minimumCompressionPercentage");
nodeConfig.register("maxTimeForSingleCompressor", "20m", sortOrder++,
true, true, "Node.maxTimeForSingleCompressor",
"Node.maxTimeForSingleCompressorLong", new IntCallback() {
@Override
public Integer get() {
return maxTimeForSingleCompressor;
}
@Override
public void set(Integer maxTimeForSingleCompressor) {
synchronized(Node.this) {
Node.this.maxTimeForSingleCompressor = maxTimeForSingleCompressor;
}
}
}, Dimension.DURATION);
maxTimeForSingleCompressor = nodeConfig.getInt("maxTimeForSingleCompressor");
nodeConfig.register("connectionSpeedDetection", true, sortOrder++,
true, true, "Node.connectionSpeedDetection",
"Node.connectionSpeedDetectionLong", new BooleanCallback() {
@Override
public Boolean get() {
return connectionSpeedDetection;
}
@Override
public void set(Boolean connectionSpeedDetection) {
synchronized(Node.this) {
Node.this.connectionSpeedDetection = connectionSpeedDetection;
}
}
});
connectionSpeedDetection = nodeConfig.getBoolean("connectionSpeedDetection");
nodeConfig.register("throttleLocalTraffic", false, sortOrder++, true, false, "Node.throttleLocalTraffic", "Node.throttleLocalTrafficLong", new BooleanCallback() {
@Override
public Boolean get() {
return throttleLocalData;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
throttleLocalData = val;
}
});
throttleLocalData = nodeConfig.getBoolean("throttleLocalTraffic");
String s = "Testnet mode DISABLED. You may have some level of anonymity. :)\n"+
"Note that this version of Freenet is still a very early alpha, and may well have numerous bugs and design flaws.\n"+
"In particular: YOU ARE WIDE OPEN TO YOUR IMMEDIATE PEERS! They can eavesdrop on your requests with relatively little difficulty at present (correlation attacks etc).";
Logger.normal(this, s);
System.err.println(s);
File nodeFile = nodeDir.file("node-"+getDarknetPortNumber());
File nodeFileBackup = nodeDir.file("node-"+getDarknetPortNumber()+".bak");
// After we have set up testnet and IP address, load the node file
try {
// FIXME should take file directly?
readNodeFile(nodeFile.getPath());
} catch (IOException e) {
try {
System.err.println("Trying to read node file backup ...");
readNodeFile(nodeFileBackup.getPath());
} catch (IOException e1) {
if(nodeFile.exists() || nodeFileBackup.exists()) {
System.err.println("No node file or cannot read, (re)initialising crypto etc");
System.err.println(e1.toString());
e1.printStackTrace();
System.err.println("After:");
System.err.println(e.toString());
e.printStackTrace();
} else {
System.err.println("Creating new cryptographic keys...");
}
initNodeFileSettings();
}
}
// Then read the peers
peers = new PeerManager(this, shutdownHook);
tracker = new RequestTracker(peers, ticker);
usm.setDispatcher(dispatcher=new NodeDispatcher(this));
uptime = new UptimeEstimator(runDir, ticker, darknetCrypto.identityHash);
// ULPRs
failureTable = new FailureTable(this);
nodeStats = new NodeStats(this, sortOrder, config.createSubConfig("node.load"), obwLimit, ibwLimit, lastVersion);
// clientCore needs new load management and other settings from stats.
clientCore = new NodeClientCore(this, config, nodeConfig, installConfig, getDarknetPortNumber(), sortOrder, oldConfig, fproxyConfig, toadlets, databaseKey, persistentSecret);
toadlets.setCore(clientCore);
if (JVMVersion.isEOL()) {
clientCore.alerts.register(new JVMVersionAlert());
}
if(showFriendsVisibilityAlert)
registerFriendsVisibilityAlert();
// Node updater support
System.out.println("Initializing Node Updater");
try {
nodeUpdater = NodeUpdateManager.maybeCreate(this, config);
} catch (InvalidConfigValueException e) {
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_UPDATER, "Could not create Updater: "+e);
}
// Opennet
final SubConfig opennetConfig = config.createSubConfig("node.opennet");
opennetConfig.register("connectToSeednodes", true, 0, true, false, "Node.withAnnouncement", "Node.withAnnouncementLong", new BooleanCallback() {
@Override
public Boolean get() {
return isAllowedToConnectToSeednodes;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
if (get().equals(val))
return;
synchronized(Node.this) {
isAllowedToConnectToSeednodes = val;
if(opennet != null)
throw new NodeNeedRestartException(l10n("connectToSeednodesCannotBeChangedMustDisableOpennetOrReboot"));
}
}
});
isAllowedToConnectToSeednodes = opennetConfig.getBoolean("connectToSeednodes");
// Can be enabled on the fly
opennetConfig.register("enabled", false, 0, true, true, "Node.opennetEnabled", "Node.opennetEnabledLong", new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return opennet != null;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
OpennetManager o;
synchronized(Node.this) {
if(val == (opennet != null)) return;
if(val) {
try {
o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes);
} catch (NodeInitException e) {
opennet = null;
throw new InvalidConfigValueException(e.getMessage());
}
} else {
o = opennet;
opennet = null;
}
}
if(val) o.start();
else o.stop(true);
ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts());
}
});
boolean opennetEnabled = opennetConfig.getBoolean("enabled");
opennetConfig.register("maxOpennetPeers", OpennetManager.MAX_PEERS_FOR_SCALING, 1, true, false, "Node.maxOpennetPeers",
"Node.maxOpennetPeersLong", new IntCallback() {
@Override
public Integer get() {
return maxOpennetPeers;
}
@Override
public void set(Integer inputMaxOpennetPeers) throws InvalidConfigValueException {
if(inputMaxOpennetPeers < 0) throw new InvalidConfigValueException(l10n("mustBePositive"));
if(inputMaxOpennetPeers > OpennetManager.MAX_PEERS_FOR_SCALING) throw new InvalidConfigValueException(l10n("maxOpennetPeersMustBeTwentyOrLess", "maxpeers", Integer.toString(OpennetManager.MAX_PEERS_FOR_SCALING)));
maxOpennetPeers = inputMaxOpennetPeers;
}
}
, false);
maxOpennetPeers = opennetConfig.getInt("maxOpennetPeers");
if(maxOpennetPeers > OpennetManager.MAX_PEERS_FOR_SCALING) {
Logger.error(this, "maxOpennetPeers may not be over "+OpennetManager.MAX_PEERS_FOR_SCALING);
maxOpennetPeers = OpennetManager.MAX_PEERS_FOR_SCALING;
}
opennetCryptoConfig = new NodeCryptoConfig(opennetConfig, 2 /* 0 = enabled */, true, securityLevels);
if(opennetEnabled) {
opennet = new OpennetManager(this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes);
// Will be started later
} else {
opennet = null;
}
securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) {
if(newLevel == NETWORK_THREAT_LEVEL.HIGH
|| newLevel == NETWORK_THREAT_LEVEL.MAXIMUM) {
OpennetManager om;
synchronized(Node.this) {
om = opennet;
if(om != null)
opennet = null;
}
if(om != null) {
om.stop(true);
ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts());
}
} else if(newLevel == NETWORK_THREAT_LEVEL.NORMAL
|| newLevel == NETWORK_THREAT_LEVEL.LOW) {
OpennetManager o = null;
synchronized(Node.this) {
if(opennet == null) {
try {
o = opennet = new OpennetManager(Node.this, opennetCryptoConfig, System.currentTimeMillis(), isAllowedToConnectToSeednodes);
} catch (NodeInitException e) {
opennet = null;
Logger.error(this, "UNABLE TO ENABLE OPENNET: "+e, e);
clientCore.alerts.register(new SimpleUserAlert(false, l10n("enableOpennetFailedTitle"), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), l10n("enableOpennetFailed", "message", e.getLocalizedMessage()), UserAlert.ERROR));
}
}
}
if(o != null) {
o.start();
ipDetector.ipDetectorManager.notifyPortChange(getPublicInterfacePorts());
}
}
Node.this.config.store();
}
});
opennetConfig.register("acceptSeedConnections", false, 2, true, true, "Node.acceptSeedConnectionsShort", "Node.acceptSeedConnections", new BooleanCallback() {
@Override
public Boolean get() {
return acceptSeedConnections;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
acceptSeedConnections = val;
}
});
acceptSeedConnections = opennetConfig.getBoolean("acceptSeedConnections");
if(acceptSeedConnections && opennet != null)
opennet.crypto.socket.getAddressTracker().setHugeTracker();
opennetConfig.finishedInitialization();
nodeConfig.register("passOpennetPeersThroughDarknet", true, sortOrder++, true, false, "Node.passOpennetPeersThroughDarknet", "Node.passOpennetPeersThroughDarknetLong",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return passOpennetRefsThroughDarknet;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
synchronized(Node.this) {
passOpennetRefsThroughDarknet = val;
}
}
});
passOpennetRefsThroughDarknet = nodeConfig.getBoolean("passOpennetPeersThroughDarknet");
this.extraPeerDataDir = userDir.file("extra-peer-data-"+getDarknetPortNumber());
if (!((extraPeerDataDir.exists() && extraPeerDataDir.isDirectory()) || (extraPeerDataDir.mkdir()))) {
String msg = "Could not find or create extra peer data directory";
throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, msg);
}
// Name
nodeConfig.register("name", myName, sortOrder++, false, true, "Node.nodeName", "Node.nodeNameLong",
new NodeNameCallback());
myName = nodeConfig.getString("name");
// Datastore
nodeConfig.register("storeForceBigShrinks", false, sortOrder++, true, false, "Node.forceBigShrink", "Node.forceBigShrinkLong",
new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return storeForceBigShrinks;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException {
synchronized(Node.this) {
storeForceBigShrinks = val;
}
}
});
// Datastore
nodeConfig.register("storeType", "ram", sortOrder++, true, true, "Node.storeType", "Node.storeTypeLong", new StoreTypeCallback());
storeType = nodeConfig.getString("storeType");
/*
* Very small initial store size, since the node will preallocate it when starting up for the first time,
* BLOCKING STARTUP, and since everyone goes through the wizard anyway...
*/
nodeConfig.register("storeSize", DEFAULT_STORE_SIZE, sortOrder++, false, true, "Node.storeSize", "Node.storeSizeLong",
new LongCallback() {
@Override
public Long get() {
return maxTotalDatastoreSize;
}
@Override
public void set(Long storeSize) throws InvalidConfigValueException {
if(storeSize < MIN_STORE_SIZE)
throw new InvalidConfigValueException(l10n("invalidStoreSize"));
long newMaxStoreKeys = storeSize / sizePerKey;
if(newMaxStoreKeys == maxTotalKeys) return;
// Update each datastore
synchronized(Node.this) {
maxTotalDatastoreSize = storeSize;
maxTotalKeys = newMaxStoreKeys;
maxStoreKeys = maxTotalKeys / 2;
maxCacheKeys = maxTotalKeys - maxStoreKeys;
}
try {
chkDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks);
chkDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks);
pubKeyDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks);
pubKeyDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks);
sskDatastore.setMaxKeys(maxStoreKeys, storeForceBigShrinks);
sskDatacache.setMaxKeys(maxCacheKeys, storeForceBigShrinks);
} catch (IOException e) {
// FIXME we need to be able to tell the user.
Logger.error(this, "Caught "+e+" resizing the datastore", e);
System.err.println("Caught "+e+" resizing the datastore");
e.printStackTrace();
}
//Perhaps a bit hackish...? Seems like this should be near it's definition in NodeStats.
nodeStats.avgStoreCHKLocation.changeMaxReports((int)maxStoreKeys);
nodeStats.avgCacheCHKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgSlashdotCacheCHKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgClientCacheCHKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgStoreSSKLocation.changeMaxReports((int)maxStoreKeys);
nodeStats.avgCacheSSKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgSlashdotCacheSSKLocation.changeMaxReports((int)maxCacheKeys);
nodeStats.avgClientCacheSSKLocation.changeMaxReports((int)maxCacheKeys);
}
}, true);
maxTotalDatastoreSize = nodeConfig.getLong("storeSize");
if(maxTotalDatastoreSize < MIN_STORE_SIZE && !storeType.equals("ram")) { // totally arbitrary minimum!
throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Store size too small");
}
maxTotalKeys = maxTotalDatastoreSize / sizePerKey;
nodeConfig.register("storeUseSlotFilters", true, sortOrder++, true, false, "Node.storeUseSlotFilters", "Node.storeUseSlotFiltersLong", new BooleanCallback() {
public Boolean get() {
synchronized(Node.this) {
return storeUseSlotFilters;
}
}
public void set(Boolean val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(Node.this) {
storeUseSlotFilters = val;
}
// FIXME l10n
throw new NodeNeedRestartException("Need to restart to change storeUseSlotFilters");
}
});
storeUseSlotFilters = nodeConfig.getBoolean("storeUseSlotFilters");
nodeConfig.register("storeSaltHashSlotFilterPersistenceTime", ResizablePersistentIntBuffer.DEFAULT_PERSISTENCE_TIME, sortOrder++, true, false,
"Node.storeSaltHashSlotFilterPersistenceTime", "Node.storeSaltHashSlotFilterPersistenceTimeLong", new IntCallback() {
@Override
public Integer get() {
return ResizablePersistentIntBuffer.getPersistenceTime();
}
@Override
public void set(Integer val)
throws InvalidConfigValueException,
NodeNeedRestartException {
if(val >= -1)
ResizablePersistentIntBuffer.setPersistenceTime(val);
else
throw new InvalidConfigValueException(l10n("slotFilterPersistenceTimeError"));
}
}, false);
nodeConfig.register("storeSaltHashResizeOnStart", false, sortOrder++, true, false,
"Node.storeSaltHashResizeOnStart", "Node.storeSaltHashResizeOnStartLong", new BooleanCallback() {
@Override
public Boolean get() {
return storeSaltHashResizeOnStart;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
storeSaltHashResizeOnStart = val;
}
});
storeSaltHashResizeOnStart = nodeConfig.getBoolean("storeSaltHashResizeOnStart");
this.storeDir = setupProgramDir(installConfig, "storeDir", userDir().file("datastore").getPath(), "Node.storeDirectory", "Node.storeDirectoryLong", nodeConfig);
installConfig.finishedInitialization();
final String suffix = getStoreSuffix();
maxStoreKeys = maxTotalKeys / 2;
maxCacheKeys = maxTotalKeys - maxStoreKeys;
/*
* On Windows, setting the file length normally involves writing lots of zeros.
* So it's an uninterruptible system call that takes a loooong time. On OS/X,
* presumably the same is true. If the RNG is fast enough, this means that
* setting the length and writing random data take exactly the same amount
* of time. On most versions of Unix, holes can be created. However on all
* systems, predictable disk usage is a good thing. So lets turn it on by
* default for now, on all systems. The datastore can be read but mostly not
* written while the random data is being written.
*/
nodeConfig.register("storePreallocate", true, sortOrder++, true, true, "Node.storePreallocate", "Node.storePreallocateLong",
new BooleanCallback() {
@Override
public Boolean get() {
return storePreallocate;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
storePreallocate = val;
if (storeType.equals("salt-hash")) {
setPreallocate(chkDatastore, val);
setPreallocate(chkDatacache, val);
setPreallocate(pubKeyDatastore, val);
setPreallocate(pubKeyDatacache, val);
setPreallocate(sskDatastore, val);
setPreallocate(sskDatacache, val);
}
}
private void setPreallocate(StoreCallback<?> datastore,
boolean val) {
// Avoid race conditions by checking first.
FreenetStore<?> store = datastore.getStore();
if(store instanceof SaltedHashFreenetStore)
((SaltedHashFreenetStore<?>)store).setPreallocate(val);
}}
);
storePreallocate = nodeConfig.getBoolean("storePreallocate");
if(File.separatorChar == '/' && System.getProperty("os.name").toLowerCase().indexOf("mac os") < 0) {
securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<SecurityLevels.PHYSICAL_THREAT_LEVEL>() {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
try {
if(newLevel == PHYSICAL_THREAT_LEVEL.LOW)
nodeConfig.set("storePreallocate", false);
else
nodeConfig.set("storePreallocate", true);
} catch (NodeNeedRestartException e) {
// Ignore
} catch (InvalidConfigValueException e) {
// Ignore
}
}
});
}
securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<SecurityLevels.PHYSICAL_THREAT_LEVEL>() {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
if(newLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) {
synchronized(this) {
clientCacheAwaitingPassword = false;
databaseAwaitingPassword = false;
}
try {
killMasterKeysFile();
clientCore.clientLayerPersister.disableWrite();
clientCore.clientLayerPersister.waitForNotWriting();
clientCore.clientLayerPersister.deleteAllFiles();
} catch (IOException e) {
masterKeysFile.delete();
Logger.error(this, "Unable to securely delete "+masterKeysFile);
System.err.println(NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFile", "filename", masterKeysFile.getAbsolutePath()));
clientCore.alerts.register(new SimpleUserAlert(true, NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFileTitle"), NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFile"), NodeL10n.getBase().getString("SecurityLevels.cantDeletePasswordFileTitle"), UserAlert.CRITICAL_ERROR));
}
}
if(oldLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM && newLevel != PHYSICAL_THREAT_LEVEL.HIGH) {
// Not passworded.
// Create the master.keys.
// Keys must exist.
try {
MasterKeys keys;
synchronized(this) {
keys = Node.this.keys;
}
keys.changePassword(masterKeysFile, "", secureRandom);
} catch (IOException e) {
Logger.error(this, "Unable to create encryption keys file: "+masterKeysFile+" : "+e, e);
System.err.println("Unable to create encryption keys file: "+masterKeysFile+" : "+e);
e.printStackTrace();
}
}
}
});
if(securityLevels.physicalThreatLevel == PHYSICAL_THREAT_LEVEL.MAXIMUM) {
try {
killMasterKeysFile();
} catch (IOException e) {
String msg = "Unable to securely delete old master.keys file when switching to MAXIMUM seclevel!!";
System.err.println(msg);
throw new NodeInitException(NodeInitException.EXIT_CANT_WRITE_MASTER_KEYS, msg);
}
}
long defaultCacheSize;
long memoryLimit = NodeStarter.getMemoryLimitBytes();
// This is tricky because systems with low memory probably also have slow disks, but using
// up too much memory can be catastrophic...
// Total alchemy, FIXME!
if(memoryLimit == Long.MAX_VALUE || memoryLimit < 0)
defaultCacheSize = 1024*1024;
else if(memoryLimit <= 128*1024*1024)
defaultCacheSize = 0; // Turn off completely for very small memory.
else {
// 9 stores, total should be 5% of memory, up to maximum of 1MB per store at 308MB+
defaultCacheSize = Math.min(1024*1024, (memoryLimit - 128*1024*1024) / (20*9));
}
nodeConfig.register("cachingFreenetStoreMaxSize", defaultCacheSize, sortOrder++, true, false, "Node.cachingFreenetStoreMaxSize", "Node.cachingFreenetStoreMaxSizeLong",
new LongCallback() {
@Override
public Long get() {
synchronized(Node.this) {
return cachingFreenetStoreMaxSize;
}
}
@Override
public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException {
if(val < 0) throw new InvalidConfigValueException(l10n("invalidMemoryCacheSize"));
// Any positive value is legal. In particular, e.g. 1200 bytes would cause us to cache SSKs but not CHKs.
synchronized(Node.this) {
cachingFreenetStoreMaxSize = val;
}
throw new NodeNeedRestartException("Caching Maximum Size cannot be changed on the fly");
}
}, true);
cachingFreenetStoreMaxSize = nodeConfig.getLong("cachingFreenetStoreMaxSize");
if(cachingFreenetStoreMaxSize < 0)
throw new NodeInitException(NodeInitException.EXIT_BAD_CONFIG, l10n("invalidMemoryCacheSize"));
nodeConfig.register("cachingFreenetStorePeriod", "300k", sortOrder++, true, false, "Node.cachingFreenetStorePeriod", "Node.cachingFreenetStorePeriod",
new LongCallback() {
@Override
public Long get() {
synchronized(Node.this) {
return cachingFreenetStorePeriod;
}
}
@Override
public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException {
synchronized(Node.this) {
cachingFreenetStorePeriod = val;
}
throw new NodeNeedRestartException("Caching Period cannot be changed on the fly");
}
}, true);
cachingFreenetStorePeriod = nodeConfig.getLong("cachingFreenetStorePeriod");
if(cachingFreenetStoreMaxSize > 0 && cachingFreenetStorePeriod > 0) {
cachingFreenetStoreTracker = new CachingFreenetStoreTracker(cachingFreenetStoreMaxSize, cachingFreenetStorePeriod, ticker);
}
boolean shouldWriteConfig = false;
if(storeType.equals("bdb-index")) {
System.err.println("Old format Berkeley DB datastore detected.");
System.err.println("This datastore format is no longer supported.");
System.err.println("The old datastore will be securely deleted.");
storeType = "salt-hash";
shouldWriteConfig = true;
deleteOldBDBIndexStoreFiles();
}
if (storeType.equals("salt-hash")) {
initRAMFS();
initSaltHashFS(suffix, false, null);
} else {
initRAMFS();
}
if(databaseAwaitingPassword) createPasswordUserAlert();
// Client cache
// Default is 10MB, in memory only. The wizard will change this.
nodeConfig.register("clientCacheType", "ram", sortOrder++, true, true, "Node.clientCacheType", "Node.clientCacheTypeLong", new ClientCacheTypeCallback());
clientCacheType = nodeConfig.getString("clientCacheType");
nodeConfig.register("clientCacheSize", DEFAULT_CLIENT_CACHE_SIZE, sortOrder++, false, true, "Node.clientCacheSize", "Node.clientCacheSizeLong",
new LongCallback() {
@Override
public Long get() {
return maxTotalClientCacheSize;
}
@Override
public void set(Long storeSize) throws InvalidConfigValueException {
if(storeSize < MIN_CLIENT_CACHE_SIZE)
throw new InvalidConfigValueException(l10n("invalidStoreSize"));
long newMaxStoreKeys = storeSize / sizePerKey;
if(newMaxStoreKeys == maxClientCacheKeys) return;
// Update each datastore
synchronized(Node.this) {
maxTotalClientCacheSize = storeSize;
maxClientCacheKeys = newMaxStoreKeys;
}
try {
chkClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks);
pubKeyClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks);
sskClientcache.setMaxKeys(maxClientCacheKeys, storeForceBigShrinks);
} catch (IOException e) {
// FIXME we need to be able to tell the user.
Logger.error(this, "Caught "+e+" resizing the clientcache", e);
System.err.println("Caught "+e+" resizing the clientcache");
e.printStackTrace();
}
}
}, true);
maxTotalClientCacheSize = nodeConfig.getLong("clientCacheSize");
if(maxTotalClientCacheSize < MIN_CLIENT_CACHE_SIZE) {
throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Client cache size too small");
}
maxClientCacheKeys = maxTotalClientCacheSize / sizePerKey;
boolean startedClientCache = false;
if (clientCacheType.equals("salt-hash")) {
if(clientCacheKey == null) {
System.err.println("Cannot open client-cache, it is passworded");
setClientCacheAwaitingPassword();
} else {
initSaltHashClientCacheFS(suffix, false, clientCacheKey);
startedClientCache = true;
}
} else if(clientCacheType.equals("none")) {
initNoClientCacheFS();
startedClientCache = true;
} else { // ram
initRAMClientCacheFS();
startedClientCache = true;
}
if(!startedClientCache)
initRAMClientCacheFS();
if(!clientCore.loadedDatabase() && databaseKey != null) {
try {
lateSetupDatabase(databaseKey);
} catch (MasterKeysWrongPasswordException e2) {
System.err.println("Impossible: "+e2);
e2.printStackTrace();
} catch (MasterKeysFileSizeException e2) {
System.err.println("Impossible: "+e2);
e2.printStackTrace();
} catch (IOException e2) {
System.err.println("Unable to load database: "+e2);
e2.printStackTrace();
}
}
nodeConfig.register("useSlashdotCache", true, sortOrder++, true, false, "Node.useSlashdotCache", "Node.useSlashdotCacheLong", new BooleanCallback() {
@Override
public Boolean get() {
return useSlashdotCache;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
useSlashdotCache = val;
}
});
useSlashdotCache = nodeConfig.getBoolean("useSlashdotCache");
nodeConfig.register("writeLocalToDatastore", false, sortOrder++, true, false, "Node.writeLocalToDatastore", "Node.writeLocalToDatastoreLong", new BooleanCallback() {
@Override
public Boolean get() {
return writeLocalToDatastore;
}
@Override
public void set(Boolean val) throws InvalidConfigValueException, NodeNeedRestartException {
writeLocalToDatastore = val;
}
});
writeLocalToDatastore = nodeConfig.getBoolean("writeLocalToDatastore");
// LOW network *and* physical seclevel = writeLocalToDatastore
securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) {
if(newLevel == NETWORK_THREAT_LEVEL.LOW && securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.LOW)
writeLocalToDatastore = true;
else
writeLocalToDatastore = false;
}
});
securityLevels.addPhysicalThreatLevelListener(new SecurityLevelListener<PHYSICAL_THREAT_LEVEL>() {
@Override
public void onChange(PHYSICAL_THREAT_LEVEL oldLevel, PHYSICAL_THREAT_LEVEL newLevel) {
if(newLevel == PHYSICAL_THREAT_LEVEL.LOW && securityLevels.getNetworkThreatLevel() == NETWORK_THREAT_LEVEL.LOW)
writeLocalToDatastore = true;
else
writeLocalToDatastore = false;
}
});
nodeConfig.register("slashdotCacheLifetime", MINUTES.toMillis(30), sortOrder++, true, false, "Node.slashdotCacheLifetime", "Node.slashdotCacheLifetimeLong", new LongCallback() {
@Override
public Long get() {
return chkSlashdotcacheStore.getLifetime();
}
@Override
public void set(Long val) throws InvalidConfigValueException, NodeNeedRestartException {
if(val < 0) throw new InvalidConfigValueException("Must be positive!");
chkSlashdotcacheStore.setLifetime(val);
pubKeySlashdotcacheStore.setLifetime(val);
sskSlashdotcacheStore.setLifetime(val);
}
}, false);
long slashdotCacheLifetime = nodeConfig.getLong("slashdotCacheLifetime");
nodeConfig.register("slashdotCacheSize", DEFAULT_SLASHDOT_CACHE_SIZE, sortOrder++, false, true, "Node.slashdotCacheSize", "Node.slashdotCacheSizeLong",
new LongCallback() {
@Override
public Long get() {
return maxSlashdotCacheSize;
}
@Override
public void set(Long storeSize) throws InvalidConfigValueException {
if(storeSize < MIN_SLASHDOT_CACHE_SIZE)
throw new InvalidConfigValueException(l10n("invalidStoreSize"));
int newMaxStoreKeys = (int) Math.min(storeSize / sizePerKey, Integer.MAX_VALUE);
if(newMaxStoreKeys == maxSlashdotCacheKeys) return;
// Update each datastore
synchronized(Node.this) {
maxSlashdotCacheSize = storeSize;
maxSlashdotCacheKeys = newMaxStoreKeys;
}
try {
chkSlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks);
pubKeySlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks);
sskSlashdotcache.setMaxKeys(maxSlashdotCacheKeys, storeForceBigShrinks);
} catch (IOException e) {
// FIXME we need to be able to tell the user.
Logger.error(this, "Caught "+e+" resizing the slashdotcache", e);
System.err.println("Caught "+e+" resizing the slashdotcache");
e.printStackTrace();
}
}
}, true);
maxSlashdotCacheSize = nodeConfig.getLong("slashdotCacheSize");
if(maxSlashdotCacheSize < MIN_SLASHDOT_CACHE_SIZE) {
throw new NodeInitException(NodeInitException.EXIT_INVALID_STORE_SIZE, "Slashdot cache size too small");
}
maxSlashdotCacheKeys = (int) Math.min(maxSlashdotCacheSize / sizePerKey, Integer.MAX_VALUE);
chkSlashdotcache = new CHKStore();
chkSlashdotcacheStore = new SlashdotStore<CHKBlock>(chkSlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory);
pubKeySlashdotcache = new PubkeyStore();
pubKeySlashdotcacheStore = new SlashdotStore<DSAPublicKey>(pubKeySlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory);
getPubKey.setLocalSlashdotcache(pubKeySlashdotcache);
sskSlashdotcache = new SSKStore(getPubKey);
sskSlashdotcacheStore = new SlashdotStore<SSKBlock>(sskSlashdotcache, maxSlashdotCacheKeys, slashdotCacheLifetime, PURGE_INTERVAL, ticker, this.clientCore.tempBucketFactory);
// MAXIMUM seclevel = no slashdot cache.
securityLevels.addNetworkThreatLevelListener(new SecurityLevelListener<NETWORK_THREAT_LEVEL>() {
@Override
public void onChange(NETWORK_THREAT_LEVEL oldLevel, NETWORK_THREAT_LEVEL newLevel) {
if(newLevel == NETWORK_THREAT_LEVEL.MAXIMUM)
useSlashdotCache = false;
else if(oldLevel == NETWORK_THREAT_LEVEL.MAXIMUM)
useSlashdotCache = true;
}
});
nodeConfig.register("skipWrapperWarning", false, sortOrder++, true, false, "Node.skipWrapperWarning", "Node.skipWrapperWarningLong", new BooleanCallback() {
@Override
public void set(Boolean value) throws InvalidConfigValueException, NodeNeedRestartException {
skipWrapperWarning = value;
}
@Override
public Boolean get() {
return skipWrapperWarning;
}
});
skipWrapperWarning = nodeConfig.getBoolean("skipWrapperWarning");
nodeConfig.register("maxPacketSize", 1280, sortOrder++, true, true, "Node.maxPacketSize", "Node.maxPacketSizeLong", new IntCallback() {
@Override
public Integer get() {
synchronized(Node.this) {
return maxPacketSize;
}
}
@Override
public void set(Integer val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(Node.this) {
if(val == maxPacketSize) return;
if(val < UdpSocketHandler.MIN_MTU) throw new InvalidConfigValueException("Must be over 576");
if(val > 1492) throw new InvalidConfigValueException("Larger than ethernet frame size unlikely to work!");
maxPacketSize = val;
}
updateMTU();
}
}, true);
maxPacketSize = nodeConfig.getInt("maxPacketSize");
nodeConfig.register("enableRoutedPing", false, sortOrder++, true, false, "Node.enableRoutedPing", "Node.enableRoutedPingLong", new BooleanCallback() {
@Override
public Boolean get() {
synchronized(Node.this) {
return enableRoutedPing;
}
}
@Override
public void set(Boolean val) throws InvalidConfigValueException,
NodeNeedRestartException {
synchronized(Node.this) {
enableRoutedPing = val;
}
}
});
enableRoutedPing = nodeConfig.getBoolean("enableRoutedPing");
updateMTU();
// peers-offers/*.fref files
peersOffersFrefFilesConfiguration(nodeConfig, sortOrder++);
if (!peersOffersDismissed && checkPeersOffersFrefFiles())
PeersOffersUserAlert.createAlert(this);
/* Take care that no configuration options are registered after this point; they will not persist
* between restarts.
*/
nodeConfig.finishedInitialization();
if(shouldWriteConfig) config.store();
writeNodeFile();
// Initialize the plugin manager
Logger.normal(this, "Initializing Plugin Manager");
System.out.println("Initializing Plugin Manager");
pluginManager = new PluginManager(this, lastVersion);
shutdownHook.addEarlyJob(new NativeThread("Shutdown plugins", NativeThread.HIGH_PRIORITY, true) {
@Override
public void realRun() {
pluginManager.stop(SECONDS.toMillis(30)); // FIXME make it configurable??
}
});
// FIXME
// Short timeouts and JVM timeouts with nothing more said than the above have been seen...
// I don't know why... need a stack dump...
// For now just give it an extra 2 minutes. If it doesn't start in that time,
// it's likely (on reports so far) that a restart will fix it.
// And we have to get a build out because ALL plugins are now failing to load,
// including the absolutely essential (for most nodes) JSTUN and UPnP.
WrapperManager.signalStarting((int) MINUTES.toMillis(2));
FetchContext ctx = clientCore.makeClient((short)0, true, false).getFetchContext();
ctx.allowSplitfiles = false;
ctx.dontEnterImplicitArchives = true;
ctx.maxArchiveRestarts = 0;
ctx.maxMetadataSize = 256;
ctx.maxNonSplitfileRetries = 10;
ctx.maxOutputLength = 4096;
ctx.maxRecursionLevel = 2;
ctx.maxTempLength = 4096;
this.arkFetcherContext = ctx;
registerNodeToNodeMessageListener(N2N_MESSAGE_TYPE_FPROXY, fproxyN2NMListener);
registerNodeToNodeMessageListener(Node.N2N_MESSAGE_TYPE_DIFFNODEREF, diffNoderefListener);
// FIXME this is a hack
// toadlet server should start after all initialized
// see NodeClientCore line 437
if (toadlets.isEnabled()) {
toadlets.finishStart();
toadlets.createFproxy();
toadlets.removeStartupToadlet();
}
Logger.normal(this, "Node constructor completed");
System.out.println("Node constructor completed");
new BandwidthManager(this).start();
}
private void peersOffersFrefFilesConfiguration(SubConfig nodeConfig, int configOptionSortOrder) {
final Node node = this;
nodeConfig.register("peersOffersDismissed", false, configOptionSortOrder, true, true,
"Node.peersOffersDismissed", "Node.peersOffersDismissedLong", new BooleanCallback() {
@Override
public Boolean get() {
return peersOffersDismissed;
}
@Override
public void set(Boolean val) {
if (val) {
for (UserAlert alert : clientCore.alerts.getAlerts())
if (alert instanceof PeersOffersUserAlert)
clientCore.alerts.unregister(alert);
} else
PeersOffersUserAlert.createAlert(node);
peersOffersDismissed = val;
}
});
peersOffersDismissed = nodeConfig.getBoolean("peersOffersDismissed");
}
private boolean checkPeersOffersFrefFiles() {
File[] files = runDir.file("peers-offers").listFiles();
if (files != null && files.length > 0) {
for (File file : files) {
if (file.isFile()) {
String filename = file.getName();
if (filename.endsWith(".fref"))
return true;
}
}
}
return false;
}
/** Delete files from old BDB-index datastore. */
private void deleteOldBDBIndexStoreFiles() {
File dbDir = storeDir.file("database-"+getDarknetPortNumber());
FileUtil.removeAll(dbDir);
File dir = storeDir.dir();
File[] list = dir.listFiles();
for(File f : list) {
String name = f.getName();
if(f.isFile() &&
name.toLowerCase().matches("((chk)|(ssk)|(pubkey))-[0-9]*\\.((store)|(cache))(\\.((keys)|(lru)))?")) {
System.out.println("Deleting old datastore file \""+f+"\"");
try {
FileUtil.secureDelete(f);
} catch (IOException e) {
System.err.println("Failed to delete old datastore file \""+f+"\": "+e);
e.printStackTrace();
}
}
}
}
private void fixCertsFiles() {
// Hack to update certificates file to fix update.cmd
// startssl.pem: Might be useful for old versions of update.sh too?
File certs = new File(PluginDownLoaderOfficialHTTPS.certfileOld);
fixCertsFile(certs);
if(FileUtil.detectedOS.isWindows) {
// updater\startssl.pem: Needed for Windows update.cmd.
certs = new File("updater", PluginDownLoaderOfficialHTTPS.certfileOld);
fixCertsFile(certs);
}
}
private void fixCertsFile(File certs) {
long oldLength = certs.exists() ? certs.length() : -1;
try {
File tmpFile = File.createTempFile(PluginDownLoaderOfficialHTTPS.certfileOld, ".tmp", new File("."));
PluginDownLoaderOfficialHTTPS.writeCertsTo(tmpFile);
if(FileUtil.renameTo(tmpFile, certs)) {
long newLength = certs.length();
if(newLength != oldLength)
System.err.println("Updated "+certs+" so that update scripts will work");
} else {
if(certs.length() != tmpFile.length()) {
System.err.println("Cannot update "+certs+" : last-resort update scripts (in particular update.cmd on Windows) may not work");
File manual = new File(PluginDownLoaderOfficialHTTPS.certfileOld+".new");
manual.delete();
if(tmpFile.renameTo(manual))
System.err.println("Please delete "+certs+" and rename "+manual+" over it");
else
tmpFile.delete();
}
}
} catch (IOException e) {
}
}
/**
** Sets up a program directory using the config value defined by the given
** parameters.
*/
public ProgramDirectory setupProgramDir(SubConfig installConfig,
String cfgKey, String defaultValue, String shortdesc, String longdesc, String moveErrMsg,
SubConfig oldConfig) throws NodeInitException {
ProgramDirectory dir = new ProgramDirectory(moveErrMsg);
int sortOrder = ProgramDirectory.nextOrder();
// forceWrite=true because currently it can't be changed on the fly, also for packages
installConfig.register(cfgKey, defaultValue, sortOrder, true, true, shortdesc, longdesc, dir.getStringCallback());
String dirName = installConfig.getString(cfgKey);
try {
dir.move(dirName);
} catch (IOException e) {
throw new NodeInitException(NodeInitException.EXIT_BAD_DIR, "could not set up directory: " + longdesc);
}
return dir;
}
protected ProgramDirectory setupProgramDir(SubConfig installConfig,
String cfgKey, String defaultValue, String shortdesc, String longdesc,
SubConfig oldConfig) throws NodeInitException {
return setupProgramDir(installConfig, cfgKey, defaultValue, shortdesc, longdesc, null, oldConfig);
}
public void lateSetupDatabase(DatabaseKey databaseKey) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException {
if(clientCore.loadedDatabase()) return;
System.out.println("Starting late database initialisation");
try {
if(!clientCore.lateInitDatabase(databaseKey))
failLateInitDatabase();
} catch (NodeInitException e) {
failLateInitDatabase();
}
}
private void failLateInitDatabase() {
System.err.println("Failed late initialisation of database, closing...");
}
public void killMasterKeysFile() throws IOException {
MasterKeys.killMasterKeys(masterKeysFile);
}
private void setClientCacheAwaitingPassword() {
createPasswordUserAlert();
synchronized(this) {
clientCacheAwaitingPassword = true;
}
}
/** Called when the client layer needs the decryption password. */
void setDatabaseAwaitingPassword() {
synchronized(this) {
databaseAwaitingPassword = true;
}
}
private final UserAlert masterPasswordUserAlert = new UserAlert() {
final long creationTime = System.currentTimeMillis();
@Override
public String anchor() {
return "password";
}
@Override
public String dismissButtonText() {
return null;
}
@Override
public long getUpdatedTime() {
return creationTime;
}
@Override
public FCPMessage getFCPMessage() {
return new FeedMessage(getTitle(), getShortText(), getText(), getPriorityClass(), getUpdatedTime());
}
@Override
public HTMLNode getHTMLText() {
HTMLNode content = new HTMLNode("div");
SecurityLevelsToadlet.generatePasswordFormPage(false, clientCore.getToadletContainer(), content, false, false, false, null, null);
return content;
}
@Override
public short getPriorityClass() {
return UserAlert.ERROR;
}
@Override
public String getShortText() {
return NodeL10n.getBase().getString("SecurityLevels.enterPassword");
}
@Override
public String getText() {
return NodeL10n.getBase().getString("SecurityLevels.enterPassword");
}
@Override
public String getTitle() {
return NodeL10n.getBase().getString("SecurityLevels.enterPassword");
}
@Override
public boolean isEventNotification() {
return false;
}
@Override
public boolean isValid() {
synchronized(Node.this) {
return clientCacheAwaitingPassword || databaseAwaitingPassword;
}
}
@Override
public void isValid(boolean validity) {
// Ignore
}
@Override
public void onDismiss() {
// Ignore
}
@Override
public boolean shouldUnregisterOnDismiss() {
return false;
}
@Override
public boolean userCanDismiss() {
return false;
}
};
private void createPasswordUserAlert() {
this.clientCore.alerts.register(masterPasswordUserAlert);
}
private void initRAMClientCacheFS() {
chkClientcache = new CHKStore();
new RAMFreenetStore<CHKBlock>(chkClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys));
pubKeyClientcache = new PubkeyStore();
new RAMFreenetStore<DSAPublicKey>(pubKeyClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys));
sskClientcache = new SSKStore(getPubKey);
new RAMFreenetStore<SSKBlock>(sskClientcache, (int) Math.min(Integer.MAX_VALUE, maxClientCacheKeys));
}
private void initNoClientCacheFS() {
chkClientcache = new CHKStore();
new NullFreenetStore<CHKBlock>(chkClientcache);
pubKeyClientcache = new PubkeyStore();
new NullFreenetStore<DSAPublicKey>(pubKeyClientcache);
sskClientcache = new SSKStore(getPubKey);
new NullFreenetStore<SSKBlock>(sskClientcache);
}
private String getStoreSuffix() {
return "-" + getDarknetPortNumber();
}
private void finishInitSaltHashFS(final String suffix, NodeClientCore clientCore) {
if(clientCore.alerts == null) throw new NullPointerException();
chkDatastore.getStore().setUserAlertManager(clientCore.alerts);
chkDatacache.getStore().setUserAlertManager(clientCore.alerts);
pubKeyDatastore.getStore().setUserAlertManager(clientCore.alerts);
pubKeyDatacache.getStore().setUserAlertManager(clientCore.alerts);
sskDatastore.getStore().setUserAlertManager(clientCore.alerts);
sskDatacache.getStore().setUserAlertManager(clientCore.alerts);
}
private void initRAMFS() {
chkDatastore = new CHKStore();
new RAMFreenetStore<CHKBlock>(chkDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys));
chkDatacache = new CHKStore();
new RAMFreenetStore<CHKBlock>(chkDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys));
pubKeyDatastore = new PubkeyStore();
new RAMFreenetStore<DSAPublicKey>(pubKeyDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys));
pubKeyDatacache = new PubkeyStore();
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
new RAMFreenetStore<DSAPublicKey>(pubKeyDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys));
sskDatastore = new SSKStore(getPubKey);
new RAMFreenetStore<SSKBlock>(sskDatastore, (int) Math.min(Integer.MAX_VALUE, maxStoreKeys));
sskDatacache = new SSKStore(getPubKey);
new RAMFreenetStore<SSKBlock>(sskDatacache, (int) Math.min(Integer.MAX_VALUE, maxCacheKeys));
}
private long cachingFreenetStoreMaxSize;
private long cachingFreenetStorePeriod;
private CachingFreenetStoreTracker cachingFreenetStoreTracker;
private void initSaltHashFS(final String suffix, boolean dontResizeOnStart, byte[] masterKey) throws NodeInitException {
try {
final CHKStore chkDatastore = new CHKStore();
final FreenetStore<CHKBlock> chkDataFS = makeStore("CHK", true, chkDatastore, dontResizeOnStart, masterKey);
final CHKStore chkDatacache = new CHKStore();
final FreenetStore<CHKBlock> chkCacheFS = makeStore("CHK", false, chkDatacache, dontResizeOnStart, masterKey);
((SaltedHashFreenetStore<CHKBlock>) chkCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<CHKBlock>) chkDataFS.getUnderlyingStore()));
final PubkeyStore pubKeyDatastore = new PubkeyStore();
final FreenetStore<DSAPublicKey> pubkeyDataFS = makeStore("PUBKEY", true, pubKeyDatastore, dontResizeOnStart, masterKey);
final PubkeyStore pubKeyDatacache = new PubkeyStore();
final FreenetStore<DSAPublicKey> pubkeyCacheFS = makeStore("PUBKEY", false, pubKeyDatacache, dontResizeOnStart, masterKey);
((SaltedHashFreenetStore<DSAPublicKey>) pubkeyCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<DSAPublicKey>) pubkeyDataFS.getUnderlyingStore()));
final SSKStore sskDatastore = new SSKStore(getPubKey);
final FreenetStore<SSKBlock> sskDataFS = makeStore("SSK", true, sskDatastore, dontResizeOnStart, masterKey);
final SSKStore sskDatacache = new SSKStore(getPubKey);
final FreenetStore<SSKBlock> sskCacheFS = makeStore("SSK", false, sskDatacache, dontResizeOnStart, masterKey);
((SaltedHashFreenetStore<SSKBlock>) sskCacheFS.getUnderlyingStore()).setAltStore(((SaltedHashFreenetStore<SSKBlock>) sskDataFS.getUnderlyingStore()));
boolean delay =
chkDataFS.start(ticker, false) |
chkCacheFS.start(ticker, false) |
pubkeyDataFS.start(ticker, false) |
pubkeyCacheFS.start(ticker, false) |
sskDataFS.start(ticker, false) |
sskCacheFS.start(ticker, false);
if(delay) {
System.err.println("Delayed init of datastore");
initRAMFS();
final Runnable migrate = new MigrateOldStoreData(false);
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
System.err.println("Starting delayed init of datastore");
try {
chkDataFS.start(ticker, true);
chkCacheFS.start(ticker, true);
pubkeyDataFS.start(ticker, true);
pubkeyCacheFS.start(ticker, true);
sskDataFS.start(ticker, true);
sskCacheFS.start(ticker, true);
} catch (IOException e) {
Logger.error(this, "Failed to start datastore: "+e, e);
System.err.println("Failed to start datastore: "+e);
e.printStackTrace();
return;
}
Node.this.chkDatastore = chkDatastore;
Node.this.chkDatacache = chkDatacache;
Node.this.pubKeyDatastore = pubKeyDatastore;
Node.this.pubKeyDatacache = pubKeyDatacache;
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
Node.this.sskDatastore = sskDatastore;
Node.this.sskDatacache = sskDatacache;
finishInitSaltHashFS(suffix, clientCore);
System.err.println("Finishing delayed init of datastore");
migrate.run();
}
}, "Start store", 0, true, false); // Use Ticker to guarantee that this runs *after* constructors have completed.
} else {
Node.this.chkDatastore = chkDatastore;
Node.this.chkDatacache = chkDatacache;
Node.this.pubKeyDatastore = pubKeyDatastore;
Node.this.pubKeyDatacache = pubKeyDatacache;
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
Node.this.sskDatastore = sskDatastore;
Node.this.sskDatacache = sskDatacache;
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
Node.this.chkDatastore = chkDatastore;
Node.this.chkDatacache = chkDatacache;
Node.this.pubKeyDatastore = pubKeyDatastore;
Node.this.pubKeyDatacache = pubKeyDatacache;
getPubKey.setDataStore(pubKeyDatastore, pubKeyDatacache);
Node.this.sskDatastore = sskDatastore;
Node.this.sskDatacache = sskDatacache;
finishInitSaltHashFS(suffix, clientCore);
}
}, "Start store", 0, true, false);
}
} catch (IOException e) {
System.err.println("Could not open store: " + e);
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage());
}
}
private void initSaltHashClientCacheFS(final String suffix, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws NodeInitException {
try {
final CHKStore chkClientcache = new CHKStore();
final FreenetStore<CHKBlock> chkDataFS = makeClientcache("CHK", true, chkClientcache, dontResizeOnStart, clientCacheMasterKey);
final PubkeyStore pubKeyClientcache = new PubkeyStore();
final FreenetStore<DSAPublicKey> pubkeyDataFS = makeClientcache("PUBKEY", true, pubKeyClientcache, dontResizeOnStart, clientCacheMasterKey);
final SSKStore sskClientcache = new SSKStore(getPubKey);
final FreenetStore<SSKBlock> sskDataFS = makeClientcache("SSK", true, sskClientcache, dontResizeOnStart, clientCacheMasterKey);
boolean delay =
chkDataFS.start(ticker, false) |
pubkeyDataFS.start(ticker, false) |
sskDataFS.start(ticker, false);
if(delay) {
System.err.println("Delayed init of client-cache");
initRAMClientCacheFS();
final Runnable migrate = new MigrateOldStoreData(true);
getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
System.err.println("Starting delayed init of client-cache");
try {
chkDataFS.start(ticker, true);
pubkeyDataFS.start(ticker, true);
sskDataFS.start(ticker, true);
} catch (IOException e) {
Logger.error(this, "Failed to start client-cache: "+e, e);
System.err.println("Failed to start client-cache: "+e);
e.printStackTrace();
return;
}
Node.this.chkClientcache = chkClientcache;
Node.this.pubKeyClientcache = pubKeyClientcache;
getPubKey.setLocalDataStore(pubKeyClientcache);
Node.this.sskClientcache = sskClientcache;
System.err.println("Finishing delayed init of client-cache");
migrate.run();
}
}, "Migrate store", 0, true, false);
} else {
Node.this.chkClientcache = chkClientcache;
Node.this.pubKeyClientcache = pubKeyClientcache;
getPubKey.setLocalDataStore(pubKeyClientcache);
Node.this.sskClientcache = sskClientcache;
}
} catch (IOException e) {
System.err.println("Could not open store: " + e);
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_STORE_OTHER, e.getMessage());
}
}
private <T extends StorableBlock> FreenetStore<T> makeClientcache(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws IOException {
FreenetStore<T> store = makeStore(type, "clientcache", maxClientCacheKeys, cb, dontResizeOnStart, clientCacheMasterKey);
return store;
}
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, boolean isStore, StoreCallback<T> cb, boolean dontResizeOnStart, byte[] clientCacheMasterKey) throws IOException {
String store = isStore ? "store" : "cache";
long maxKeys = isStore ? maxStoreKeys : maxCacheKeys;
return makeStore(type, store, maxKeys, cb, dontResizeOnStart, clientCacheMasterKey);
}
private <T extends StorableBlock> FreenetStore<T> makeStore(String type, String store, long maxKeys, StoreCallback<T> cb, boolean lateStart, byte[] clientCacheMasterKey) throws IOException {
Logger.normal(this, "Initializing "+type+" Data"+store);
System.out.println("Initializing "+type+" Data"+store+" (" + maxStoreKeys + " keys)");
SaltedHashFreenetStore<T> fs = SaltedHashFreenetStore.<T>construct(getStoreDir(), type+"-"+store, cb,
random, maxKeys, storeUseSlotFilters, shutdownHook, storePreallocate, storeSaltHashResizeOnStart && !lateStart, lateStart ? ticker : null, clientCacheMasterKey);
cb.setStore(fs);
if(cachingFreenetStoreMaxSize > 0)
return new CachingFreenetStore<T>(cb, fs, cachingFreenetStoreTracker);
else
return fs;
}
public void start(boolean noSwaps) throws NodeInitException {
// IMPORTANT: Read the peers only after we have finished initializing Node.
// Peer constructors are complex and can call methods on Node.
peers.tryReadPeers(nodeDir.file("peers-"+getDarknetPortNumber()).getPath(), darknetCrypto, null, false, false);
peers.updatePMUserAlert();
dispatcher.start(nodeStats); // must be before usm
dnsr.start();
peers.start(); // must be before usm
nodeStats.start();
uptime.start();
failureTable.start();
darknetCrypto.start();
if(opennet != null)
opennet.start();
ps.start(nodeStats);
ticker.start();
scheduleVersionTransition();
usm.start(ticker);
if(isUsingWrapper()) {
Logger.normal(this, "Using wrapper correctly: "+nodeStarter);
System.out.println("Using wrapper correctly: "+nodeStarter);
} else {
Logger.error(this, "NOT using wrapper (at least not correctly). Your freenet-ext.jar <http://downloads.freenetproject.org/alpha/freenet-ext.jar> and/or wrapper.conf <https://emu.freenetproject.org/svn/trunk/apps/installer/installclasspath/config/wrapper.conf> need to be updated.");
System.out.println("NOT using wrapper (at least not correctly). Your freenet-ext.jar <http://downloads.freenetproject.org/alpha/freenet-ext.jar> and/or wrapper.conf <https://emu.freenetproject.org/svn/trunk/apps/installer/installclasspath/config/wrapper.conf> need to be updated.");
}
Logger.normal(this, "Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision());
System.out.println("Freenet 0.7.5 Build #"+Version.buildNumber()+" r"+Version.cvsRevision());
Logger.normal(this, "FNP port is on "+darknetCrypto.getBindTo()+ ':' +getDarknetPortNumber());
System.out.println("FNP port is on "+darknetCrypto.getBindTo()+ ':' +getDarknetPortNumber());
// Start services
// SubConfig pluginManagerConfig = new SubConfig("pluginmanager3", config);
// pluginManager3 = new freenet.plugin_new.PluginManager(pluginManagerConfig);
ipDetector.start();
// Start sending swaps
lm.start();
// Node Updater
try{
Logger.normal(this, "Starting the node updater");
nodeUpdater.start();
}catch (Exception e) {
e.printStackTrace();
throw new NodeInitException(NodeInitException.EXIT_COULD_NOT_START_UPDATER, "Could not start Updater: "+e);
}
/* TODO: Make sure that this is called BEFORE any instances of HTTPFilter are created.
* HTTPFilter uses checkForGCJCharConversionBug() which returns the value of the static
* variable jvmHasGCJCharConversionBug - and this is initialized in the following function.
* If this is not possible then create a separate function to check for the GCJ bug and
* call this function earlier.
*/
checkForEvilJVMBugs();
if(!NativeThread.HAS_ENOUGH_NICE_LEVELS)
clientCore.alerts.register(new NotEnoughNiceLevelsUserAlert());
this.clientCore.start(config);
tracker.startDeadUIDChecker();
// After everything has been created, write the config file back to disk.
if(config instanceof FreenetFilePersistentConfig) {
FreenetFilePersistentConfig cfg = (FreenetFilePersistentConfig) config;
cfg.finishedInit(this.ticker);
cfg.setHasNodeStarted();
}
config.store();
// Process any data in the extra peer data directory
peers.readExtraPeerData();
Logger.normal(this, "Started node");
hasStarted = true;
}
private void scheduleVersionTransition() {
long now = System.currentTimeMillis();
long transition = Version.transitionTime();
if(now < transition)
ticker.queueTimedJob(new Runnable() {
@Override
public void run() {
freenet.support.Logger.OSThread.logPID(this);
for(PeerNode pn: peers.myPeers()) {
pn.updateVersionRoutablity();
}
}
}, transition - now);
}
private static boolean jvmHasGCJCharConversionBug=false;
private void checkForEvilJVMBugs() {
// Now check whether we are likely to get the EvilJVMBug.
// If we are running a Sun/Oracle or Blackdown JVM, on Linux, and LD_ASSUME_KERNEL is not set, then we are.
String jvmVendor = System.getProperty("java.vm.vendor");
String jvmSpecVendor = System.getProperty("java.specification.vendor","");
String javaVersion = System.getProperty("java.version");
String jvmName = System.getProperty("java.vm.name");
String osName = System.getProperty("os.name");
String osVersion = System.getProperty("os.version");
boolean isOpenJDK = false;
//boolean isOracle = false;
if(logMINOR) Logger.minor(this, "JVM vendor: "+jvmVendor+", JVM name: "+jvmName+", JVM version: "+javaVersion+", OS name: "+osName+", OS version: "+osVersion);
if(jvmName.startsWith("OpenJDK ")) {
isOpenJDK = true;
}
//Add some checks for "Oracle" to futureproof against them renaming from "Sun".
//Should have no effect because if a user has downloaded a new enough file for Oracle to have changed the name these bugs shouldn't apply.
//Still, one never knows and this code might be extended to cover future bugs.
if((!isOpenJDK) && (jvmVendor.startsWith("Sun ") || jvmVendor.startsWith("Oracle ")) || (jvmVendor.startsWith("The FreeBSD Foundation") && (jvmSpecVendor.startsWith("Sun ") || jvmSpecVendor.startsWith("Oracle "))) || (jvmVendor.startsWith("Apple "))) {
//isOracle = true;
// Sun/Oracle bugs
// Spurious OOMs
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4855795
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=2138757
// http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=2138759
// Fixed in 1.5.0_10 and 1.4.2_13
boolean is150 = javaVersion.startsWith("1.5.0_");
boolean is160 = javaVersion.startsWith("1.6.0_");
if(is150 || is160) {
String[] split = javaVersion.split("_");
String secondPart = split[1];
if(secondPart.indexOf("-") != -1) {
split = secondPart.split("-");
secondPart = split[0];
}
int subver = Integer.parseInt(secondPart);
Logger.minor(this, "JVM version: "+javaVersion+" subver: "+subver+" from "+secondPart);
}
} else if (jvmVendor.startsWith("Apple ") || jvmVendor.startsWith("\"Apple ")) {
//Note that Sun/Oracle does not produce VMs for the Macintosh operating system, dont ask the user to find one...
} else if(!isOpenJDK) {
if(jvmVendor.startsWith("Free Software Foundation")) {
// GCJ/GIJ.
try {
javaVersion = System.getProperty("java.version").split(" ")[0].replaceAll("[.]","");
int jvmVersionInt = Integer.parseInt(javaVersion);
if(jvmVersionInt <= 422 && jvmVersionInt >= 100) // make sure that no bogus values cause true
jvmHasGCJCharConversionBug=true;
}
catch(Throwable t) {
Logger.error(this, "GCJ version check is broken!", t);
}
clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingGCJTitle"), l10n("usingGCJ"), l10n("usingGCJTitle"), UserAlert.WARNING));
}
}
if(!isUsingWrapper() && !skipWrapperWarning) {
clientCore.alerts.register(new SimpleUserAlert(true, l10n("notUsingWrapperTitle"), l10n("notUsingWrapper"), l10n("notUsingWrapperShort"), UserAlert.WARNING));
}
// Unfortunately debian's version of OpenJDK appears to have segfaulting issues.
// Which presumably are exploitable.
// So we can't recommend people switch just yet. :(
// if(isOracle && Rijndael.AesCtrProvider == null) {
// if(!(FileUtil.detectedOS == FileUtil.OperatingSystem.Windows || FileUtil.detectedOS == FileUtil.OperatingSystem.MacOS))
// clientCore.alerts.register(new SimpleUserAlert(true, l10n("usingOracleTitle"), l10n("usingOracle"), l10n("usingOracleTitle"), UserAlert.WARNING));
// }
}
public static boolean checkForGCJCharConversionBug() {
return jvmHasGCJCharConversionBug; // should be initialized on early startup
}
private String l10n(String key) {
return NodeL10n.getBase().getString("Node."+key);
}
private String l10n(String key, String pattern, String value) {
return NodeL10n.getBase().getString("Node."+key, pattern, value);
}
private String l10n(String key, String[] pattern, String[] value) {
return NodeL10n.getBase().getString("Node."+key, pattern, value);
}
/**
* Export volatile data about the node as a SimpleFieldSet
*/
public SimpleFieldSet exportVolatileFieldSet() {
return nodeStats.exportVolatileFieldSet();
}
/**
* Do a routed ping of another node on the network by its location.
* @param loc2 The location of the other node to ping. It must match
* exactly.
* @param pubKeyHash The hash of the pubkey of the target node. We match
* by location; this is just a shortcut if we get close.
* @return The number of hops it took to find the node, if it was found.
* Otherwise -1.
*/
public int routedPing(double loc2, byte[] pubKeyHash) {
long uid = random.nextLong();
int initialX = random.nextInt();
Message m = DMT.createFNPRoutedPing(uid, loc2, maxHTL, initialX, pubKeyHash);
Logger.normal(this, "Message: "+m);
dispatcher.handleRouted(m, null);
// FIXME: might be rejected
MessageFilter mf1 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedPong).setTimeout(5000);
try {
//MessageFilter mf2 = MessageFilter.create().setField(DMT.UID, uid).setType(DMT.FNPRoutedRejected).setTimeout(5000);
// Ignore Rejected - let it be retried on other peers
m = usm.waitFor(mf1/*.or(mf2)*/, null);
} catch (DisconnectedException e) {
Logger.normal(this, "Disconnected in waiting for pong");
return -1;
}
if(m == null) return -1;
if(m.getSpec() == DMT.FNPRoutedRejected) return -1;
return m.getInt(DMT.COUNTER) - initialX;
}
/**
* Look for a block in the datastore, as part of a request.
* @param key The key to fetch.
* @param uid The UID of the request (for logging only).
* @param promoteCache Whether to promote the key if found.
* @param canReadClientCache If the request is local, we can read the client cache.
* @param canWriteClientCache If the request is local, and the client hasn't turned off
* writing to the client cache, we can write to the client cache.
* @param canWriteDatastore If the request HTL is too high, including if it is local, we
* cannot write to the datastore.
* @return A KeyBlock for the key requested or null.
*/
private KeyBlock makeRequestLocal(Key key, long uid, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean offersOnly) {
KeyBlock kb = null;
if (key instanceof NodeCHK) {
kb = fetch(key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, null);
} else if (key instanceof NodeSSK) {
NodeSSK sskKey = (NodeSSK) key;
DSAPublicKey pubKey = sskKey.getPubKey();
if (pubKey == null) {
pubKey = getPubKey.getKey(sskKey.getPubKeyHash(), canReadClientCache, offersOnly, null);
if (logMINOR)
Logger.minor(this, "Fetched pubkey: " + pubKey);
try {
sskKey.setPubKey(pubKey);
} catch (SSKVerifyException e) {
Logger.error(this, "Error setting pubkey: " + e, e);
}
}
if (pubKey != null) {
if (logMINOR)
Logger.minor(this, "Got pubkey: " + pubKey);
kb = fetch(sskKey, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null);
} else {
if (logMINOR)
Logger.minor(this, "Not found because no pubkey: " + uid);
}
} else
throw new IllegalStateException("Unknown key type: " + key.getClass());
if (kb != null) {
// Probably somebody waiting for it. Trip it.
if (clientCore != null && clientCore.requestStarters != null) {
if (kb instanceof CHKBlock) {
clientCore.requestStarters.chkFetchSchedulerBulk.tripPendingKey(kb);
clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(kb);
} else {
clientCore.requestStarters.sskFetchSchedulerBulk.tripPendingKey(kb);
clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(kb);
}
}
failureTable.onFound(kb);
return kb;
}
return null;
}
/**
* Check the datastore, then if the key is not in the store,
* check whether another node is requesting the same key at
* the same HTL, and if all else fails, create a new
* RequestSender for the key/htl.
* @param closestLocation The closest location to the key so far.
* @param localOnly If true, only check the datastore.
* @return A KeyBlock if the data is in the store, otherwise
* a RequestSender, unless the HTL is 0, in which case NULL.
* RequestSender.
*/
public Object makeRequestSender(Key key, short htl, long uid, RequestTag tag, PeerNode source, boolean localOnly, boolean ignoreStore, boolean offersOnly, boolean canReadClientCache, boolean canWriteClientCache, boolean realTimeFlag) {
boolean canWriteDatastore = canWriteDatastoreRequest(htl);
if(logMINOR) Logger.minor(this, "makeRequestSender("+key+ ',' +htl+ ',' +uid+ ',' +source+") on "+getDarknetPortNumber());
// In store?
if(!ignoreStore) {
KeyBlock kb = makeRequestLocal(key, uid, canReadClientCache, canWriteClientCache, canWriteDatastore, offersOnly);
if (kb != null)
return kb;
}
if(localOnly) return null;
if(logMINOR) Logger.minor(this, "Not in store locally");
// Transfer coalescing - match key only as HTL irrelevant
RequestSender sender = key instanceof NodeCHK ?
tracker.getTransferringRequestSenderByKey((NodeCHK)key, realTimeFlag) : null;
if(sender != null) {
if(logMINOR) Logger.minor(this, "Data already being transferred: "+sender);
sender.setTransferCoalesced();
tag.setSender(sender, true);
return sender;
}
// HTL == 0 => Don't search further
if(htl == 0) {
if(logMINOR) Logger.minor(this, "No HTL");
return null;
}
sender = new RequestSender(key, null, htl, uid, tag, this, source, offersOnly, canWriteClientCache, canWriteDatastore, realTimeFlag);
tag.setSender(sender, false);
sender.start();
if(logMINOR) Logger.minor(this, "Created new sender: "+sender);
return sender;
}
/** Can we write to the datastore for a given request?
* We do not write to the datastore until 2 hops below maximum. This is an average of 4
* hops from the originator. Thus, data returned from local requests is never cached,
* finally solving The Register's attack, Bloom filter sharing doesn't give away your local
* requests and inserts, and *anything starting at high HTL* is not cached, including stuff
* from other nodes which hasn't been decremented far enough yet, so it's not ONLY local
* requests that don't get cached. */
boolean canWriteDatastoreRequest(short htl) {
return htl <= (maxHTL - 2);
}
/** Can we write to the datastore for a given insert?
* We do not write to the datastore until 3 hops below maximum. This is an average of 5
* hops from the originator. Thus, data sent by local inserts is never cached,
* finally solving The Register's attack, Bloom filter sharing doesn't give away your local
* requests and inserts, and *anything starting at high HTL* is not cached, including stuff
* from other nodes which hasn't been decremented far enough yet, so it's not ONLY local
* inserts that don't get cached. */
boolean canWriteDatastoreInsert(short htl) {
return htl <= (maxHTL - 3);
}
/**
* Fetch a block from the datastore.
* @param key
* @param canReadClientCache
* @param canWriteClientCache
* @param canWriteDatastore
* @param forULPR
* @param mustBeMarkedAsPostCachingChanges If true, the key must have the
* ENTRY_NEW_BLOCK flag (if saltedhash), indicating that it a) has been added
* since the caching changes in 1224 (since we didn't delete the stores), and b)
* that it wasn't added due to low network security caching everything, unless we
* are currently in low network security mode. Only applies to main store.
*/
public KeyBlock fetch(Key key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) {
if(key instanceof NodeSSK)
return fetch((NodeSSK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta);
else if(key instanceof NodeCHK)
return fetch((NodeCHK)key, false, canReadClientCache, canWriteClientCache, canWriteDatastore, forULPR, meta);
else throw new IllegalArgumentException();
}
public SSKBlock fetch(NodeSSK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) {
double loc=key.toNormalizedDouble();
double dist=Location.distance(lm.getLocation(), loc);
if(canReadClientCache) {
try {
SSKBlock block = sskClientcache.fetch(key, dontPromote || !canWriteClientCache, canReadClientCache, forULPR, false, meta);
if(block != null) {
nodeStats.avgClientCacheSSKSuccess.report(loc);
if (dist > nodeStats.furthestClientCacheSSKSuccess)
nodeStats.furthestClientCacheSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in client-cache");
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from client cache: "+e, e);
}
}
if(forULPR || useSlashdotCache || canReadClientCache) {
try {
SSKBlock block = sskSlashdotcache.fetch(key, dontPromote, canReadClientCache, forULPR, false, meta);
if(block != null) {
nodeStats.avgSlashdotCacheSSKSuccess.report(loc);
if (dist > nodeStats.furthestSlashdotCacheSSKSuccess)
nodeStats.furthestSlashdotCacheSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in slashdot-cache");
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e);
}
}
boolean ignoreOldBlocks = !writeLocalToDatastore;
if(canReadClientCache) ignoreOldBlocks = false;
if(logMINOR) dumpStoreHits();
try {
nodeStats.avgRequestLocation.report(loc);
SSKBlock block = sskDatastore.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
if(block == null) {
SSKStore store = oldSSK;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
}
if(block != null) {
nodeStats.avgStoreSSKSuccess.report(loc);
if (dist > nodeStats.furthestStoreSSKSuccess)
nodeStats.furthestStoreSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in store");
return block;
}
block=sskDatacache.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
if(block == null) {
SSKStore store = oldSSKCache;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, canReadClientCache, forULPR, ignoreOldBlocks, meta);
}
if (block != null) {
nodeStats.avgCacheSSKSuccess.report(loc);
if (dist > nodeStats.furthestCacheSSKSuccess)
nodeStats.furthestCacheSSKSuccess=dist;
if(logDEBUG) Logger.debug(this, "Found key "+key+" in cache");
}
return block;
} catch (IOException e) {
Logger.error(this, "Cannot fetch data: "+e, e);
return null;
}
}
public CHKBlock fetch(NodeCHK key, boolean dontPromote, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR, BlockMetadata meta) {
double loc=key.toNormalizedDouble();
double dist=Location.distance(lm.getLocation(), loc);
if(canReadClientCache) {
try {
CHKBlock block = chkClientcache.fetch(key, dontPromote || !canWriteClientCache, false, meta);
if(block != null) {
nodeStats.avgClientCacheCHKSuccess.report(loc);
if (dist > nodeStats.furthestClientCacheCHKSuccess)
nodeStats.furthestClientCacheCHKSuccess=dist;
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from client cache: "+e, e);
}
}
if(forULPR || useSlashdotCache || canReadClientCache) {
try {
CHKBlock block = chkSlashdotcache.fetch(key, dontPromote, false, meta);
if(block != null) {
nodeStats.avgSlashdotCacheCHKSucess.report(loc);
if (dist > nodeStats.furthestSlashdotCacheCHKSuccess)
nodeStats.furthestSlashdotCacheCHKSuccess=dist;
return block;
}
} catch (IOException e) {
Logger.error(this, "Could not read from slashdot/ULPR cache: "+e, e);
}
}
boolean ignoreOldBlocks = !writeLocalToDatastore;
if(canReadClientCache) ignoreOldBlocks = false;
if(logMINOR) dumpStoreHits();
try {
nodeStats.avgRequestLocation.report(loc);
CHKBlock block = chkDatastore.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
if(block == null) {
CHKStore store = oldCHK;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
}
if (block != null) {
nodeStats.avgStoreCHKSuccess.report(loc);
if (dist > nodeStats.furthestStoreCHKSuccess)
nodeStats.furthestStoreCHKSuccess=dist;
return block;
}
block=chkDatacache.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
if(block == null) {
CHKStore store = oldCHKCache;
if(store != null)
block = store.fetch(key, dontPromote || !canWriteDatastore, ignoreOldBlocks, meta);
}
if (block != null) {
nodeStats.avgCacheCHKSuccess.report(loc);
if (dist > nodeStats.furthestCacheCHKSuccess)
nodeStats.furthestCacheCHKSuccess=dist;
}
return block;
} catch (IOException e) {
Logger.error(this, "Cannot fetch data: "+e, e);
return null;
}
}
CHKStore getChkDatacache() {
return chkDatacache;
}
CHKStore getChkDatastore() {
return chkDatastore;
}
SSKStore getSskDatacache() {
return sskDatacache;
}
SSKStore getSskDatastore() {
return sskDatastore;
}
CHKStore getChkSlashdotCache() {
return chkSlashdotcache;
}
CHKStore getChkClientCache() {
return chkClientcache;
}
SSKStore getSskSlashdotCache() {
return sskSlashdotcache;
}
SSKStore getSskClientCache() {
return sskClientcache;
}
/**
* This method returns all statistics info for our data store stats table
*
* @return map that has an entry for each data store instance type and corresponding stats
*/
public Map<DataStoreInstanceType, DataStoreStats> getDataStoreStats() {
Map<DataStoreInstanceType, DataStoreStats> map = new LinkedHashMap<DataStoreInstanceType, DataStoreStats>();
map.put(new DataStoreInstanceType(CHK, STORE), new StoreCallbackStats(chkDatastore, nodeStats.chkStoreStats()));
map.put(new DataStoreInstanceType(CHK, CACHE), new StoreCallbackStats(chkDatacache, nodeStats.chkCacheStats()));
map.put(new DataStoreInstanceType(CHK, SLASHDOT), new StoreCallbackStats(chkSlashdotcache,nodeStats.chkSlashDotCacheStats()));
map.put(new DataStoreInstanceType(CHK, CLIENT), new StoreCallbackStats(chkClientcache, nodeStats.chkClientCacheStats()));
map.put(new DataStoreInstanceType(SSK, STORE), new StoreCallbackStats(sskDatastore, nodeStats.sskStoreStats()));
map.put(new DataStoreInstanceType(SSK, CACHE), new StoreCallbackStats(sskDatacache, nodeStats.sskCacheStats()));
map.put(new DataStoreInstanceType(SSK, SLASHDOT), new StoreCallbackStats(sskSlashdotcache, nodeStats.sskSlashDotCacheStats()));
map.put(new DataStoreInstanceType(SSK, CLIENT), new StoreCallbackStats(sskClientcache, nodeStats.sskClientCacheStats()));
map.put(new DataStoreInstanceType(PUB_KEY, STORE), new StoreCallbackStats(pubKeyDatastore, new NotAvailNodeStoreStats()));
map.put(new DataStoreInstanceType(PUB_KEY, CACHE), new StoreCallbackStats(pubKeyDatacache, new NotAvailNodeStoreStats()));
map.put(new DataStoreInstanceType(PUB_KEY, SLASHDOT), new StoreCallbackStats(pubKeySlashdotcache, new NotAvailNodeStoreStats()));
map.put(new DataStoreInstanceType(PUB_KEY, CLIENT), new StoreCallbackStats(pubKeyClientcache, new NotAvailNodeStoreStats()));
return map;
}
public long getMaxTotalKeys() {
return maxTotalKeys;
}
long timeLastDumpedHits;
public void dumpStoreHits() {
long now = System.currentTimeMillis();
if(now - timeLastDumpedHits > 5000) {
timeLastDumpedHits = now;
} else return;
Logger.minor(this, "Distribution of hits and misses over stores:\n"+
"CHK Datastore: "+chkDatastore.hits()+ '/' +(chkDatastore.hits()+chkDatastore.misses())+ '/' +chkDatastore.keyCount()+
"\nCHK Datacache: "+chkDatacache.hits()+ '/' +(chkDatacache.hits()+chkDatacache.misses())+ '/' +chkDatacache.keyCount()+
"\nSSK Datastore: "+sskDatastore.hits()+ '/' +(sskDatastore.hits()+sskDatastore.misses())+ '/' +sskDatastore.keyCount()+
"\nSSK Datacache: "+sskDatacache.hits()+ '/' +(sskDatacache.hits()+sskDatacache.misses())+ '/' +sskDatacache.keyCount());
}
public void storeShallow(CHKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) {
store(block, false, canWriteClientCache, canWriteDatastore, forULPR);
}
/**
* Store a datum.
* @param block
* a KeyBlock
* @param deep If true, insert to the store as well as the cache. Do not set
* this to true unless the store results from an insert, and this node is the
* closest node to the target; see the description of chkDatastore.
*/
public void store(KeyBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws KeyCollisionException {
if(block instanceof CHKBlock)
store((CHKBlock)block, deep, canWriteClientCache, canWriteDatastore, forULPR);
else if(block instanceof SSKBlock)
store((SSKBlock)block, deep, false, canWriteClientCache, canWriteDatastore, forULPR);
else throw new IllegalArgumentException("Unknown keytype ");
}
private void store(CHKBlock block, boolean deep, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) {
try {
double loc = block.getKey().toNormalizedDouble();
if (canWriteClientCache) {
chkClientcache.put(block, false);
nodeStats.avgClientCacheCHKLocation.report(loc);
}
if ((forULPR || useSlashdotCache) && !(canWriteDatastore || writeLocalToDatastore)) {
chkSlashdotcache.put(block, false);
nodeStats.avgSlashdotCacheCHKLocation.report(loc);
}
if (canWriteDatastore || writeLocalToDatastore) {
if (deep) {
chkDatastore.put(block, !canWriteDatastore);
nodeStats.avgStoreCHKLocation.report(loc);
}
chkDatacache.put(block, !canWriteDatastore);
nodeStats.avgCacheCHKLocation.report(loc);
}
if (canWriteDatastore || forULPR || useSlashdotCache)
failureTable.onFound(block);
} catch (IOException e) {
Logger.error(this, "Cannot store data: "+e, e);
} catch (Throwable t) {
System.err.println(t);
t.printStackTrace();
Logger.error(this, "Caught "+t+" storing data", t);
}
if(clientCore != null && clientCore.requestStarters != null) {
clientCore.requestStarters.chkFetchSchedulerBulk.tripPendingKey(block);
clientCore.requestStarters.chkFetchSchedulerRT.tripPendingKey(block);
}
}
/** Store the block if this is a sink. Call for inserts. */
public void storeInsert(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyCollisionException {
store(block, deep, overwrite, canWriteClientCache, canWriteDatastore, false);
}
/** Store only to the cache, and not the store. Called by requests,
* as only inserts cause data to be added to the store. */
public void storeShallow(SSKBlock block, boolean canWriteClientCache, boolean canWriteDatastore, boolean fromULPR) throws KeyCollisionException {
store(block, false, canWriteClientCache, canWriteDatastore, fromULPR);
}
public void store(SSKBlock block, boolean deep, boolean overwrite, boolean canWriteClientCache, boolean canWriteDatastore, boolean forULPR) throws KeyCollisionException {
try {
// Store the pubkey before storing the data, otherwise we can get a race condition and
// end up deleting the SSK data.
double loc = block.getKey().toNormalizedDouble();
getPubKey.cacheKey((block.getKey()).getPubKeyHash(), (block.getKey()).getPubKey(), deep, canWriteClientCache, canWriteDatastore, forULPR || useSlashdotCache, writeLocalToDatastore);
if(canWriteClientCache) {
sskClientcache.put(block, overwrite, false);
nodeStats.avgClientCacheSSKLocation.report(loc);
}
if((forULPR || useSlashdotCache) && !(canWriteDatastore || writeLocalToDatastore)) {
sskSlashdotcache.put(block, overwrite, false);
nodeStats.avgSlashdotCacheSSKLocation.report(loc);
}
if(canWriteDatastore || writeLocalToDatastore) {
if(deep) {
sskDatastore.put(block, overwrite, !canWriteDatastore);
nodeStats.avgStoreSSKLocation.report(loc);
}
sskDatacache.put(block, overwrite, !canWriteDatastore);
nodeStats.avgCacheSSKLocation.report(loc);
}
if(canWriteDatastore || forULPR || useSlashdotCache)
failureTable.onFound(block);
} catch (IOException e) {
Logger.error(this, "Cannot store data: "+e, e);
} catch (KeyCollisionException e) {
throw e;
} catch (Throwable t) {
System.err.println(t);
t.printStackTrace();
Logger.error(this, "Caught "+t+" storing data", t);
}
if(clientCore != null && clientCore.requestStarters != null) {
clientCore.requestStarters.sskFetchSchedulerBulk.tripPendingKey(block);
clientCore.requestStarters.sskFetchSchedulerRT.tripPendingKey(block);
}
}
final boolean decrementAtMax;
final boolean decrementAtMin;
/**
* Decrement the HTL according to the policy of the given
* NodePeer if it is non-null, or do something else if it is
* null.
*/
public short decrementHTL(PeerNode source, short htl) {
if(source != null)
return source.decrementHTL(htl);
// Otherwise...
if(htl >= maxHTL) htl = maxHTL;
if(htl <= 0) {
return 0;
}
if(htl == maxHTL) {
if(decrementAtMax || disableProbabilisticHTLs) htl--;
return htl;
}
if(htl == 1) {
if(decrementAtMin || disableProbabilisticHTLs) htl--;
return htl;
}
return --htl;
}
/**
* Fetch or create an CHKInsertSender for a given key/htl.
* @param key The key to be inserted.
* @param htl The current HTL. We can't coalesce inserts across
* HTL's.
* @param uid The UID of the caller's request chain, or a new
* one. This is obviously not used if there is already an
* CHKInsertSender running.
* @param source The node that sent the InsertRequest, or null
* if it originated locally.
* @param ignoreLowBackoff
* @param preferInsert
*/
public CHKInsertSender makeInsertSender(NodeCHK key, short htl, long uid, InsertTag tag, PeerNode source,
byte[] headers, PartiallyReceivedBlock prb, boolean fromStore, boolean canWriteClientCache, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) {
if(logMINOR) Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore);
CHKInsertSender is = null;
is = new CHKInsertSender(key, uid, tag, headers, htl, source, this, prb, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff,realTimeFlag);
is.start();
// CHKInsertSender adds itself to insertSenders
return is;
}
/**
* Fetch or create an SSKInsertSender for a given key/htl.
* @param key The key to be inserted.
* @param htl The current HTL. We can't coalesce inserts across
* HTL's.
* @param uid The UID of the caller's request chain, or a new
* one. This is obviously not used if there is already an
* SSKInsertSender running.
* @param source The node that sent the InsertRequest, or null
* if it originated locally.
* @param ignoreLowBackoff
* @param preferInsert
*/
public SSKInsertSender makeInsertSender(SSKBlock block, short htl, long uid, InsertTag tag, PeerNode source,
boolean fromStore, boolean canWriteClientCache, boolean canWriteDatastore, boolean forkOnCacheable, boolean preferInsert, boolean ignoreLowBackoff, boolean realTimeFlag) {
NodeSSK key = block.getKey();
if(key.getPubKey() == null) {
throw new IllegalArgumentException("No pub key when inserting");
}
getPubKey.cacheKey(key.getPubKeyHash(), key.getPubKey(), false, canWriteClientCache, canWriteDatastore, false, writeLocalToDatastore);
Logger.minor(this, "makeInsertSender("+key+ ',' +htl+ ',' +uid+ ',' +source+",...,"+fromStore);
SSKInsertSender is = null;
is = new SSKInsertSender(block, uid, tag, htl, source, this, fromStore, canWriteClientCache, forkOnCacheable, preferInsert, ignoreLowBackoff, realTimeFlag);
is.start();
return is;
}
/**
* @return Some status information.
*/
public String getStatus() {
StringBuilder sb = new StringBuilder();
if (peers != null)
sb.append(peers.getStatus());
else
sb.append("No peers yet");
sb.append(tracker.getNumTransferringRequestSenders());
sb.append('\n');
return sb.toString();
}
/**
* @return TMCI peer list
*/
public String getTMCIPeerList() {
StringBuilder sb = new StringBuilder();
if (peers != null)
sb.append(peers.getTMCIPeerList());
else
sb.append("No peers yet");
return sb.toString();
}
/** Length of signature parameters R and S */
static final int SIGNATURE_PARAMETER_LENGTH = 32;
public ClientKeyBlock fetchKey(ClientKey key, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws KeyVerifyException {
if(key instanceof ClientCHK)
return fetch((ClientCHK)key, canReadClientCache, canWriteClientCache, canWriteDatastore);
else if(key instanceof ClientSSK)
return fetch((ClientSSK)key, canReadClientCache, canWriteClientCache, canWriteDatastore);
else
throw new IllegalStateException("Don't know what to do with "+key);
}
public ClientKeyBlock fetch(ClientSSK clientSSK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws SSKVerifyException {
DSAPublicKey key = clientSSK.getPubKey();
if(key == null) {
key = getPubKey.getKey(clientSSK.pubKeyHash, canReadClientCache, false, null);
}
if(key == null) return null;
clientSSK.setPublicKey(key);
SSKBlock block = fetch((NodeSSK)clientSSK.getNodeKey(true), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null);
if(block == null) {
if(logMINOR)
Logger.minor(this, "Could not find key for "+clientSSK);
return null;
}
// Move the pubkey to the top of the LRU, and fix it if it
// was corrupt.
getPubKey.cacheKey(clientSSK.pubKeyHash, key, false, canWriteClientCache, canWriteDatastore, false, writeLocalToDatastore);
return ClientSSKBlock.construct(block, clientSSK);
}
private ClientKeyBlock fetch(ClientCHK clientCHK, boolean canReadClientCache, boolean canWriteClientCache, boolean canWriteDatastore) throws CHKVerifyException {
CHKBlock block = fetch(clientCHK.getNodeCHK(), false, canReadClientCache, canWriteClientCache, canWriteDatastore, false, null);
if(block == null) return null;
return new ClientCHKBlock(block, clientCHK);
}
public void exit(int reason) {
try {
this.park();
System.out.println("Goodbye.");
System.out.println(reason);
} finally {
System.exit(reason);
}
}
public void exit(String reason){
try {
this.park();
System.out.println("Goodbye. from "+this+" ("+reason+ ')');
} finally {
System.exit(0);
}
}
/**
* Returns true if the node is shutting down.
* The packet receiver calls this for every packet, and boolean is atomic, so this method is not synchronized.
*/
public boolean isStopping() {
return isStopping;
}
/**
* Get the node into a state where it can be stopped safely
* May be called twice - once in exit (above) and then again
* from the wrapper triggered by calling System.exit(). Beware!
*/
public void park() {
synchronized(this) {
if(isStopping) return;
isStopping = true;
}
try {
Message msg = DMT.createFNPDisconnect(false, false, -1, new ShortBuffer(new byte[0]));
peers.localBroadcast(msg, true, false, peers.ctrDisconn);
} catch (Throwable t) {
try {
// E.g. if we haven't finished startup
Logger.error(this, "Failed to tell peers we are going down: "+t, t);
} catch (Throwable t1) {
// Ignore. We don't want to mess up the exit process!
}
}
config.store();
if(random instanceof PersistentRandomSource) {
((PersistentRandomSource) random).write_seed(true);
}
}
public NodeUpdateManager getNodeUpdater(){
return nodeUpdater;
}
public DarknetPeerNode[] getDarknetConnections() {
return peers.getDarknetPeers();
}
public boolean addPeerConnection(PeerNode pn) {
boolean retval = peers.addPeer(pn);
peers.writePeersUrgent(pn.isOpennet());
return retval;
}
public void removePeerConnection(PeerNode pn) {
peers.disconnectAndRemove(pn, true, false, false);
}
public void onConnectedPeer() {
if(logMINOR) Logger.minor(this, "onConnectedPeer()");
ipDetector.onConnectedPeer();
}
public int getFNPPort(){
return this.getDarknetPortNumber();
}
public boolean isOudated() {
return peers.isOutdated();
}
private Map<Integer, NodeToNodeMessageListener> n2nmListeners = new HashMap<Integer, NodeToNodeMessageListener>();
public synchronized void registerNodeToNodeMessageListener(int type, NodeToNodeMessageListener listener) {
n2nmListeners.put(type, listener);
}
/**
* Handle a received node to node message
*/
public void receivedNodeToNodeMessage(Message m, PeerNode src) {
int type = ((Integer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_TYPE)).intValue();
ShortBuffer messageData = (ShortBuffer) m.getObject(DMT.NODE_TO_NODE_MESSAGE_DATA);
receivedNodeToNodeMessage(src, type, messageData, false);
}
public void receivedNodeToNodeMessage(PeerNode src, int type, ShortBuffer messageData, boolean partingMessage) {
boolean fromDarknet = src instanceof DarknetPeerNode;
NodeToNodeMessageListener listener = null;
synchronized(this) {
listener = n2nmListeners.get(type);
}
if(listener == null) {
Logger.error(this, "Unknown n2nm ID: "+type+" - discarding packet length "+messageData.getLength());
return;
}
listener.handleMessage(messageData.getData(), fromDarknet, src, type);
}
private NodeToNodeMessageListener diffNoderefListener = new NodeToNodeMessageListener() {
@Override
public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) {
Logger.normal(this, "Received differential node reference node to node message from "+src.getPeer());
SimpleFieldSet fs = null;
try {
fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false);
} catch (IOException e) {
Logger.error(this, "IOException while parsing node to node message data", e);
return;
}
if(fs.get("n2nType") != null) {
fs.removeValue("n2nType");
}
try {
src.processDiffNoderef(fs);
} catch (FSParseException e) {
Logger.error(this, "FSParseException while parsing node to node message data", e);
return;
}
}
};
private NodeToNodeMessageListener fproxyN2NMListener = new NodeToNodeMessageListener() {
@Override
public void handleMessage(byte[] data, boolean fromDarknet, PeerNode src, int type) {
if(!fromDarknet) {
Logger.error(this, "Got N2NTM from non-darknet node ?!?!?!: from "+src);
return;
}
DarknetPeerNode darkSource = (DarknetPeerNode) src;
Logger.normal(this, "Received N2NTM from '"+darkSource.getPeer()+"'");
SimpleFieldSet fs = null;
try {
fs = new SimpleFieldSet(new String(data, "UTF-8"), false, true, false);
} catch (UnsupportedEncodingException e) {
throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e);
} catch (IOException e) {
Logger.error(this, "IOException while parsing node to node message data", e);
return;
}
fs.putOverwrite("n2nType", Integer.toString(type));
fs.putOverwrite("receivedTime", Long.toString(System.currentTimeMillis()));
fs.putOverwrite("receivedAs", "nodeToNodeMessage");
int fileNumber = darkSource.writeNewExtraPeerDataFile( fs, EXTRA_PEER_DATA_TYPE_N2NTM);
if( fileNumber == -1 ) {
Logger.error( this, "Failed to write N2NTM to extra peer data file for peer "+darkSource.getPeer());
}
// Keep track of the fileNumber so we can potentially delete the extra peer data file later, the file is authoritative
try {
handleNodeToNodeTextMessageSimpleFieldSet(fs, darkSource, fileNumber);
} catch (FSParseException e) {
// Shouldn't happen
throw new Error(e);
}
}
};
/**
* Handle a node to node text message SimpleFieldSet
* @throws FSParseException
*/
public void handleNodeToNodeTextMessageSimpleFieldSet(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException {
if(logMINOR)
Logger.minor(this, "Got node to node message: \n"+fs);
int overallType = fs.getInt("n2nType");
fs.removeValue("n2nType");
if(overallType == Node.N2N_MESSAGE_TYPE_FPROXY) {
handleFproxyNodeToNodeTextMessageSimpleFieldSet(fs, source, fileNumber);
} else {
Logger.error(this, "Received unknown node to node message type '"+overallType+"' from "+source.getPeer());
}
}
private void handleFproxyNodeToNodeTextMessageSimpleFieldSet(SimpleFieldSet fs, DarknetPeerNode source, int fileNumber) throws FSParseException {
int type = fs.getInt("type");
if(type == Node.N2N_TEXT_MESSAGE_TYPE_USERALERT) {
source.handleFproxyN2NTM(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER) {
source.handleFproxyFileOffer(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED) {
source.handleFproxyFileOfferAccepted(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED) {
source.handleFproxyFileOfferRejected(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_BOOKMARK) {
source.handleFproxyBookmarkFeed(fs, fileNumber);
} else if(type == Node.N2N_TEXT_MESSAGE_TYPE_DOWNLOAD) {
source.handleFproxyDownloadFeed(fs, fileNumber);
} else {
Logger.error(this, "Received unknown fproxy node to node message sub-type '"+type+"' from "+source.getPeer());
}
}
public String getMyName() {
return myName;
}
public MessageCore getUSM() {
return usm;
}
public LocationManager getLocationManager() {
return lm;
}
public int getSwaps() {
return LocationManager.swaps;
}
public int getNoSwaps() {
return LocationManager.noSwaps;
}
public int getStartedSwaps() {
return LocationManager.startedSwaps;
}
public int getSwapsRejectedAlreadyLocked() {
return LocationManager.swapsRejectedAlreadyLocked;
}
public int getSwapsRejectedNowhereToGo() {
return LocationManager.swapsRejectedNowhereToGo;
}
public int getSwapsRejectedRateLimit() {
return LocationManager.swapsRejectedRateLimit;
}
public int getSwapsRejectedRecognizedID() {
return LocationManager.swapsRejectedRecognizedID;
}
public PeerNode[] getPeerNodes() {
return peers.myPeers();
}
public PeerNode[] getConnectedPeers() {
return peers.connectedPeers();
}
/**
* Return a peer of the node given its ip and port, name or identity, as a String
*/
public PeerNode getPeerNode(String nodeIdentifier) {
for(PeerNode pn: peers.myPeers()) {
Peer peer = pn.getPeer();
String nodeIpAndPort = "";
if(peer != null) {
nodeIpAndPort = peer.toString();
}
String identity = pn.getIdentityString();
if(pn instanceof DarknetPeerNode) {
DarknetPeerNode dpn = (DarknetPeerNode) pn;
String name = dpn.myName;
if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier) || name.equals(nodeIdentifier)) {
return pn;
}
} else {
if(identity.equals(nodeIdentifier) || nodeIpAndPort.equals(nodeIdentifier)) {
return pn;
}
}
}
return null;
}
public boolean isHasStarted() {
return hasStarted;
}
public void queueRandomReinsert(KeyBlock block) {
clientCore.queueRandomReinsert(block);
}
public String getExtraPeerDataDir() {
return extraPeerDataDir.getPath();
}
public boolean noConnectedPeers() {
return !peers.anyConnectedPeers();
}
public double getLocation() {
return lm.getLocation();
}
public double getLocationChangeSession() {
return lm.getLocChangeSession();
}
public int getAverageOutgoingSwapTime() {
return lm.getAverageSwapTime();
}
public long getSendSwapInterval() {
return lm.getSendSwapInterval();
}
public int getNumberOfRemotePeerLocationsSeenInSwaps() {
return lm.numberOfRemotePeerLocationsSeenInSwaps;
}
public boolean isAdvancedModeEnabled() {
if(clientCore == null) return false;
return clientCore.isAdvancedModeEnabled();
}
public boolean isFProxyJavascriptEnabled() {
return clientCore.isFProxyJavascriptEnabled();
}
// FIXME convert these kind of threads to Checkpointed's and implement a handler
// using the PacketSender/Ticker. Would save a few threads.
public int getNumARKFetchers() {
int x = 0;
for(PeerNode p: peers.myPeers()) {
if(p.isFetchingARK()) x++;
}
return x;
}
// FIXME put this somewhere else
private volatile Object statsSync = new Object();
/** The total number of bytes of real data i.e. payload sent by the node */
private long totalPayloadSent;
public void sentPayload(int len) {
synchronized(statsSync) {
totalPayloadSent += len;
}
}
/**
* Get the total number of bytes of payload (real data) sent by the node
*
* @return Total payload sent in bytes
*/
public long getTotalPayloadSent() {
synchronized(statsSync) {
return totalPayloadSent;
}
}
public void setName(String key) throws InvalidConfigValueException, NodeNeedRestartException {
config.get("node").getOption("name").setValue(key);
}
public Ticker getTicker() {
return ticker;
}
public int getUnclaimedFIFOSize() {
return usm.getUnclaimedFIFOSize();
}
/**
* Connect this node to another node (for purposes of testing)
*/
public void connectToSeednode(SeedServerTestPeerNode node) throws OpennetDisabledException, FSParseException, PeerParseException, ReferenceSignatureVerificationException {
peers.addPeer(node,false,false);
}
public void connect(Node node, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
peers.connect(node.darknetCrypto.exportPublicFieldSet(), darknetCrypto.packetMangler, trust, visibility);
}
public short maxHTL() {
return maxHTL;
}
public int getDarknetPortNumber() {
return darknetCrypto.portNumber;
}
public synchronized int getOutputBandwidthLimit() {
return outputBandwidthLimit;
}
public synchronized int getInputBandwidthLimit() {
if(inputLimitDefault)
return outputBandwidthLimit * 4;
return inputBandwidthLimit;
}
/**
* @return total datastore size in bytes.
*/
public synchronized long getStoreSize() {
return maxTotalDatastoreSize;
}
@Override
public synchronized void setTimeSkewDetectedUserAlert() {
if(timeSkewDetectedUserAlert == null) {
timeSkewDetectedUserAlert = new TimeSkewDetectedUserAlert();
clientCore.alerts.register(timeSkewDetectedUserAlert);
}
}
public File getNodeDir() { return nodeDir.dir(); }
public File getCfgDir() { return cfgDir.dir(); }
public File getUserDir() { return userDir.dir(); }
public File getRunDir() { return runDir.dir(); }
public File getStoreDir() { return storeDir.dir(); }
public File getPluginDir() { return pluginDir.dir(); }
public ProgramDirectory nodeDir() { return nodeDir; }
public ProgramDirectory cfgDir() { return cfgDir; }
public ProgramDirectory userDir() { return userDir; }
public ProgramDirectory runDir() { return runDir; }
public ProgramDirectory storeDir() { return storeDir; }
public ProgramDirectory pluginDir() { return pluginDir; }
public DarknetPeerNode createNewDarknetNode(SimpleFieldSet fs, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
return new DarknetPeerNode(fs, this, darknetCrypto, false, trust, visibility);
}
public OpennetPeerNode createNewOpennetNode(SimpleFieldSet fs) throws FSParseException, OpennetDisabledException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
if(opennet == null) throw new OpennetDisabledException("Opennet is not currently enabled");
return new OpennetPeerNode(fs, this, opennet.crypto, opennet, false);
}
public SeedServerTestPeerNode createNewSeedServerTestPeerNode(SimpleFieldSet fs) throws FSParseException, OpennetDisabledException, PeerParseException, ReferenceSignatureVerificationException, PeerTooOldException {
if(opennet == null) throw new OpennetDisabledException("Opennet is not currently enabled");
return new SeedServerTestPeerNode(fs, this, opennet.crypto, true);
}
public OpennetPeerNode addNewOpennetNode(SimpleFieldSet fs, ConnectionType connectionType) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException {
// FIXME: perhaps this should throw OpennetDisabledExcemption rather than returing false?
if(opennet == null) return null;
return opennet.addNewOpennetNode(fs, connectionType, false);
}
public byte[] getOpennetPubKeyHash() {
return opennet.crypto.ecdsaPubKeyHash;
}
public byte[] getDarknetPubKeyHash() {
return darknetCrypto.ecdsaPubKeyHash;
}
public synchronized boolean isOpennetEnabled() {
return opennet != null;
}
public SimpleFieldSet exportDarknetPublicFieldSet() {
return darknetCrypto.exportPublicFieldSet();
}
public SimpleFieldSet exportOpennetPublicFieldSet() {
return opennet.crypto.exportPublicFieldSet();
}
public SimpleFieldSet exportDarknetPrivateFieldSet() {
return darknetCrypto.exportPrivateFieldSet();
}
public SimpleFieldSet exportOpennetPrivateFieldSet() {
return opennet.crypto.exportPrivateFieldSet();
}
/**
* Should the IP detection code only use the IP address override and the bindTo information,
* rather than doing a full detection?
*/
public synchronized boolean dontDetect() {
// Only return true if bindTo is set on all ports which are in use
if(!darknetCrypto.getBindTo().isRealInternetAddress(false, true, false)) return false;
if(opennet != null) {
if(opennet.crypto.getBindTo().isRealInternetAddress(false, true, false)) return false;
}
return true;
}
public int getOpennetFNPPort() {
if(opennet == null) return -1;
return opennet.crypto.portNumber;
}
public OpennetManager getOpennet() {
return opennet;
}
public synchronized boolean passOpennetRefsThroughDarknet() {
return passOpennetRefsThroughDarknet;
}
/**
* Get the set of public ports that need to be forwarded. These are internal
* ports, not necessarily external - they may be rewritten by the NAT.
* @return A Set of ForwardPort's to be fed to port forward plugins.
*/
public Set<ForwardPort> getPublicInterfacePorts() {
HashSet<ForwardPort> set = new HashSet<ForwardPort>();
// FIXME IPv6 support
set.add(new ForwardPort("darknet", false, ForwardPort.PROTOCOL_UDP_IPV4, darknetCrypto.portNumber));
if(opennet != null) {
NodeCrypto crypto = opennet.crypto;
if(crypto != null) {
set.add(new ForwardPort("opennet", false, ForwardPort.PROTOCOL_UDP_IPV4, crypto.portNumber));
}
}
return set;
}
/**
* Get the time since the node was started in milliseconds.
*
* @return Uptime in milliseconds
*/
public long getUptime() {
return System.currentTimeMillis() - usm.getStartedTime();
}
public synchronized UdpSocketHandler[] getPacketSocketHandlers() {
// FIXME better way to get these!
if(opennet != null) {
return new UdpSocketHandler[] { darknetCrypto.socket, opennet.crypto.socket };
// TODO Auto-generated method stub
} else {
return new UdpSocketHandler[] { darknetCrypto.socket };
}
}
public int getMaxOpennetPeers() {
return maxOpennetPeers;
}
public void onAddedValidIP() {
OpennetManager om;
synchronized(this) {
om = opennet;
}
if(om != null) {
Announcer announcer = om.announcer;
if(announcer != null) {
announcer.maybeSendAnnouncement();
}
}
}
public boolean isSeednode() {
return acceptSeedConnections;
}
/**
* Returns true if the packet receiver should try to decode/process packets that are not from a peer (i.e. from a seed connection)
* The packet receiver calls this upon receiving an unrecognized packet.
*/
public boolean wantAnonAuth(boolean isOpennet) {
if(isOpennet)
return opennet != null && acceptSeedConnections;
else
return false;
}
// FIXME make this configurable
// Probably should wait until we have non-opennet anon auth so we can add it to NodeCrypto.
public boolean wantAnonAuthChangeIP(boolean isOpennet) {
return !isOpennet;
}
public boolean opennetDefinitelyPortForwarded() {
OpennetManager om;
synchronized(this) {
om = this.opennet;
}
if(om == null) return false;
NodeCrypto crypto = om.crypto;
if(crypto == null) return false;
return crypto.definitelyPortForwarded();
}
public boolean darknetDefinitelyPortForwarded() {
if(darknetCrypto == null) return false;
return darknetCrypto.definitelyPortForwarded();
}
public boolean hasKey(Key key, boolean canReadClientCache, boolean forULPR) {
// FIXME optimise!
if(key instanceof NodeCHK)
return fetch((NodeCHK)key, true, canReadClientCache, false, false, forULPR, null) != null;
else
return fetch((NodeSSK)key, true, canReadClientCache, false, false, forULPR, null) != null;
}
/**
* Warning: does not announce change in location!
*/
public void setLocation(double loc) {
lm.setLocation(loc);
}
public boolean peersWantKey(Key key) {
return failureTable.peersWantKey(key, null);
}
private SimpleUserAlert alertMTUTooSmall;
public final RequestClient nonPersistentClientBulk = new RequestClientBuilder().build();
public final RequestClient nonPersistentClientRT = new RequestClientBuilder().realTime().build();
public void setDispatcherHook(NodeDispatcherCallback cb) {
this.dispatcher.setHook(cb);
}
public boolean shallWePublishOurPeersLocation() {
return publishOurPeersLocation;
}
public boolean shallWeRouteAccordingToOurPeersLocation(int htl) {
return routeAccordingToOurPeersLocation && htl > 1;
}
/** Can be called to decrypt client.dat* etc, or can be called when switching from another
* security level to HIGH. */
public void setMasterPassword(String password, boolean inFirstTimeWizard) throws AlreadySetPasswordException, MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException {
MasterKeys k;
synchronized(this) {
if(keys == null) {
// Decrypting.
keys = MasterKeys.read(masterKeysFile, secureRandom, password);
databaseKey = keys.createDatabaseKey(secureRandom);
} else {
// Setting password when changing to HIGH from another mode.
keys.changePassword(masterKeysFile, password, secureRandom);
return;
}
k = keys;
}
setPasswordInner(k, inFirstTimeWizard);
}
private void setPasswordInner(MasterKeys keys, boolean inFirstTimeWizard) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException {
MasterSecret secret = keys.getPersistentMasterSecret();
clientCore.setupMasterSecret(secret);
boolean wantClientCache = false;
boolean wantDatabase = false;
synchronized(this) {
wantClientCache = clientCacheAwaitingPassword;
wantDatabase = databaseAwaitingPassword;
databaseAwaitingPassword = false;
}
if(wantClientCache)
activatePasswordedClientCache(keys);
if(wantDatabase)
lateSetupDatabase(keys.createDatabaseKey(secureRandom));
}
private void activatePasswordedClientCache(MasterKeys keys) {
synchronized(this) {
if(clientCacheType.equals("ram")) {
System.err.println("RAM client cache cannot be passworded!");
return;
}
if(!clientCacheType.equals("salt-hash")) {
System.err.println("Unknown client cache type, cannot activate passworded store: "+clientCacheType);
return;
}
}
Runnable migrate = new MigrateOldStoreData(true);
String suffix = getStoreSuffix();
try {
initSaltHashClientCacheFS(suffix, true, keys.clientCacheMasterKey);
} catch (NodeInitException e) {
Logger.error(this, "Unable to activate passworded client cache", e);
System.err.println("Unable to activate passworded client cache: "+e);
e.printStackTrace();
return;
}
synchronized(this) {
clientCacheAwaitingPassword = false;
}
executor.execute(migrate, "Migrate data from previous store");
}
public void changeMasterPassword(String oldPassword, String newPassword, boolean inFirstTimeWizard) throws MasterKeysWrongPasswordException, MasterKeysFileSizeException, IOException, AlreadySetPasswordException {
if(securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.MAXIMUM)
Logger.error(this, "Changing password while physical threat level is at MAXIMUM???");
if(masterKeysFile.exists()) {
keys.changePassword(masterKeysFile, newPassword, secureRandom);
setPasswordInner(keys, inFirstTimeWizard);
} else {
setMasterPassword(newPassword, inFirstTimeWizard);
}
}
public static class AlreadySetPasswordException extends Exception {
final private static long serialVersionUID = -7328456475029374032L;
}
public synchronized File getMasterPasswordFile() {
return masterKeysFile;
}
boolean hasPanicked() {
return hasPanicked;
}
public void panic() {
hasPanicked = true;
clientCore.clientLayerPersister.panic();
clientCore.clientLayerPersister.killAndWaitForNotRunning();
try {
MasterKeys.killMasterKeys(getMasterPasswordFile());
} catch (IOException e) {
System.err.println("Unable to wipe master passwords key file!");
System.err.println("Please delete " + getMasterPasswordFile()
+ " to ensure that nobody can recover your old downloads.");
}
// persistent-temp will be cleaned on restart.
}
public void finishPanic() {
WrapperManager.restart();
System.exit(0);
}
public boolean awaitingPassword() {
if(clientCacheAwaitingPassword) return true;
if(databaseAwaitingPassword) return true;
return false;
}
public boolean wantEncryptedDatabase() {
return this.securityLevels.getPhysicalThreatLevel() != PHYSICAL_THREAT_LEVEL.LOW;
}
public boolean wantNoPersistentDatabase() {
return this.securityLevels.getPhysicalThreatLevel() == PHYSICAL_THREAT_LEVEL.MAXIMUM;
}
public boolean hasDatabase() {
return !clientCore.clientLayerPersister.isKilledOrNotLoaded();
}
/**
* @return canonical path of the database file in use.
*/
public String getDatabasePath() throws IOException {
return clientCore.clientLayerPersister.getWriteFilename().toString();
}
/** Should we commit the block to the store rather than the cache?
*
* <p>We used to check whether we are a sink by checking whether any peer has
* a closer location than we do. Then we made low-uptime nodes exempt from
* this calculation: if we route to a low uptime node with a closer location,
* we want to store it anyway since he may go offline. The problem was that
* if we routed to a low-uptime node, and there was another option that wasn't
* low-uptime but was closer to the target than we were, then we would not
* store in the store. Also, routing isn't always by the closest peer location:
* FOAF and per-node failure tables change it. So now, we consider the nodes
* we have actually routed to:</p>
*
* <p>Store in datastore if our location is closer to the target than:</p><ol>
* <li>the source location (if any, and ignoring if low-uptime)</li>
* <li>the locations of the nodes we just routed to (ditto)</li>
* </ol>
*
* @param key
* @param source
* @param routedTo
* @return
*/
public boolean shouldStoreDeep(Key key, PeerNode source, PeerNode[] routedTo) {
double myLoc = getLocation();
double target = key.toNormalizedDouble();
double myDist = Location.distance(myLoc, target);
// First, calculate whether we would have stored it using the old formula.
if(logMINOR) Logger.minor(this, "Should store for "+key+" ?");
// Don't sink store if any of the nodes we routed to, or our predecessor, is both high-uptime and closer to the target than we are.
if(source != null && !source.isLowUptime()) {
if(Location.distance(source, target) < myDist) {
if(logMINOR) Logger.minor(this, "Not storing because source is closer to target for "+key+" : "+source);
return false;
}
}
for(PeerNode pn : routedTo) {
if(Location.distance(pn, target) < myDist && !pn.isLowUptime()) {
if(logMINOR) Logger.minor(this, "Not storing because peer "+pn+" is closer to target for "+key+" his loc "+pn.getLocation()+" my loc "+myLoc+" target is "+target);
return false;
} else {
if(logMINOR) Logger.minor(this, "Should store maybe, peer "+pn+" loc = "+pn.getLocation()+" my loc is "+myLoc+" target is "+target+" low uptime is "+pn.isLowUptime());
}
}
if(logMINOR) Logger.minor(this, "Should store returning true for "+key+" target="+target+" myLoc="+myLoc+" peers: "+routedTo.length);
return true;
}
public boolean getWriteLocalToDatastore() {
return writeLocalToDatastore;
}
public boolean getUseSlashdotCache() {
return useSlashdotCache;
}
// FIXME remove the visibility alert after a few builds.
public void createVisibilityAlert() {
synchronized(this) {
if(showFriendsVisibilityAlert) return;
showFriendsVisibilityAlert = true;
}
// Wait until startup completed.
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
config.store();
}
}, 0);
registerFriendsVisibilityAlert();
}
private UserAlert visibilityAlert = new SimpleUserAlert(true, l10n("pleaseSetPeersVisibilityAlertTitle"), l10n("pleaseSetPeersVisibilityAlert"), l10n("pleaseSetPeersVisibilityAlert"), UserAlert.ERROR) {
@Override
public void onDismiss() {
synchronized(Node.this) {
showFriendsVisibilityAlert = false;
}
config.store();
unregisterFriendsVisibilityAlert();
}
};
private void registerFriendsVisibilityAlert() {
if(clientCore == null || clientCore.alerts == null) {
// Wait until startup completed.
this.getTicker().queueTimedJob(new Runnable() {
@Override
public void run() {
registerFriendsVisibilityAlert();
}
}, 0);
return;
}
clientCore.alerts.register(visibilityAlert);
}
private void unregisterFriendsVisibilityAlert() {
clientCore.alerts.unregister(visibilityAlert);
}
public int getMinimumMTU() {
int mtu;
synchronized(this) {
mtu = maxPacketSize;
}
if(ipDetector != null) {
int detected = ipDetector.getMinimumDetectedMTU();
if(detected < mtu) return detected;
}
return mtu;
}
public void updateMTU() {
this.darknetCrypto.socket.calculateMaxPacketSize();
OpennetManager om = opennet;
if(om != null) {
om.crypto.socket.calculateMaxPacketSize();
}
}
public static boolean isTestnetEnabled() {
return false;
}
public MersenneTwister createRandom() {
byte[] buf = new byte[16];
random.nextBytes(buf);
return new MersenneTwister(buf);
}
public boolean enableNewLoadManagement(boolean realTimeFlag) {
NodeStats stats = this.nodeStats;
if(stats == null) {
Logger.error(this, "Calling enableNewLoadManagement before Node constructor completes! FIX THIS!", new Exception("error"));
return false;
}
return stats.enableNewLoadManagement(realTimeFlag);
}
/** FIXME move to Probe.java? */
public boolean enableRoutedPing() {
return enableRoutedPing;
}
public boolean updateIsUrgent() {
OpennetManager om = getOpennet();
if(om != null) {
if(om.announcer != null && om.announcer.isWaitingForUpdater())
return true;
}
if(peers.getPeerNodeStatusSize(PeerManager.PEER_NODE_STATUS_TOO_NEW, true) > PeerManager.OUTDATED_MIN_TOO_NEW_DARKNET)
return true;
return false;
}
public byte[] getPluginStoreKey(String storeIdentifier) {
DatabaseKey key;
synchronized(this) {
key = databaseKey;
}
if(key != null)
return key.getPluginStoreKey(storeIdentifier);
else
return null;
}
public PluginManager getPluginManager() {
return pluginManager;
}
DatabaseKey getDatabaseKey() {
return databaseKey;
}
}
| nextgens/fred | src/freenet/node/Node.java | Java | gpl-2.0 | 177,426 |
/* Copyright (C) 2014 InfiniDB, 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; version 2 of
the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
MA 02110-1301, USA. */
/*****************************************************************************
* $Id: sessionmanagerserver.cpp 1906 2013-06-14 19:15:32Z rdempsey $
*
****************************************************************************/
/*
* This class issues Transaction ID and keeps track of the current version ID
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <cerrno>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <string>
#include <stdexcept>
#include <limits>
#ifdef _MSC_VER
#include <io.h>
#include <psapi.h>
#endif
using namespace std;
#include <boost/thread/mutex.hpp>
#include <boost/scoped_ptr.hpp>
using namespace boost;
#include "brmtypes.h"
#include "calpontsystemcatalog.h"
using namespace execplan;
#include "configcpp.h"
#include "atomicops.h"
#define SESSIONMANAGERSERVER_DLLEXPORT
#include "sessionmanagerserver.h"
#undef SESSIONMANAGERSERVER_DLLEXPORT
#ifndef O_BINARY
#define O_BINARY 0
#endif
#ifndef O_DIRECT
#define O_DIRECT 0
#endif
#ifndef O_LARGEFILE
#define O_LARGEFILE 0
#endif
#ifndef O_NOATIME
#define O_NOATIME 0
#endif
#include "IDBDataFile.h"
#include "IDBPolicy.h"
using namespace idbdatafile;
namespace BRM
{
const uint32_t SessionManagerServer::SS_READY = 1 << 0; // Set by dmlProc one time when dmlProc is ready
const uint32_t SessionManagerServer::SS_SUSPENDED =
1 << 1; // Set by console when the system has been suspended by user.
const uint32_t SessionManagerServer::SS_SUSPEND_PENDING =
1 << 2; // Set by console when user wants to suspend, but writing is occuring.
const uint32_t SessionManagerServer::SS_SHUTDOWN_PENDING =
1 << 3; // Set by console when user wants to shutdown, but writing is occuring.
const uint32_t SessionManagerServer::SS_ROLLBACK =
1 << 4; // In combination with a PENDING flag, force a rollback as soom as possible.
const uint32_t SessionManagerServer::SS_FORCE =
1 << 5; // In combination with a PENDING flag, force a shutdown without rollback.
const uint32_t SessionManagerServer::SS_QUERY_READY =
1 << 6; // Set by ProcManager when system is ready for queries
SessionManagerServer::SessionManagerServer() : unique32(0), unique64(0)
{
config::Config* conf;
string stmp;
const char* ctmp;
conf = config::Config::makeConfig();
try
{
stmp = conf->getConfig("SessionManager", "MaxConcurrentTransactions");
}
catch (const std::exception& e)
{
cout << e.what() << endl;
stmp.clear();
}
if (stmp != "")
{
int64_t tmp;
ctmp = stmp.c_str();
tmp = config::Config::fromText(ctmp);
if (tmp < 1)
maxTxns = 1;
else
maxTxns = static_cast<int>(tmp);
}
else
maxTxns = 1;
txnidFilename = conf->getConfig("SessionManager", "TxnIDFile");
semValue = maxTxns;
_verID = 0;
_sysCatVerID = 0;
systemState = 0;
try
{
loadState();
}
catch (...)
{
// first-time run most likely, ignore the error
}
}
SessionManagerServer::~SessionManagerServer()
{
}
void SessionManagerServer::reset()
{
mutex.try_lock();
semValue = maxTxns;
condvar.notify_all();
activeTxns.clear();
mutex.unlock();
}
void SessionManagerServer::loadState()
{
int lastTxnID;
int err;
int lastSysCatVerId;
again:
// There are now 3 pieces of info stored in the txnidfd file: last
// transaction id, last system catalog version id, and the
// system state flags. All these values are stored in shared, an
// instance of struct Overlay.
// If we fail to read a full four bytes for any value, then the
// value isn't in the file, and we start with the default.
if (IDBPolicy::exists(txnidFilename.c_str()))
{
scoped_ptr<IDBDataFile> txnidfp(IDBDataFile::open(
IDBPolicy::getType(txnidFilename.c_str(), IDBPolicy::WRITEENG), txnidFilename.c_str(), "rb", 0));
if (!txnidfp)
{
perror("SessionManagerServer(): open");
throw runtime_error("SessionManagerServer: Could not open the transaction ID file");
}
// Last transaction id
txnidfp->seek(0, SEEK_SET);
err = txnidfp->read(&lastTxnID, 4);
if (err < 0 && errno != EINTR)
{
perror("Sessionmanager::initSegment(): read");
throw runtime_error("SessionManagerServer: read failed, aborting");
}
else if (err < 0)
goto again;
else if (err == sizeof(int))
_verID = lastTxnID;
// last system catalog version id
err = txnidfp->read(&lastSysCatVerId, 4);
if (err < 0 && errno != EINTR)
{
perror("Sessionmanager::initSegment(): read");
throw runtime_error("SessionManagerServer: read failed, aborting");
}
else if (err < 0)
goto again;
else if (err == sizeof(int))
_sysCatVerID = lastSysCatVerId;
// System state. Contains flags regarding the suspend state of the system.
err = txnidfp->read(&systemState, 4);
if (err < 0 && errno == EINTR)
{
goto again;
}
else if (err == sizeof(int))
{
// Turn off the pending and force flags. They make no sense for a clean start.
// Turn off the ready flag. DMLProc will set it back on when
// initialized.
systemState &=
~(SS_READY | SS_QUERY_READY | SS_SUSPEND_PENDING | SS_SHUTDOWN_PENDING | SS_ROLLBACK | SS_FORCE);
}
else
{
// else no problem. System state wasn't saved. Might be an upgraded system.
systemState = 0;
}
}
}
/* Save the systemState flags of the Overlay
* segment. This is saved in the third
* word of txnid File
*/
void SessionManagerServer::saveSystemState()
{
saveSMTxnIDAndState();
}
const QueryContext SessionManagerServer::verID()
{
QueryContext ret;
boost::mutex::scoped_lock lk(mutex);
ret.currentScn = _verID;
for (iterator i = activeTxns.begin(); i != activeTxns.end(); ++i)
ret.currentTxns->push_back(i->second);
return ret;
}
const QueryContext SessionManagerServer::sysCatVerID()
{
QueryContext ret;
boost::mutex::scoped_lock lk(mutex);
ret.currentScn = _sysCatVerID;
for (iterator i = activeTxns.begin(); i != activeTxns.end(); ++i)
ret.currentTxns->push_back(i->second);
return ret;
}
const TxnID SessionManagerServer::newTxnID(const SID session, bool block, bool isDDL)
{
TxnID ret; // ctor must set valid = false
iterator it;
boost::mutex::scoped_lock lk(mutex);
// if it already has a txn...
it = activeTxns.find(session);
if (it != activeTxns.end())
{
ret.id = it->second;
ret.valid = true;
return ret;
}
if (!block && semValue == 0)
return ret;
else
while (semValue == 0)
condvar.wait(lk);
semValue--;
idbassert(semValue <= (uint32_t)maxTxns);
ret.id = ++_verID;
ret.valid = true;
activeTxns[session] = ret.id;
if (isDDL)
++_sysCatVerID;
saveSMTxnIDAndState();
return ret;
}
void SessionManagerServer::finishTransaction(TxnID& txn)
{
iterator it;
boost::mutex::scoped_lock lk(mutex);
bool found = false;
if (!txn.valid)
throw invalid_argument("SessionManagerServer::finishTransaction(): transaction is invalid");
for (it = activeTxns.begin(); it != activeTxns.end();)
{
if (it->second == txn.id)
{
activeTxns.erase(it++);
txn.valid = false;
found = true;
// we could probably break at this point, but there won't be that many active txns, and,
// even though it'd be an error to have multiple entries for the same txn, we might
// well just get rid of them...
}
else
++it;
}
if (found)
{
semValue++;
idbassert(semValue <= (uint32_t)maxTxns);
condvar.notify_one();
}
else
throw invalid_argument("SessionManagerServer::finishTransaction(): transaction doesn't exist");
}
const TxnID SessionManagerServer::getTxnID(const SID session)
{
TxnID ret;
iterator it;
boost::mutex::scoped_lock lk(mutex);
it = activeTxns.find(session);
if (it != activeTxns.end())
{
ret.id = it->second;
ret.valid = true;
}
return ret;
}
shared_array<SIDTIDEntry> SessionManagerServer::SIDTIDMap(int& len)
{
int j;
shared_array<SIDTIDEntry> ret;
boost::mutex::scoped_lock lk(mutex);
iterator it;
ret.reset(new SIDTIDEntry[activeTxns.size()]);
len = activeTxns.size();
for (it = activeTxns.begin(), j = 0; it != activeTxns.end(); ++it, ++j)
{
ret[j].sessionid = it->first;
ret[j].txnid.id = it->second;
ret[j].txnid.valid = true;
}
return ret;
}
void SessionManagerServer::setSystemState(uint32_t state)
{
boost::mutex::scoped_lock lk(mutex);
systemState |= state;
saveSystemState();
}
void SessionManagerServer::clearSystemState(uint32_t state)
{
boost::mutex::scoped_lock lk(mutex);
systemState &= ~state;
saveSystemState();
}
uint32_t SessionManagerServer::getTxnCount()
{
boost::mutex::scoped_lock lk(mutex);
return activeTxns.size();
}
void SessionManagerServer::saveSMTxnIDAndState()
{
// caller holds the lock
scoped_ptr<IDBDataFile> txnidfp(IDBDataFile::open(
IDBPolicy::getType(txnidFilename.c_str(), IDBPolicy::WRITEENG), txnidFilename.c_str(), "wb", 0));
if (!txnidfp)
{
perror("SessionManagerServer(): open");
throw runtime_error("SessionManagerServer: Could not open the transaction ID file");
}
int filedata[2];
filedata[0] = _verID;
filedata[1] = _sysCatVerID;
int err = txnidfp->write(filedata, 8);
if (err < 0)
{
perror("SessionManagerServer::newTxnID(): write(verid)");
throw runtime_error("SessionManagerServer::newTxnID(): write(verid) failed");
}
uint32_t lSystemState = systemState;
// We don't save the pending flags, the force flag or the ready flags.
lSystemState &= ~(SS_READY | SS_QUERY_READY | SS_SUSPEND_PENDING | SS_SHUTDOWN_PENDING | SS_FORCE);
err = txnidfp->write(&lSystemState, sizeof(int));
if (err < 0)
{
perror("SessionManagerServer::saveSystemState(): write(systemState)");
throw runtime_error("SessionManagerServer::saveSystemState(): write(systemState) failed");
}
txnidfp->flush();
}
} // namespace BRM
| mariadb-corporation/mariadb-columnstore-engine | versioning/BRM/sessionmanagerserver.cpp | C++ | gpl-2.0 | 10,706 |
package org.adempiere.impexp.impl;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
import java.util.HashMap;
import java.util.Map;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.impexp.BPartnerImportProcess;
import org.adempiere.impexp.IImportProcess;
import org.adempiere.impexp.IImportProcessFactory;
import org.adempiere.impexp.ProductImportProcess;
import org.adempiere.impexp.spi.IAsyncImportProcessBuilder;
import org.adempiere.model.InterfaceWrapperHelper;
import org.adempiere.util.Check;
import org.compiere.model.I_I_BPartner;
import org.compiere.model.I_I_Product;
import com.google.common.base.Supplier;
public class ImportProcessFactory implements IImportProcessFactory
{
private final Map<Class<?>, Class<?>> modelImportClass2importProcessClasses = new HashMap<>();
private final Map<String, Class<?>> tableName2importProcessClasses = new HashMap<>();
private Supplier<IAsyncImportProcessBuilder> asyncImportProcessBuilderSupplier;
public ImportProcessFactory()
{
// Register standard import processes
registerImportProcess(I_I_BPartner.class, BPartnerImportProcess.class);
registerImportProcess(I_I_Product.class, ProductImportProcess.class);
}
@Override
public <ImportRecordType> void registerImportProcess(final Class<ImportRecordType> modelImportClass, final Class<? extends IImportProcess<ImportRecordType>> importProcessClass)
{
Check.assumeNotNull(modelImportClass, "modelImportClass not null");
Check.assumeNotNull(importProcessClass, "importProcessClass not null");
modelImportClass2importProcessClasses.put(modelImportClass, importProcessClass);
final String tableName = InterfaceWrapperHelper.getTableName(modelImportClass);
tableName2importProcessClasses.put(tableName, importProcessClass);
}
@Override
public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcess(final Class<ImportRecordType> modelImportClass)
{
final IImportProcess<ImportRecordType> importProcess = newImportProcessOrNull(modelImportClass);
Check.assumeNotNull(importProcess, "importProcess not null for {}", modelImportClass);
return importProcess;
}
@Override
public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessOrNull(final Class<ImportRecordType> modelImportClass)
{
Check.assumeNotNull(modelImportClass, "modelImportClass not null");
final Class<?> importProcessClass = modelImportClass2importProcessClasses.get(modelImportClass);
if (importProcessClass == null)
{
return null;
}
return newInstance(importProcessClass);
}
private <ImportRecordType> IImportProcess<ImportRecordType> newInstance(final Class<?> importProcessClass)
{
try
{
@SuppressWarnings("unchecked")
final IImportProcess<ImportRecordType> importProcess = (IImportProcess<ImportRecordType>)importProcessClass.newInstance();
return importProcess;
}
catch (Exception e)
{
throw new AdempiereException("Failed instantiating " + importProcessClass, e);
}
}
@Override
public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableNameOrNull(final String tableName)
{
Check.assumeNotNull(tableName, "tableName not null");
final Class<?> importProcessClass = tableName2importProcessClasses.get(tableName);
if (importProcessClass == null)
{
return null;
}
return newInstance(importProcessClass);
}
@Override
public <ImportRecordType> IImportProcess<ImportRecordType> newImportProcessForTableName(final String tableName)
{
final IImportProcess<ImportRecordType> importProcess = newImportProcessForTableNameOrNull(tableName);
Check.assumeNotNull(importProcess, "importProcess not null for {}", tableName);
return importProcess;
}
@Override
public IAsyncImportProcessBuilder newAsyncImportProcessBuilder()
{
Check.assumeNotNull(asyncImportProcessBuilderSupplier, "A supplier for {} shall be registered first", IAsyncImportProcessBuilder.class);
return asyncImportProcessBuilderSupplier.get();
}
@Override
public void setAsyncImportProcessBuilderSupplier(Supplier<IAsyncImportProcessBuilder> asyncImportProcessBuilderSupplier)
{
Check.assumeNotNull(asyncImportProcessBuilderSupplier, "asyncImportProcessBuilderSupplier not null");
this.asyncImportProcessBuilderSupplier = asyncImportProcessBuilderSupplier;
}
}
| klst-com/metasfresh | de.metas.business/src/main/java/org/adempiere/impexp/impl/ImportProcessFactory.java | Java | gpl-2.0 | 5,016 |
#pragma once
#include <MellowPlayer/Presentation/Notifications/ISystemTrayIcon.hpp>
#include <QMenu>
#include <QSystemTrayIcon>
namespace MellowPlayer::Domain
{
class ILogger;
class IPlayer;
class Setting;
class Settings;
}
class SystemTrayIconStrings : public QObject
{
Q_OBJECT
public:
QString playPause() const;
QString next() const;
QString previous() const;
QString restoreWindow() const;
QString quit() const;
};
namespace MellowPlayer::Infrastructure
{
class IApplication;
}
namespace MellowPlayer::Presentation
{
class IMainWindow;
class SystemTrayIcon : public QObject, public ISystemTrayIcon
{
Q_OBJECT
public:
SystemTrayIcon(Domain::IPlayer& player, IMainWindow& mainWindow, Domain::Settings& settings);
void show() override;
void hide() override;
void showMessage(const QString& title, const QString& message) override;
public slots:
void onActivated(QSystemTrayIcon::ActivationReason reason);
void togglePlayPause();
void next();
void previous();
void restoreWindow();
void quit();
private slots:
void onShowTrayIconSettingValueChanged();
private:
void setUpMenu();
Domain::ILogger& logger_;
Domain::IPlayer& player_;
IMainWindow& mainWindow_;
Domain::Settings& settings_;
Domain::Setting& showTrayIconSetting_;
QSystemTrayIcon qSystemTrayIcon_;
QMenu menu_;
QAction* playPauseAction_;
QAction* previousSongAction_;
QAction* nextSongAction_;
QAction* restoreWindowAction_;
QAction* quitApplicationAction_;
};
}
| ColinDuquesnoy/MellowPlayer | src/lib/presentation/include/MellowPlayer/Presentation/Notifications/SystemTrayIcon.hpp | C++ | gpl-2.0 | 1,712 |
package irc.bot;
import java.io.*;
public class OutHandler implements Runnable {
OutHandler(Connection connection) {
this.connection = connection;
}
private Connection connection;
public void run() {}
}
| propheh/IRCBot | irc/bot/OutHandler.java | Java | gpl-2.0 | 225 |
<?php
function edd_rp_settings( $settings ) {
$suggested_download_settings = array(
array(
'id' => 'edd_rp_header',
'name' => '<strong>' . __('Recommended Products', 'edd-rp-txt') . '</strong>',
'desc' => '',
'type' => 'header',
'size' => 'regular'
),
array(
'id' => 'edd_rp_display_single',
'name' => __('Show on Downloads', 'edd-rp-txt'),
'desc' => __('Display the recommended products on the download post type', 'edd-rp-txt'),
'type' => 'checkbox',
'size' => 'regular'
),
array(
'id' => 'edd_rp_display_checkout',
'name' => __('Show on Checkout', 'edd-rp-txt'),
'desc' => __('Display the recommended products after the Checkout Cart, and before the Checkout Form', 'edd-rp-txt'),
'type' => 'checkbox',
'size' => 'regular'
),
array(
'id' => 'edd_rp_suggestion_count',
'name' => __('Number of Recommendations', 'edd-rp-txt'),
'desc' => __('How many recommendations should be shown to users', 'edd-rp-txt'),
'type' => 'select',
'options' => edd_rp_suggestion_count()
),
array(
'id' => 'edd_rp_show_free',
'name' => __('Show Free Products', 'edd-rp-txt'),
'desc' => __('Allows free products to be shown in the recommendations. (Requires Refresh of Recommendations after save)', 'edd-rp-txt'),
'type' => 'checkbox',
'size' => 'regular'
),
array(
'id' => 'rp_settings_additional',
'name' => '',
'desc' => '',
'type' => 'hook'
)
);
return array_merge( $settings, $suggested_download_settings );
}
add_filter( 'edd_settings_extensions', 'edd_rp_settings' );
function edd_rp_suggestion_count() {
for ( $i = 1; $i <= 5; $i++ ) {
$count[$i] = $i;
}
$count[3] = __( '3 - Default', 'edd-rp-txt' );
return apply_filters( 'edd_rp_suggestion_counts', $count );
}
function edd_rp_recalc_suggestions_button() {
echo '<a href="' . wp_nonce_url( add_query_arg( array( 'edd_action' => 'refresh_edd_rp' ) ), 'edd-rp-recalculate' ) . '" class="button-secondary">' . __( 'Refresh Recommendations', 'edd-rp-txt' ) . '</a>';
}
add_action( 'edd_rp_settings_additional', 'edd_rp_recalc_suggestions_button' );
function refresh_edd_rp( $data ) {
if ( ! wp_verify_nonce( $data['_wpnonce'], 'edd-rp-recalculate' ) ) {
return;
}
// Refresh Suggestions
edd_rp_generate_stats();
add_action( 'admin_notices', 'edd_rp_recalc_notice' );
}
add_action( 'edd_refresh_edd_rp', 'refresh_edd_rp' );
function edd_rp_recalc_notice() {
printf( '<div class="updated settings-error"> <p> %s </p> </div>', esc_html__( 'Recommendations Updated.', 'edd-rp-txt' ) );
}
| SelaInc/eassignment | wp-content/plugins/edd-recommended-products/includes/settings.php | PHP | gpl-2.0 | 2,572 |
define(function(require) {
var Model = require("web/common/model");
var SpsrModel = Model.extend({
idAttribute: "recordId",
defaults: {
name: "SDI1",
kzck: 0,
ydsd: 0,
srjkxh: 0,
ld: 123,
dbd: 124,
bhd: 125,
sppy: 126,
czpy: 127
},
urls: {
"create": "spsr.psp",
"update": "spsr.psp",
"delete": "spsr.psp",
"read": "spsr.psp"
}
});
return SpsrModel;
}); | huang147300/EDSFrontEnd | js/index/pz/spsr/spsr_model.js | JavaScript | gpl-2.0 | 413 |
/**
* Copyright (c) 2008-2012 Indivica Inc.
*
* This software is made available under the terms of the
* GNU General Public License, Version 2, 1991 (GPLv2).
* License details are available via "indivica.ca/gplv2"
* and "gnu.org/licenses/gpl-2.0.html".
*/
package org.oscarehr.document.web;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.oscarehr.common.dao.CtlDocumentDao;
import org.oscarehr.common.dao.DocumentDao;
import org.oscarehr.common.dao.PatientLabRoutingDao;
import org.oscarehr.common.dao.ProviderInboxRoutingDao;
import org.oscarehr.common.dao.ProviderLabRoutingDao;
import org.oscarehr.common.dao.QueueDocumentLinkDao;
import org.oscarehr.common.model.CtlDocument;
import org.oscarehr.common.model.CtlDocumentPK;
import org.oscarehr.common.model.Document;
import org.oscarehr.common.model.PatientLabRouting;
import org.oscarehr.common.model.ProviderInboxItem;
import org.oscarehr.common.model.ProviderLabRoutingModel;
import org.oscarehr.util.LoggedInInfo;
import org.oscarehr.util.SpringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import oscar.dms.EDoc;
import oscar.dms.EDocUtil;
import oscar.oscarLab.ca.all.upload.ProviderLabRouting;
public class SplitDocumentAction extends DispatchAction {
private DocumentDao documentDao = SpringUtils.getBean(DocumentDao.class);
public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
String docNum = request.getParameter("document");
String[] commands = request.getParameterValues("page[]");
Document doc = documentDao.getDocument(docNum);
String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
new File(docdownload);
String newFilename = doc.getDocfilename();
FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
PDFParser parser = new PDFParser(input);
parser.parse();
PDDocument pdf = parser.getPDDocument();
PDDocument newPdf = new PDDocument();
List pages = pdf.getDocumentCatalog().getAllPages();
if (commands != null) {
for (String c : commands) {
String[] command = c.split(",");
int pageNum = Integer.parseInt(command[0]);
int rotation = Integer.parseInt(command[1]);
PDPage p = (PDPage)pages.get(pageNum-1);
p.setRotation(rotation);
newPdf.addPage(p);
}
}
//newPdf.save(docdownload + newFilename);
if (newPdf.getNumberOfPages() > 0) {
LoggedInInfo loggedInInfo=LoggedInInfo.loggedInInfo.get();
EDoc newDoc = new EDoc("","", newFilename, "", loggedInInfo.loggedInProvider.getProviderNo(), doc.getDoccreator(), "", 'A', oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1",0);
newDoc.setDocPublic("0");
newDoc.setContentType("application/pdf");
newDoc.setNumberOfPages(newPdf.getNumberOfPages());
String newDocNo = EDocUtil.addDocumentSQL(newDoc);
newPdf.save(docdownload + newDoc.getFileName());
newPdf.close();
WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getSession().getServletContext());
ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx.getBean("providerInboxRoutingDAO");
providerInboxRoutingDao.addToProviderInbox("0", Integer.parseInt(newDocNo), "DOC");
List<ProviderInboxItem> routeList = providerInboxRoutingDao.getProvidersWithRoutingForDocument("DOC", Integer.parseInt(docNum));
for (ProviderInboxItem i : routeList) {
providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), Integer.parseInt(newDocNo), "DOC");
}
providerInboxRoutingDao.addToProviderInbox(loggedInInfo.loggedInProvider.getProviderNo(), Integer.parseInt(newDocNo), "DOC");
QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx.getBean("queueDocumentLinkDAO");
Integer qid = 1;
Integer did= Integer.parseInt(newDocNo.trim());
queueDocumentLinkDAO.addToQueueDocumentLink(qid,did);
ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils.getBean("providerLabRoutingDao");
List<ProviderLabRoutingModel> result = providerLabRoutingDao.getProviderLabRoutingDocuments(Integer.parseInt(docNum));
if (!result.isEmpty()) {
new ProviderLabRouting().route(newDocNo,
result.get(0).getProviderNo(),"DOC");
}
PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils.getBean("patientLabRoutingDao");
List<PatientLabRouting> result2 = patientLabRoutingDao.findDocByDemographic(Integer.parseInt(docNum));
if (!result2.isEmpty()) {
PatientLabRouting newPatientRoute = new PatientLabRouting();
newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo());
newPatientRoute.setLabNo(Integer.parseInt(newDocNo));
newPatientRoute.setLabType("DOC");
patientLabRoutingDao.persist(newPatientRoute);
}
CtlDocumentDao ctlDocumentDao = SpringUtils.getBean(CtlDocumentDao.class);
CtlDocument result3 = ctlDocumentDao.getCtrlDocument(Integer.parseInt(docNum));
if (result3!=null) {
CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic");
CtlDocument newCtlDocument = new CtlDocument();
newCtlDocument.setId(ctlDocumentPK);
newCtlDocument.getId().setModuleId(result3.getId().getModuleId());
newCtlDocument.setStatus(result3.getStatus());
documentDao.persist(newCtlDocument);
}
}
pdf.close();
input.close();
return mapping.findForward("success");
}
public ActionForward rotate180(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Document doc = documentDao.getDocument(request.getParameter("document"));
String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
PDFParser parser = new PDFParser(input);
parser.parse();
PDDocument pdf = parser.getPDDocument();
int x = 1;
for (Object p : pdf.getDocumentCatalog().getAllPages()) {
PDPage pg = (PDPage)p;
Integer r = (pg.getRotation() != null ? pg.getRotation() : 0);
pg.setRotation((r+180)%360);
ManageDocumentAction.deleteCacheVersion(doc, x);
x++;
}
pdf.save(docdownload + doc.getDocfilename());
pdf.close();
input.close();
return null;
}
public ActionForward rotate90(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Document doc = documentDao.getDocument(request.getParameter("document"));
String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
PDFParser parser = new PDFParser(input);
parser.parse();
PDDocument pdf = parser.getPDDocument();
int x = 1;
for (Object p : pdf.getDocumentCatalog().getAllPages()) {
PDPage pg = (PDPage)p;
Integer r = (pg.getRotation() != null ? pg.getRotation() : 0);
pg.setRotation((r+90)%360);
ManageDocumentAction.deleteCacheVersion(doc, x);
x++;
}
pdf.save(docdownload + doc.getDocfilename());
pdf.close();
input.close();
return null;
}
public ActionForward removeFirstPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Document doc = documentDao.getDocument(request.getParameter("document"));
String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
FileInputStream input = new FileInputStream(docdownload + doc.getDocfilename());
PDFParser parser = new PDFParser(input);
parser.parse();
PDDocument pdf = parser.getPDDocument();
// Documents must have at least 2 pages, for the first page to be removed.
if (pdf.getNumberOfPages() <= 1) { return null; }
int x = 1;
for (Object p : pdf.getDocumentCatalog().getAllPages()) {
ManageDocumentAction.deleteCacheVersion(doc, x);
x++;
}
pdf.removePage(0);
EDocUtil.subtractOnePage(request.getParameter("document"));
pdf.save(docdownload + doc.getDocfilename());
pdf.close();
input.close();
return null;
}
} | hexbinary/landing | src/main/java/org/oscarehr/document/web/SplitDocumentAction.java | Java | gpl-2.0 | 8,755 |
<?php
if (!defined('TFUSE'))
exit('Direct access forbidden.');
/**
* Class UPDATER. Check for new versions of the theme, framework, or modules. Installs if found.
*/
class TF_UPDATER extends TF_TFUSE {
public $_the_class_name = 'UPDATER';
public $themefuse_update = false;
public $check_url; #http://themefuse.com/update-themes/
public function __construct() {
parent::__construct();
//$this->check_url = 'http://' . $_SERVER['HTTP_HOST'] . '/wp-updater/';
$this->check_url = 'http://themefuse.com/update-themes/';
}
public function __init() {
$this->themefuse_update = $this->themefuse_update_check();
if (get_option(TF_THEME_PREFIX . '_disable_updates') != 1) {
add_action('admin_menu', array($this, 'updates_item_menu_page'), 20);
if ($this->themefuse_update) {
add_action('admin_notices', array($this, 'themefuse_update_nag'));
}
}
}
function updates_item_menu_page() {
if (!empty($this->themefuse_update->response[TF_THEME_PREFIX]))
$count = count($this->themefuse_update->response[TF_THEME_PREFIX]);
$title = !empty($count) ? __('Updates', 'tfuse') . '<span class="update-plugins count-' . $count . '"><span class="update-count">' . number_format_i18n($count) . '</span></span>' : __('Updates', 'tfuse');
add_submenu_page('themefuse', __('Updates', 'tfuse'), $title, 'manage_options', 'tfupdates', array($this, 'themefuse_update_page'));
}
/**
* This function pings an http://themefuse.com/ asking if a new
* version of this theme is available. If not, it returns FALSE.
* If so, the external server passes serialized data back to this
* function, which gets unserialized and returned for use.
*
* @since 2.0
*/
function themefuse_update_check() {
if (!current_user_can('update_themes'))
return false;
if (!$this->request->empty_GET('action') && $this->request->GET('action') == 'checkagain') {
delete_site_transient('themefuse-update');
wp_redirect(self_admin_url('admin.php?page=tfupdates'));
}
$themefuse_update = get_site_transient('themefuse-update');
if (!$themefuse_update) {
$url = $this->check_url;
$options = array(
'body' => $this->update_params()
);
$request = wp_remote_post($url, $options);
$response = wp_remote_retrieve_body($request);
$themefuse_update = new stdClass();
$themefuse_update->last_checked = time();
// If an error occurred, return FALSE, store for 1 hour
if ($response == 'error' || is_wp_error($response) || !is_serialized($response)) {
$themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version'] = $this->theme->framework_version;
$themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version'] = $this->theme->mods_version;
$themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version'] = $this->theme->theme_version;
set_site_transient('themefuse-update', $themefuse_update, 60 * 60); // store for 1 hour
return false;
}
// Else, unserialize
$themefuse_update->response[TF_THEME_PREFIX] = maybe_unserialize($response);
// And store in transient
set_site_transient('themefuse-update', $themefuse_update, 60 * 60 * 24); // store for 24 hours
}
if (!(@$themefuse_update->response[TF_THEME_PREFIX]))
{ // If response is empty
return false;
}
else if (!empty($themefuse_update->response[TF_THEME_PREFIX]['suspended']))
{ // Verify if updates for this theme are not suspended from themefuse
return false;
} else if (
version_compare(
$this->theme->framework_version,
(!empty($themefuse_update->response[TF_THEME_PREFIX]['Framework'])
? @$themefuse_update->response[TF_THEME_PREFIX]['Framework']['new_version']
: '0'
),
'>='
)
&&
version_compare(
$this->theme->mods_version,
(!empty($themefuse_update->response[TF_THEME_PREFIX]['ThemeMods'])
? @$themefuse_update->response[TF_THEME_PREFIX]['ThemeMods']['new_version']
: '0'
),
'>='
)
&&
version_compare(
$this->theme->theme_version,
(!empty($themefuse_update->response[TF_THEME_PREFIX]['Templates'])
? @$themefuse_update->response[TF_THEME_PREFIX]['Templates']['new_version']
: '0'
),
'>='
)
)
{ // If we're already using the latest version, return FALSE
return false;
}
return $themefuse_update;
}
function update_params()
{
global $wp_version, $wpdb;
$params = array(
'theme_name' => $this->theme->theme_name,
'prefix' => $this->theme->prefix,
'framework_version' => $this->theme->framework_version,
'mods_version' => $this->theme->mods_version,
'theme_version' => $this->theme->theme_version,
'wp_version' => $wp_version,
'php_version' => phpversion(),
'mysql_version' => $wpdb->db_version(),
'uri' => home_url(),
'locale' => get_locale(),
'is_multi' => is_multisite(),
'is_child' => is_child_theme()
);
return apply_filters('tf_update_param', $params);
}
/**
* This function displays the update nag at the top of the
* dashboard if there is an ThemeFuse update available.
*
* @since 2.0
*/
function themefuse_update_nag() {
global $upgrading;
if (!$this->request->empty_GET('page') && $this->request->GET('page') == 'tfupdates')
return;
echo apply_filters('tf_update_nag_notice', $this->load->view('updater/update_nag', NULL, true) );
}
function themefuse_update_page() {
if ('tf-do-upgrade' == $this->theme->action || 'tf-do-reinstall' == $this->theme->action || ($this->request->isset_POST('upgrade') && $this->request->POST('upgrade') == __('Proceed', 'tfuse'))) {
check_admin_referer('themefuse-bulk-update');
$updates = !empty($this->themefuse_update->response[TF_THEME_PREFIX]) ? array_keys($this->themefuse_update->response[TF_THEME_PREFIX]) : array();
$updates = array_map('urldecode', $updates);
$this->load->view('updater/update_page');
if ($this->request->isset_POST('connection_type') && $this->request->POST('connection_type') == 'ftp') {
$filesystem = WP_Filesystem($this->request->POST());
}
$this->do_core_upgrade($updates);
} else {
$this->themefuse_upgrade_preamble();
}
}
function themefuse_upgrade_preamble() {
$updates = get_site_transient('themefuse-update');
$data = array(
'updates' => $updates
);
if (isset($this->themefuse_update->response))
$data['response'] = $this->themefuse_update->response;
$this->load->view('updater/upgrade_preamble', $data);
}
public function do_core_upgrade($updates) {
$this->load->helper('UPGRADER');
$updates = array_map('urldecode', $updates);
$url = 'admin.php?page=tfupdates&updates=' . urlencode(implode(',', $updates));
$nonce = 'themefuse-bulk-update';
//wp_enqueue_script('jquery');
//iframe_header();
$upgrader = new TF_Theme_Upgrader(new TF_Bulk_Theme_Upgrader_Skin(compact('nonce', 'url')));
$upgrader->bulk_upgrade($updates);
//iframe_footer();
}
} | reginas/callan-consulting | wp-content/themes/interakt-parent/framework/core/UPDATER.php | PHP | gpl-2.0 | 8,320 |
from sys import argv
script, input_file = argv
def print_all(f):
print f.read()
def rewind(f):
f.seek(0)
def print_a_line(line_count, f):
print line_count, f.readline()
current_file = open(input_file)
print "First let's print the whole file:\n"
print_all(current_file)
print "Now let's rewind, kind of like a tape."
rewind(current_file)
print "Let's print three lines:"
current_line = 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
current_line = current_line + 1
print_a_line(current_line, current_file)
| maxiee/LearnPythonTheHardWayExercises | ex20.py | Python | gpl-2.0 | 601 |
<?php
session_start();
$_SESSION["Status"]=0;
include("dbconn.php");
require ('../xajax.inc.php');
include("../dbinfo.inc.php");
$memid=$_SESSION['userId'];
$_SESSION["userid"]=$memid;
function viewuseralbums($userid,$jumpto)
{//list all the albums owned by the user
$objResponse = new xajaxResponse();
// how many rows to show per page
$rowsPerPage = 5;
// if $jumpto defined, use it as page number
if($jumpto!="")
$pageNum = $jumpto;
else
// by default show first page
$pageNum = 1;
$start = ($pageNum -1) * $rowsPerPage;
// enter query and display stuff
$query = "select * from album, ownalbum where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid' limit $start, $rowsPerPage";
$result=mysql_query($query)or die(mysql_error());
$count =mysql_numrows($result);
$msg;
if($count==0)
{$msg= "No Records founds";
$objResponse->addAssign("mytable","innerHTML",$msg);
}
else{
//create a table to display album pictures now
$msg.="<table class=\"table-wrapper\">";//echo
$msg.="<tr>";//end of echo
for($S=0;$S<$count;$S++)
{
$albumid =mysql_result($result,$S,"album.AlbumId");
$albumname= mysql_result($result,$S,"album.AlbumName");
//now display the album pic
//1st get the image path of the pic
// call a function Getpath2
$path = Getpath2($albumid);
// now display the album
//3 by 2
$msg.="<td>";
$msg.="<table class=\"table-shadows\" >
<tr>
<td class=\"td-shadows-main\">
<a href=\"javascript:void(null);\"onclick = \"xajax_createAlbumView($albumid,''); \" >";//end of echo
//GetImage path
$msg.="<IMG SRC=\"".$path."\"width=150 height=160>
</a>
</td >
<td class=\"td-shadows-right\"></td>
</tr>
<tr>
<td class=\"td-shadows-bottom\"></td>
<td class=\"td-shadows-bottomright\">
</td>
</tr>
<tr><td width = 50 class =\"mytext_account\">$albumname</td></tr>
</table><!--end of table shadows-->
</td>";//end of echo
//if no if col = 5 then new row
if(($S %5 )==0 &&($S+1)!==1 )
$msg.="</tr><tr>";
}//for
$msg.="</tr><table>";
//############## End of display stuff
// how many rows we have in database
$query="select COUNT(*) AS numrows from album, ownalbum
where album.AlbumId =ownalbum.AlbumId and ownalbum.OwnerId ='$userid'";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
//####################################
// creating 'previous' and 'next' link
if ($pageNum > 1)
{
$page = $pageNum -1;
$prev="<input type=\"button\" name=\"prev\" onclick =\"xajax_viewuseralbums($userid,$page);\" value=\"Prev\">";
$first = "<input type=\"button\" name=\"first\" onclick =\"xajax_viewuseralbums($userid,1);\" value=\"First\">";
}
else
{
$prev = ' '; // we're on page one, don't enable 'previous' link
$first = ' '; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = "<input type=\"button\" name=\"next\"onclick=\"xajax_viewuseralbums($userid,$page);\"value=\"Next\">";
$last = "<input type=\"button\" name=\"Last\"onclick=\"xajax_viewuseralbums($userid,$maxPage);\"value=\"Last\">";
}
else
{
$next = ' '; // we're on the last page, don't enable 'next' link
$last = ' '; // nor 'last page' link
}
// print the page navigation link
$msg.="<div class =\"mytext_account\">";
$msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
$msg.="</div>";
$objResponse->addAssign("mytable","innerHTML",$msg);
//$objResponse->addAssign("but","innerHTML",$but);
}//else
return $objResponse->getXML();
}//end of function
function Getpath2($albumid)
{
$query="SELECT images.Url FROM images,albumcontainsimages where images.ImageId=albumcontainsimages.ImageId and albumcontainsimages.AlbumId=$albumid";
$result=mysql_query($query);
$num=mysql_numrows($result);
//check
$msg;
if($num==0)
$msg= "No Records founds";
else
{
$Url=mysql_result($result,$num-1,"images.Url");
$msg="../Images/".$Url;
}//else
return $msg;
}//end of function
function createAlbumView($albumid,$jumpto)
{
$objResponse = new xajaxResponse();
// how many rows to show per page
$rowsPerPage = 15;
// if $jumpto defined, use it as page number
if($jumpto!="")
$pageNum = $jumpto;
else
// by default show first page
$pageNum = 1;
$start = ($pageNum -1) * $rowsPerPage;
// enter query and display stuff
$query="select * from images ,albumcontainsimages,album where
images.ImageId=albumcontainsimages.ImageId and
albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid limit $start, $rowsPerPage";
$result=mysql_query($query);
$num=mysql_numrows($result);
$msg;
if($num==0)
{$msg= "No Records founds";
$objResponse->addAssign("mytable","innerHTML",$msg);
}
else
{
//display Album Name
$AlbumName= mysql_result($result,0,'album.AlbumName');
//display Creation Date
$Date = mysql_result($result,0,'album.CreationDate');
//display description of album
$des= mysql_result($result,0,'album.Description');
//display no of times viewed
//call function GetViewed($albumid)
//create a table to display album details first
$msg="<table ><tr >";//end of echo
$msg.= "<td class =\"td-thumbnails-navi\">Album Name :$AlbumName</td></tr>";
$msg.= "<tr><td class =\"td-thumbnails-navi\">Created on :$Date</td></tr>";
$msg.= "<tr><td class =\"td-thumbnails-navi\">Description :$des</td></tr>";
$msg.= "</table>";
//create a table to display album pictures now
$msg.="<table class=\"table-wrapper\">";//echo
$msg.="<tr>";//end of echo
for($S=0;$S<$num;$S++)
{ //get path of image
$path="../Images/";
$path .= mysql_result($result,$S,"images.Url");
//get des of image
$imgdescription= mysql_result($result,$S,"images.Description");
//get dateuploaded of image
$dateUploaded=mysql_result($result,$S,"images.DateUploaded");
//get name of image
$ImgName=mysql_result($result,$S,"images.ImageName");
//get datecreated of image
$imageId=mysql_result($result,$S,"images.ImageId");
$msg.="<td>
";
$msg.="<table class=\"table-shadows\" >
<tr>
<td class=\"td-shadows-main\">
<a href=\"ImageZoom.php?ImgId=$imageId\" >";//end of echo
//GetImage path
$msg.="<IMG SRC=\"".$path."\"width=150 height=160
align=bottom alt=$ImgName>
</a>
</td>
<td class=\"td-shadows-right\"></td>
</tr>
<tr>
<td class=\"td-shadows-bottom\"></td>
<td class=\"td-shadows-bottomright\">
</td>
</tr>
</table><!--end of table shadows-->
</td>";//end of echo
//if no if col = 5 then new row
if(($S %4 )==0 &&($S+1)!==1 )
$msg.="</tr><tr>";
}//for
$msg.="</tr><table>";
//############## End of display stuff
// how many rows we have in database
$query="select COUNT(*) AS numrows from images ,albumcontainsimages,album where
images.ImageId=albumcontainsimages.ImageId and
albumcontainsimages.AlbumId=album.AlbumId and album.AlbumId =$albumid ";
$result = mysql_query($query) or die('Error, query failed');
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];
// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
//####################################
// creating 'previous' and 'next' link
if ($pageNum > 1)
{
$page = $pageNum -1;
$prev="<input type=\"button\" name=\"prev\" onclick =\"xajax_createAlbumView($albumid,$page);\" value=\"Prev\">";
$first = "<input type=\"button\" name=\"first\" onclick =\"xajax_createAlbumView($albumid,1);\" value=\"First\">";
}
else
{
$prev = ' '; // we're on page one, don't enable 'previous' link
$first = ' '; // nor 'first page' link
}
// print 'next' link only if we're not
// on the last page
if ($pageNum < $maxPage)
{
$page = $pageNum + 1;
$next = "<input type=\"button\" name=\"next\"onclick=\"xajax_createAlbumView($albumid,$page);\"value=\"Next\">";
$last = "<input type=\"button\" name=\"Last\"onclick=\"xajax_createAlbumView($albumid,$maxPage);\"value=\"Last\">";
}
else
{
$next = ' '; // we're on the last page, don't enable 'next' link
$last = ' '; // nor 'last page' link
}
// print the page navigation link
$msg.=$first . $prev . " Page <strong>$pageNum</strong> of <strong>$maxPage</strong> pages " . $next . $last;
$objResponse->addAssign("mytable","innerHTML",$msg);
//$objResponse->addAssign("but","innerHTML",$but);
}//else
return $objResponse->getXML();
}//end of function
////////////////////////////////
$xajax = new xajax();
$xajax->registerFunction("viewuseralbums");
$xajax->registerFunction("createAlbumView");
$xajax->processRequests();
?>
<html><head><?php $xajax->printJavascript("../"); ?><title>Select Album</title>
<link href="../css/style.css" type="text/css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../icons/spgm_style.css" />
</head><body onload = "xajax_viewuseralbums(<?php echo $memid ; ?>,'');">
<!--Start of footer table-->
<table id="wapper" border=0>
<tr>
<td id="topleft"> </td>
<td id="top"> </td>
<td id="topright"> </td>
</tr>
<tr><td id="left"></td>
<td id="logocenter">
<p><span id="title"> Select Album</span></p>
<div id = "mytable"></div>
</td>
<td id="right"> </td>
</tr>
<tr>
<td id="bottomleft"> </td>
<td id="bottom"> </td>
<td id="bottomright"> </td>
</tr>
</table>
<!--End of footer table-->
<br>
<?php
?>
</body>
</html> | avinash/nuzimazz | Image_edit/SelectAlbum.php | PHP | gpl-2.0 | 11,067 |
package edu.ucsd.ncmir.WIB.client.core.components;
import com.google.gwt.user.client.ui.Widget;
import edu.ucsd.ncmir.WIB.client.core.message.Message;
import edu.ucsd.ncmir.WIB.client.core.message.MessageListener;
import edu.ucsd.ncmir.WIB.client.core.message.MessageManager;
import edu.ucsd.ncmir.WIB.client.core.messages.ResetMessage;
/**
* HorizontalSlider bar.
* @author spl
*/
public class HorizontalSlider
extends SliderHorizontal
implements HorizontalSliderInterface,
MessageListener,
SliderValueUpdateHandler
{
private final Message _message;
/**
* Creates a <code>HorizontalSlider</code> object.
*/
public HorizontalSlider( Message message )
{
super( "150px" );
this._message = message;
super.addSliderValueUpdateHandler( this );
MessageManager.registerListener( ResetMessage.class, this );
}
private int _min_value = 0;
private int _max_value = 1;
private int _default_value = 0;
@Override
public final void setSliderParameters( int min_value, int max_value,
int default_value )
{
this._min_value = min_value;
this._max_value = max_value;
this._default_value = default_value;
this.setMaxValue( this._max_value - this._min_value );
this.setSliderValue( default_value );
super.setMinMarkStep( 1 );
}
@Override
public void setWidth( String size )
{
this._transmit_value = false;
double value = super.getValue();
super.setWidth( size );
super.setValue( value );
this._transmit_value = true;
}
private boolean _transmit_value = true;
/**
* Updates the value of the slider without firing the handler.
* @param value The value to be set.
*/
@Override
public void setSliderValueOnly( int value )
{
// Turn off the handler.
this._transmit_value = false;
this.setSliderValue( value );
this._transmit_value = true;
}
@Override
public void setSliderValue( double value )
{
super.setValue( value - this._min_value );
}
@Override
public void action( Message m, Object o )
{
this.setSliderValue( this._default_value );
}
private boolean _initial = true; // To prevent premature Message firing.
/**
* Fired when the bar value changes.
* @param event The <code>BarValueChangedEvent</code>.
*/
@Override
public void onBarValueChanged( SliderValueUpdateEvent event )
{
if ( this._transmit_value && !this._initial )
this.updateHandler( event.getValue() + this._min_value );
// Turn off the initial flag. The SliderBar object fires a
// spurious BarValueChangedEvent when the object is loaded.
// This prevents it being propagated.
this._initial = false;
}
@Override
public void updateHandler( double value )
{
this._message.send( value );
}
@Override
public Widget widget()
{
return this;
}
@Override
public double getSliderValue()
{
return this.getValue();
}
}
| imclab/WebImageBrowser | WIB/src/java/edu/ucsd/ncmir/WIB/client/core/components/HorizontalSlider.java | Java | gpl-2.0 | 3,160 |
# The absolute path of the main script(p4_tools.rb)
ROOT = File.expand_path('..', File.dirname(__FILE__))
# The absolute path of the folder which contains the command files
COMMANDS_ROOT = ROOT + '/commands'
# The absolute path of the folder which contains the custom command files
CUSTOM_COMMANDS_ROOT = COMMANDS_ROOT + '/custom'
# The absolute path of the folder which contains the configuration files
CONFIG_ROOT = ROOT + '/config'
# Array of command names, read from the COMMAND_ROOT folder
SUB_COMMANDS = Dir[COMMANDS_ROOT + '/*.rb'].collect { |file|
File.basename(file, '.rb')
}
$LOAD_PATH.unshift(CUSTOM_COMMANDS_ROOT, COMMANDS_ROOT) | ncsibra/P4Tools | lib/p4tools/environment.rb | Ruby | gpl-2.0 | 671 |
<?php
include 'init.php';
$output = '';
$setup = new ON_Settings();
$setup->load();
$setup->registerForm('setup');
// fill form with elements
$setup->fillForm();
// process forms if posted
if ($setup->form->isSubmitted() && $setup->form->validate()) {
$values =& $setup->form->exportValues();
$setup->setValues($values);
if($setup->globalid > 0) {
$res = $setup->update();
if ($res) {
ON_Say::add(fmtSuccess(_('Settings updated successfuly')));
$defaults = $setup->defaults();
$setup->form->resetDefaults($defaults);
} else {
ON_Say::add(fmtError(_('Database error: settings update failed')));
}
} else {
$res = $setup->insert();
if ($res) {
ON_Say::add(fmtSuccess(_('Settings inserted successfuly')));
} else {
ON_Say::add(fmtError(_('Database error: settings insert failed')));
}
}
}
$output .= $setup->form->toHtml();
include 'theme.php';
?> | uzaytek/orion | admin/settings-store.php | PHP | gpl-2.0 | 935 |
<?php
/**
* Template Name: Two Column, Right-Sidebar
*
* This is the most generic template file in a WordPress theme
* and one of the two required files for a theme (the other being style.css).
* It is used to display a page when nothing more specific matches a query.
* E.g., it puts together the home page when no home.php file exists.
* Learn more: http://codex.wordpress.org/Template_Hierarchy
*
* @package joe_neat
*/
get_header(); ?>
<div id="primary" class="content-area">
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
/* Include the Post-Format-specific template for the content.
* If you want to override this in a child theme, then include a file
* called content-___.php (where ___ is the Post Format name) and that will be used instead.
*/
get_template_part( 'page-templates/partials/content', 'page' );
?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() ) :
comments_template();
endif;
?>
<?php
endwhile; ?>
<?php else : ?>
<?php get_template_part( 'partials/content', 'none' ); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || '0' != get_comments_number() ) :
comments_template();
endif;
?>
<?php
endif; ?>
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| joseph-jalbert/joe_neat | page-templates/template-right-col.php | PHP | gpl-2.0 | 1,499 |
package org.nla.tarotdroid.lib.helpers;
import static com.google.common.base.Preconditions.checkArgument;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
/**
* Network and internet connexion helper class.
*/
public class ConnexionHelper {
/**
* Checking for all possible internet providers
* **/
public static boolean isConnectedToInternet(Context context) {
checkArgument(context != null, "context is null");
boolean toReturn = false;
ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
toReturn = true;
break;
}
}
return toReturn;
}
} | daffycricket/tarotdroid | tarotDroidUiLib/src/main/java/org/nla/tarotdroid/lib/helpers/ConnexionHelper.java | Java | gpl-2.0 | 1,094 |
<?php
class SatellitePlugin
{
var $plugin_name;
var $plugin_base;
var $pre = 'Satellite';
var $debugging = false;
var $menus = array();
var $latestorbit = 'jquery.orbit-1.3.1.js';
//var $latestorbit = 'orbit-min.js';
var $cssfile = 'orbit-css.php';
var $cssadmin = 'admin-styles.css';
var $sections = array(
'satellite' => 'satellite-slides',
'settings' => 'satellite',
'newgallery' => 'satellite-galleries',
);
var $helpers = array('Ajax', 'Config', 'Db', 'Html', 'Form', 'Metabox', 'Version');
var $models = array('Slide','Gallery');
function register_plugin($name, $base) {
$this->plugin_base = rtrim(dirname($base), DS);
$this->initialize_classes();
$this->initialize_options();
if (function_exists('load_plugin_textdomain')) {
$currentlocale = get_locale();
if (!empty($currentlocale)) {
$moFile = dirname(__FILE__) . DS . "languages" . DS . SATL_PLUGIN_NAME . "-" . $currentlocale . ".mo";
if (@file_exists($moFile) && is_readable($moFile)) {
load_textdomain(SATL_PLUGIN_NAME, $moFile);
}
}
}
if ($this->debugging == true) {
global $wpdb;
$wpdb->show_errors();
error_reporting(E_ALL);
@ini_set('display_errors', 1);
}
$this->add_action('wp_head', 'enqueue_scripts', 1);
$this->add_action('admin_head', 'add_admin_styles');
$this->add_action("admin_head", 'plupload_admin_head');
$this->add_action('admin_init', 'admin_scripts');
$this->add_filter('the_posts', 'conditionally_add_scripts_and_styles'); // the_posts gets triggered before wp_head
$this->add_action('wp_ajax_plupload_action', "g_plupload_action");
return true;
}
function add_admin_styles() {
$adminStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssadmin . '?v=' . SATL_VERSION;
wp_register_style(SATL_PLUGIN_NAME . "_adstyle", $adminStyleUrl);
wp_enqueue_style(SATL_PLUGIN_NAME . "_adstyle");
}
function conditionally_add_scripts_and_styles($posts){
if (empty($posts)) return $posts;
$shortcode_found = false; // use this flag to see if styles and scripts need to be enqueued
if ($this->get_option('shortreq') == 'N') { $shortcode_found = true; }
else {
foreach ($posts as $post) {
if ( ( stripos($post->post_content, '[gpslideshow') !== false ) ||
( stripos($post->post_content, '[satellite') !== false) ||
( stripos($post->post_content, '[slideshow') !== false && $this->get_option('embedss') == "Y" )
) {
$shortcode_found = true; // bingo!
$pID = $post->ID;
break;
}
}
}
if ($shortcode_found) {
$satlStyleFile = SATL_PLUGIN_DIR . '/css/' . $this -> cssfile;
$satlStyleUrl = SATL_PLUGIN_URL . '/css/' . $this -> cssfile . '?v=' . SATL_VERSION . '&pID=' . $pID;
if ($_SERVER['HTTPS']) {
$satlStyleUrl = str_replace("http:", "https:", $satlStyleUrl);
}
//$infogal = $this;
if (file_exists($satlStyleFile)) {
if ($styles = $this->get_option('styles')) {
foreach ($styles as $skey => $sval) {
$satlStyleUrl .= "&" . $skey . "=" . urlencode($sval);
}
}
$width_temp = $this->get_option('width_temp');
$height_temp = $this->get_option('height_temp');
$align_temp = $this->get_option('align_temp');
$nav_temp = $this->get_option('nav_temp');
//print_r($wp_query->current_post);
if (is_array($width_temp)) {
foreach ($width_temp as $skey => $sval) {
if ($skey == $pID)
$satlStyleUrl .= "&width_temp=" . urlencode($sval);
}
}
if (is_array($height_temp)) {
foreach ($height_temp as $skey => $sval) {
if ($skey == $pID)
$satlStyleUrl .= "&height_temp=" . urlencode($sval);
}
}
if (is_array($align_temp)) {
foreach ($align_temp as $skey => $sval) {
if ($skey == $pID)
$satlStyleUrl .= "&align=" . urlencode($sval);
}
}
if (is_array($nav_temp)) {
foreach ($nav_temp as $skey => $sval) {
if ($skey == $pID)
$satlStyleUrl .= "&nav=" . urlencode($sval);
}
}
wp_register_style(SATL_PLUGIN_NAME . "_style", $satlStyleUrl);
}
// enqueue here
wp_enqueue_style(SATL_PLUGIN_NAME . "_style");
wp_enqueue_script(SATL_PLUGIN_NAME . "_script", '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/' . $this->latestorbit,
array('jquery'),
SATL_VERSION);
//wp_enqueue_script(SATL_PLUGIN_NAME . "_script");
}
return $posts;
}
function init_class($name = null, $params = array()) {
if (!empty($name)) {
$name = $this->pre . $name;
if (class_exists($name)) {
if ($class = new $name($params)) {
return $class;
}
}
}
$this->init_class('Country');
return false;
}
function initialize_classes() {
if (!empty($this->helpers)) {
foreach ($this->helpers as $helper) {
$hfile = dirname(__FILE__) . DS . 'helpers' . DS . strtolower($helper) . '.php';
if (file_exists($hfile)) {
require_once($hfile);
if (empty($this->{$helper}) || !is_object($this->{$helper})) {
$classname = $this->pre . $helper . 'Helper';
if (class_exists($classname)) {
$this->{$helper} = new $classname;
}
}
}
}
}
if (!empty($this->models)) {
foreach ($this->models as $model) {
$mfile = dirname(__FILE__) . DS . 'models' . DS . strtolower($model) . '.php';
if (file_exists($mfile)) {
require_once($mfile);
if (empty($this->{$model}) || !is_object($this->{$model})) {
$classname = $this->pre . $model;
if (class_exists($classname)) {
$this->{$model} = new $classname;
}
}
}
}
}
}
function initialize_options() {
$styles = array(
'width' => "450",
'height' => "300",
'thumbheight' => "75",
'thumbarea' => "275",
'thumbareamargin' => "30",
'thumbmargin' => "2",
'thumbspacing' => "5",
'thumbactive' => "#FFFFFF",
'thumbopacity' => "70",
'align' => "none",
'border' => "1px solid #CCCCCC",
'background' => "#000000",
'infotitle' => "2",
'infobackground' => "#000000",
'infocolor' => "#FFFFFF",
'playshow' => "A",
'navpush' => "0",
'infomin' => "Y"
);
$this->add_option('styles', $styles);
//General Settings
$this->add_option('fadespeed', 10);
$this->add_option('nav_opacity', 30);
$this->add_option('navhover', 70);
$this->add_option('nolinker', "N");
$this->add_option('nolinkpage', 0);
$this->add_option('pagelink', "S");
$this->add_option('wpattach', "N");
$this->add_option('captionlink', "N");
$this->add_option('transition', "FB");
$this->add_option('information', "Y");
$this->add_option('infospeed', 10);
$this->add_option('showhover', "P");
$this->add_option('thumbnails', "N");
$this->add_option('thumbposition', "bottom");
$this->add_option('thumbscrollspeed', 5);
$this->add_option('autoslide', "Y");
$this->add_option('autoslide_temp', "Y");
$this->add_option('imagesbox', "T");
$this->add_option('autospeed', 10);
$this->add_option('abscenter', "Y");
$this->add_option('embedss', "Y");
$this->add_option('satwiz', "Y");
$this->add_option('shortreq', "Y");
$this->add_option('ggljquery', "Y");
$this->add_option('splash', "N");
$this->add_option('stldb_version', "1.0");
// Orbit Only
$this->add_option('autospeed2', 5000);
$this->add_option('duration', 700);
$this->add_option('othumbs', "B");
$this->add_option('bullcenter', "true");
//Multi-ImageSlide
$this->add_option('multicols', 3);
$this->add_option('dropshadow', 'N');
//Full Right / Left
$this->add_option('thumbarea', 250);
//Premium
$this->add_option('custslide', 10);
$this->add_option('preload', 'N');
$this->add_option('keyboard', 'N');
$this->add_option('manager', 'manage_options');
$this->add_option('nav', "on");
//$this->add_option('orbitinfo', 'Y');
//$this->add_option('orbitinfo_temp', 'Y');
}
function render_msg($message = '') {
$this->render('msg-top', array('message' => $message), true, 'admin');
}
function render_err($message = '') {
$this->render('err-top', array('message' => $message), true, 'admin');
}
function redirect($location = '', $msgtype = '', $message = '') {
$url = $location;
if ($msgtype == "message") {
$url .= '&' . $this->pre . 'updated=true';
} elseif ($msgtype == "error") {
$url .= '&' . $this->pre . 'error=true';
}
if (!empty($message)) {
$url .= '&' . $this->pre . 'message=' . urlencode($message);
}
?>
<script type="text/javascript">
window.location = '<?php echo (empty($url)) ? get_option('home') : $url; ?>';
</script>
<?php
flush();
}
function paginate($model = null, $fields = '*', $sub = null, $conditions = null, $searchterm = null, $per_page = 10, $order = array('modified', "DESC")) {
global $wpdb;
if (!empty($model)) {
global $paginate;
$paginate = $this->vendor('Paginate');
$paginate->table = $this->{$model}->table;
$paginate->sub = (empty($sub)) ? $this->{$model}->controller : $sub;
$paginate->fields = (empty($fields)) ? '*' : $fields;
$paginate->where = (empty($conditions)) ? false : $conditions;
$paginate->searchterm = (empty($searchterm)) ? false : $searchterm;
$paginate->per_page = $per_page;
$paginate->order = $order;
$data = $paginate->start_paging($_GET[$this->pre . 'page']);
if (!empty($data)) {
$newdata = array();
foreach ($data as $record) {
$newdata[] = $this->init_class($model, $record);
}
$data = array();
$data[$model] = $newdata;
$data['Paginate'] = $paginate;
}
return $data;
}
return false;
}
function vendor($name = '', $folder = '') {
if (!empty($name)) {
$filename = 'class.' . strtolower($name) . '.php';
$filepath = rtrim(dirname(__FILE__), DS) . DS . 'vendors' . DS . $folder . '';
$filefull = $filepath . $filename;
if (file_exists($filefull)) {
require_once($filefull);
$class = 'Satellite' . $name;
if (${$name} = new $class) {
return ${$name};
}
}
}
return false;
}
function check_uploaddir() {
if (!file_exists(SATL_UPLOAD_DIR)) {
if (@mkdir(SATL_UPLOAD_DIR, 0777)) {
@chmod(SATL_UPLOAD_DIR, 0755);
return true;
} else {
$message = __('Uploads folder named "' . SATL_PLUGIN_NAME . '" cannot be created inside "' . SATL_UPLOAD_DIR, SATL_PLUGIN_NAME);
$this->render_msg($message);
}
}
return false;
}
function check_sgprodir() {
$sgprodir = SATL_UPLOAD_DIR.'/../slideshow-gallery-pro/';
if (file_exists($sgprodir) && $this->is_empty_folder(SATL_UPLOAD_DIR)) {
if ($this->is_empty_folder($sgprodir)) {
return false;
}
$message = __('Transitioning from <strong>Slideshow Gallery Pro</strong>? <a href="admin.php?page=satellite-slides&method=copysgpro">Copy Files</a> from your previous custom galleries', SATL_PLUGIN_NAME);
$this->render_msg($message);
}
return false;
}
function is_empty_folder($folder){
$c=0;
if(is_dir($folder) ){
$files = opendir($folder);
while ($file=readdir($files)){$c++;}
if ($c>2){
return false;
}else{
return true;
}
}
}
function add_action($action, $function = null, $priority = 10, $params = 1) {
if (add_action($action, array($this, (empty($function)) ? $action : $function), $priority, $params)) {
return true;
}
return false;
}
function add_filter($filter, $function = null, $priority = 10, $params = 1) {
if (add_filter($filter, array($this, (empty($function)) ? $filter : $function), $priority, $params)) {
return true;
}
return false;
}
function admin_scripts() {
if (!empty($_GET['page']) && in_array($_GET['page'], (array) $this->sections)) {
wp_enqueue_script('autosave');
if ($_GET['page'] == 'satellite') {
wp_enqueue_script('common');
wp_enqueue_script('wp-lists');
wp_enqueue_script('postbox');
wp_enqueue_script('settings-editor', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/settings-editor.js', array('jquery'), SATL_VERSION);
wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION);
}
if ($_GET['page'] == "satellite-slides" && $_GET['method'] == "order") {
wp_enqueue_script('jquery-ui-sortable');
}
if ($_GET['page'] == "satellite-galleries") {
wp_enqueue_script('plupload-all');
wp_enqueue_script('jquery-ui-sortable');
wp_enqueue_script('admin', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/js/admin.js', array('jquery'), SATL_VERSION);
}
wp_enqueue_scripts();
//wp_enqueue_script('jquery-ui-sortable');
add_thickbox();
}
}
function enqueue_scripts() {
if ($this->get_option('ggljquery') == "Y") {
wp_deregister_script( 'jquery' );
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
}
wp_enqueue_script('jquery');
if (SATL_PRO && ($this->get_option('preload') == 'Y')) {
wp_register_script('satellite_preloader', '/' . PLUGINDIR . '/' . SATL_PLUGIN_NAME . '/pro/preloader.js');
wp_enqueue_script('satellite_preloader');
}
if ($this->get_option('imagesbox') == "T")
add_thickbox();
return true;
}
function plupload_admin_head() {
//Thank you Krishna!! http://www.krishnakantsharma.com/
// place js config array for plupload
$plupload_init = array(
'runtimes' => 'html5,silverlight,flash,html4',
'browse_button' => 'plupload-browse-button', // will be adjusted per uploader
'container' => 'plupload-upload-ui', // will be adjusted per uploader
'drop_element' => 'drag-drop-area', // will be adjusted per uploader
'file_data_name' => 'async-upload', // will be adjusted per uploader
'multiple_queues' => true,
'max_file_size' => wp_max_upload_size() . 'b',
'url' => admin_url('admin-ajax.php'),
'flash_swf_url' => includes_url('js/plupload/plupload.flash.swf'),
'silverlight_xap_url' => includes_url('js/plupload/plupload.silverlight.xap'),
'filters' => array(array('title' => __('Allowed Files'), 'extensions' => '*')),
'multipart' => true,
'urlstream_upload' => true,
'multi_selection' => false, // will be added per uploader
// additional post data to send to our ajax hook
'multipart_params' => array(
'_ajax_nonce' => "", // will be added per uploader
'action' => 'plupload_action', // the ajax action name
'imgid' => 0 // will be added per uploader
)
);
?>
<script type="text/javascript">
var base_plupload_config=<?php echo json_encode($plupload_init); ?>;
</script>
<?php
}
function g_plupload_action() {
// check ajax noonce
$imgid = $_POST["imgid"];
check_ajax_referer($imgid . 'pluploadan');
// handle file upload
$status = wp_handle_upload($_FILES[$imgid . 'async-upload'], array('test_form' => true, 'action' => 'plupload_action'));
// send the uploaded file url in response
echo $status['url'];
exit;
}
function plugin_base() {
return rtrim(dirname(__FILE__), '/');
}
function url() {
return rtrim(WP_PLUGIN_URL, '/') . '/' . substr(preg_replace("/\\" . DS . "/si", "/", $this->plugin_base()), strlen(ABSPATH));
}
function add_option($name = '', $value = '') {
if (add_option($this->pre . $name, $value)) {
return true;
}
return false;
}
function update_option($name = '', $value = '') {
if (update_option($this->pre . $name, $value)) {
return true;
}
return false;
}
function get_option($name = '', $stripslashes = true) {
if ($option = get_option($this->pre . $name)) {
if (@unserialize($option) !== false) {
return unserialize($option);
}
if ($stripslashes == true) {
$option = stripslashes_deep($option);
}
return $option;
}
return false;
}
function debug($var = array()) {
if ($this->debugging) {
echo '<pre>' . print_r($var, true) . '</pre>';
return true;
}
return false;
}
function check_table( $model = null ) {
global $wpdb;
if ( !empty($model) ) {
if ( !empty($this->fields) && is_array($this->fields ) ) {
if ( /* !$wpdb->get_var("SHOW TABLES LIKE '" . $this->table . "'") ||*/ $this->get_option($model.'db_version') != SATL_VERSION ) {
$query = "CREATE TABLE " . $this->table . " (\n";
$c = 1;
foreach ( $this->fields as $field => $attributes ) {
if ( $field != "key" ) {
$query .= "`" . $field . "` " . $attributes . "";
//$query .= "`".$field . "` " . $attributes ;
} else {
$query .= "" . $attributes . "";
}
if ($c < count($this->fields)) {
$query .= ",\n";
}
$c++;
}
$query .= ");";
if (!empty($query)) {
$this->table_query[] = $query;
}
if (SATL_PRO) {
if ( class_exists( 'SatellitePremium' ) ) {
$satlprem = new SatellitePremium;
$satlprem->check_pro_dirs();
}
}
if (!empty($this->table_query)) {
require_once(ABSPATH . 'wp-admin'.DS.'includes'.DS.'upgrade.php');
dbDelta($this->table_query, true);
$this -> update_option($model.'db_version', SATL_VERSION);
$this -> update_option('stldb_version', SATL_VERSION);
error_log("Updated slideshow satellite databases");
}
} else {
//echo "this model db version: ".$this->get_option($model.'db_version');
$field_array = $this->get_fields($this->table);
foreach ($this->fields as $field => $attributes) {
if ($field != "key") {
$this->add_field($this->table, $field, $attributes);
}
}
}
}
}
return false;
}
function get_fields($table = null) {
global $wpdb;
if (!empty($table)) {
$fullname = $table;
if (($tablefields = mysql_list_fields(DB_NAME, $fullname, $wpdb->dbh)) !== false) {
$columns = mysql_num_fields($tablefields);
$field_array = array();
for ($i = 0; $i < $columns; $i++) {
$fieldname = mysql_field_name($tablefields, $i);
$field_array[] = $fieldname;
}
return $field_array;
}
}
return false;
}
function delete_field($table = '', $field = '') {
global $wpdb;
if (!empty($table)) {
if (!empty($field)) {
$query = "ALTER TABLE `" . $wpdb->prefix . "" . $table . "` DROP `" . $field . "`";
if ($wpdb->query($query)) {
return false;
}
}
}
return false;
}
function change_field($table = '', $field = '', $newfield = '', $attributes = "TEXT NOT NULL") {
global $wpdb;
if (!empty($table)) {
if (!empty($field)) {
if (!empty($newfield)) {
$field_array = $this->get_fields($table);
if (!in_array($field, $field_array)) {
if ($this->add_field($table, $newfield)) {
return true;
}
} else {
$query = "ALTER TABLE `" . $table . "` CHANGE `" . $field . "` `" . $newfield . "` " . $attributes . ";";
if ($wpdb->query($query)) {
return true;
}
}
}
}
}
return false;
}
function add_field($table = '', $field = '', $attributes = "TEXT NOT NULL") {
global $wpdb;
if (!empty($table)) {
if (!empty($field)) {
$field_array = $this->get_fields($table);
if (!empty($field_array)) {
if (!in_array($field, $field_array)) {
$query = "ALTER TABLE `" . $table . "` ADD `" . $field . "` " . $attributes . ";";
if ($wpdb->query($query)) {
return true;
}
}
}
}
}
return false;
}
function render($file = '', $params = array(), $output = true, $folder = 'admin') {
if (!empty($file)) {
$filename = $file . '.php';
$filepath = $this->plugin_base() . DS . 'views' . DS . $folder . DS;
$filefull = $filepath . $filename;
if (file_exists($filefull)) {
if (!empty($params)) {
foreach ($params as $pkey => $pval) {
${$pkey} = $pval;
}
}
if ($output == false) {
ob_start();
}
include($filefull);
if ($output == false) {
$data = ob_get_clean();
return $data;
} else {
flush();
return true;
}
}
}
return false;
}
/**
* Add Settings link to plugins - code from GD Star Ratings
*/
function add_satl_settings_link($links, $file) {
static $this_plugin;
if (!$this_plugin)
$this_plugin = plugin_basename(__FILE__);
if ($file == $this_plugin) {
$settings_link = '<a href="admin.php?page=satellite">' . __("Settings", SATL_PLUGIN_NAME) . '</a>';
array_unshift($links, $settings_link);
}
return $links;
}
}
?>
| diegorojas/encontros.maracatu.org.br | wp-content/plugins/slideshow-satellite/slideshow-satellite-plugin.php | PHP | gpl-2.0 | 26,130 |
# -*- coding: UTF-8 -*-
#/*
# * Copyright (C) 2011 Ivo Brhel
# *
# *
# * 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, 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; see the file COPYING. If not, write to
# * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
# * http://www.gnu.org/copyleft/gpl.html
# *
# */
import re,os,urllib,urllib2,cookielib
import util,resolver
from provider import ContentProvider
class HejbejseContentProvider(ContentProvider):
def __init__(self,username=None,password=None,filter=None):
ContentProvider.__init__(self,'hejbejse.tv','http://www.kynychova-tv.cz/',username,password,filter)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.LWPCookieJar()))
urllib2.install_opener(opener)
def capabilities(self):
return ['resolve','categories','list']
def categories(self):
page = util.parse_html('http://www.kynychova-tv.cz/index.php?id=5')
result = []
for title,uri in [(x.h3.text,x.h3.a['href']) for x in page.select('div.entry5') if x.h3]:
item = self.dir_item()
item['title'] = title
item['url'] = uri
result.append(item)
return result
def list(self, url):
url = self._url(url)
page = util.parse_html(url)
result = []
for title,uri in [(x.img['title'],x['href']) for x in page.select('div.entry3')[0].findAll('a')]:
item = self.video_item()
item['title'] = title
item['url'] = uri
result.append(item)
return result
def resolve(self,item,captcha_cb=None,select_cb=None):
item = item.copy()
url = self._url(item['url'])
page = util.parse_html(url)
result = []
data=str(page.select('div.entry3 > center')[0])
resolved = resolver.findstreams(data,['<iframe(.+?)src=[\"\'](?P<url>.+?)[\'\"]'])
try:
for i in resolved:
item = self.video_item()
item['title'] = i['name']
item['url'] = i['url']
item['quality'] = i['quality']
item['surl'] = i['surl']
result.append(item)
except:
print '===Unknown resolver==='
if len(result)==1:
return result[0]
elif len(result) > 1 and select_cb:
return select_cb(result)
| kodi-czsk/plugin.video.hejbejse.tv | resources/lib/hejbejse.py | Python | gpl-2.0 | 2,611 |
<?php
/**
* Template Name: Full Width Blog
*
* The template for displaying content in full width with no sidebars.
*
*
* @package blogBox WordPress Theme
* @copyright Copyright (c) 2012, Kevin Archibald
* @license http://www.gnu.org/licenses/quick-guide-gplv3.html GNU Public License
* @author Kevin Archibald <www.kevinsspace.ca/contact/>
*/
?>
<?php get_header(); ?>
<div id="fullwidth">
<h2 class="fullwidth_blog_title"><?php the_title(); ?></h2>
<div id="home1post">
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div class="post">
<div class="entry">
<?php the_content('Read more'); ?>
</div>
</div>
<?php endwhile; else : endif; ?>
</div>
<div id="fullwidth_blog">
<?php
$exclude_categories = blogBox_exclude_categories();
$temp = $wp_query;
$wp_query = null;
$wp_query = new WP_Query();
$wp_query->query('cat='.$exclude_categories.'&paged='.$paged);
if ($wp_query->have_posts()) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php
global $more;
$more = 0;
blogBox_post_format();
?>
</div>
<?php endwhile; ?>
<?php if(function_exists('wp_pagenavi')) {
echo '<div class="postpagenav">';
wp_pagenavi();
echo '</div>';
} else { ?>
<div class="postpagenav">
<div class="left"><?php next_posts_link(__('<< older entries','blogBox') ); ?></div>
<div class="right"><?php previous_posts_link(__(' newer entries >>','blogBox') ); ?></div>
<br/>
</div>
<?php } ?>
<?php $wp_query = null; $wp_query = $temp;?>
<?php else : ?>
<?php endif; ?>
<br/>
</div>
</div>
<?php get_footer(); ?> | aliuwahab/saveghana | wp-content/themes/blogbox/page-full_width_blog.php | PHP | gpl-2.0 | 1,734 |
<?php
/**
* The template for displaying 404 pages (not found)
*
* @link https://codex.wordpress.org/Creating_an_Error_404_Page
*
* @package wapp
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<section class="error-404 not-found">
<header class="page-header">
<h1 class="page-title"><?php esc_html_e( 'Oops! That page can’t be found.', 'wapp' ); ?></h1>
</header><!-- .page-header -->
<div class="page-content">
<p><?php esc_html_e( 'It looks like nothing was found at this location. Maybe try one of the links below or a search?', 'wapp' ); ?></p>
<?php
get_search_form();
the_widget( 'WP_Widget_Recent_Posts' );
// Only show the widget if site has multiple categories.
if ( wapp_categorized_blog() ) :
?>
<div class="widget widget_categories">
<h2 class="widget-title"><?php esc_html_e( 'Most Used Categories', 'wapp' ); ?></h2>
<ul>
<?php
wp_list_categories( array(
'orderby' => 'count',
'order' => 'DESC',
'show_count' => 1,
'title_li' => '',
'number' => 10,
) );
?>
</ul>
</div><!-- .widget -->
<?php
endif;
/* translators: %1$s: smiley */
$archive_content = '<p>' . sprintf( esc_html__( 'Try looking in the monthly archives. %1$s', 'wapp' ), convert_smilies( ':)' ) ) . '</p>';
the_widget( 'WP_Widget_Archives', 'dropdown=1', "after_title=</h2>$archive_content" );
the_widget( 'WP_Widget_Tag_Cloud' );
?>
</div><!-- .page-content -->
</section><!-- .error-404 -->
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
| Headlab/wapp | 404.php | PHP | gpl-2.0 | 1,741 |
/****************************************************************************
*
* $Id: vpHinkley.cpp 4056 2013-01-05 13:04:42Z fspindle $
*
* This file is part of the ViSP software.
* Copyright (C) 2005 - 2013 by INRIA. All rights reserved.
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.txt at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using ViSP with software that can not be combined with the GNU
* GPL, please contact INRIA about acquiring a ViSP Professional
* Edition License.
*
* See http://www.irisa.fr/lagadic/visp/visp.html for more information.
*
* This software was developed at:
* INRIA Rennes - Bretagne Atlantique
* Campus Universitaire de Beaulieu
* 35042 Rennes Cedex
* France
* http://www.irisa.fr/lagadic
*
* If you have questions regarding the use of this file, please contact
* INRIA at visp@inria.fr
*
* This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
* WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
*
* Description:
* Hinkley's cumulative sum test implementation.
*
* Authors:
* Fabien Spindler
*
*****************************************************************************/
/*!
\file vpHinkley.cpp
\brief Definition of the vpHinkley class corresponding to the Hinkley's
cumulative sum test.
*/
#include <visp/vpHinkley.h>
#include <visp/vpDebug.h>
#include <visp/vpIoTools.h>
#include <visp/vpMath.h>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <cmath> // std::fabs
#include <limits> // numeric_limits
/* VP_DEBUG_MODE fixed by configure:
1:
2:
3: Print data
*/
/*!
Constructor.
Call init() to initialise the Hinkley's test and set \f$\alpha\f$
and \f$\delta\f$ to default values.
By default \f$ \delta = 0.2 \f$ and \f$ \alpha = 0.2\f$. Use
setDelta() and setAlpha() to modify these values.
*/
vpHinkley::vpHinkley()
{
init();
setAlpha(0.2);
setDelta(0.2);
}
/*!
Constructor.
Call init() to initialise the Hinkley's test and set \f$\alpha\f$
and \f$\delta\f$ thresholds.
\param alpha : \f$\alpha\f$ is a predefined threshold.
\param delta : \f$\delta\f$ denotes the jump minimal magnitude that
we want to detect.
\sa setAlpha(), setDelta()
*/
vpHinkley::vpHinkley(double alpha, double delta)
{
init();
setAlpha(alpha);
setDelta(delta);
}
/*!
Call init() to initialise the Hinkley's test and set \f$\alpha\f$
and \f$\delta\f$ thresholds.
\param alpha : \f$\alpha\f$ is a predefined threshold.
\param delta : \f$\delta\f$ denotes the jump minimal magnitude that
we want to detect.
\sa setAlpha(), setDelta()
*/
void
vpHinkley::init(double alpha, double delta)
{
init();
setAlpha(alpha);
setDelta(delta);
}
/*!
Destructor.
*/
vpHinkley::~vpHinkley()
{
}
/*!
Initialise the Hinkley's test by setting the mean signal value
\f$m_0\f$ to zero as well as \f$S_k, M_k, T_k, N_k\f$.
*/
void vpHinkley::init()
{
nsignal = 0;
mean = 0.0;
Sk = 0;
Mk = 0;
Tk = 0;
Nk = 0;
}
/*!
Set the value of \f$\delta\f$, the jump minimal magnetude that we want to
detect.
\sa setAlpha()
*/
void vpHinkley::setDelta(double delta)
{
dmin2 = delta / 2;
}
/*!
Set the value of \f$\alpha\f$, a predefined threshold.
\sa setDelta()
*/
void vpHinkley::setAlpha(double alpha)
{
this->alpha = alpha;
}
/*!
Perform the Hinkley test. A downward jump is detected if
\f$ M_k - S_k > \alpha \f$.
\param signal : Observed signal \f$ s(t) \f$.
\sa setDelta(), setAlpha(), testUpwardJump()
*/
vpHinkley::vpHinkleyJumpType vpHinkley::testDownwardJump(double signal)
{
vpHinkleyJumpType jump = noJump;
nsignal ++; // Signal length
if (nsignal == 1) mean = signal;
// Calcul des variables cumulées
computeSk(signal);
computeMk();
vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2
<< " signal: " << signal << " Sk: " << Sk << " Mk: " << Mk;
// teste si les variables cumulées excèdent le seuil
if ((Mk - Sk) > alpha)
jump = downwardJump;
#ifdef VP_DEBUG
if (VP_DEBUG_MODE >=2) {
switch(jump) {
case noJump:
std::cout << "noJump " << std::endl;
break;
case downwardJump:
std::cout << "downWardJump " << std::endl;
break;
case upwardJump:
std::cout << "upwardJump " << std::endl;
break;
}
}
#endif
computeMean(signal);
if (jump == downwardJump) {
vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n";
Sk = 0; Mk = 0; nsignal = 0;
}
return (jump);
}
/*!
Perform the Hinkley test. An upward jump is detected if \f$ T_k - N_k >
\alpha \f$.
\param signal : Observed signal \f$ s(t) \f$.
\sa setDelta(), setAlpha(), testDownwardJump()
*/
vpHinkley::vpHinkleyJumpType vpHinkley::testUpwardJump(double signal)
{
vpHinkleyJumpType jump = noJump;
nsignal ++; // Signal length
if (nsignal == 1) mean = signal;
// Calcul des variables cumulées
computeTk(signal);
computeNk();
vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2
<< " signal: " << signal << " Tk: " << Tk << " Nk: " << Nk;
// teste si les variables cumulées excèdent le seuil
if ((Tk - Nk) > alpha)
jump = upwardJump;
#ifdef VP_DEBUG
if (VP_DEBUG_MODE >= 2) {
switch(jump) {
case noJump:
std::cout << "noJump " << std::endl;
break;
case downwardJump:
std::cout << "downWardJump " << std::endl;
break;
case upwardJump:
std::cout << "upWardJump " << std::endl;
break;
}
}
#endif
computeMean(signal);
if (jump == upwardJump) {
vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n";
Tk = 0; Nk = 0; nsignal = 0;
}
return (jump);
}
/*!
Perform the Hinkley test. A downward jump is detected if \f$ M_k - S_k >
\alpha \f$. An upward jump is detected if \f$ T_k - N_k > \alpha \f$.
\param signal : Observed signal \f$ s(t) \f$.
\sa setDelta(), setAlpha(), testDownwardJump(), testUpwardJump()
*/
vpHinkley::vpHinkleyJumpType vpHinkley::testDownUpwardJump(double signal)
{
vpHinkleyJumpType jump = noJump;
nsignal ++; // Signal length
if (nsignal == 1) mean = signal;
// Calcul des variables cumulées
computeSk(signal);
computeTk(signal);
computeMk();
computeNk();
vpCDEBUG(2) << "alpha: " << alpha << " dmin2: " << dmin2
<< " signal: " << signal
<< " Sk: " << Sk << " Mk: " << Mk
<< " Tk: " << Tk << " Nk: " << Nk << std::endl;
// teste si les variables cumulées excèdent le seuil
if ((Mk - Sk) > alpha)
jump = downwardJump;
else if ((Tk - Nk) > alpha)
jump = upwardJump;
#ifdef VP_DEBUG
if (VP_DEBUG_MODE >= 2) {
switch(jump) {
case noJump:
std::cout << "noJump " << std::endl;
break;
case downwardJump:
std::cout << "downWardJump " << std::endl;
break;
case upwardJump:
std::cout << "upwardJump " << std::endl;
break;
}
}
#endif
computeMean(signal);
if ((jump == upwardJump) || (jump == downwardJump)) {
vpCDEBUG(2) << "\n*** Reset the Hinkley test ***\n";
Sk = 0; Mk = 0; Tk = 0; Nk = 0; nsignal = 0;
// Debut modif FS le 03/09/2003
mean = signal;
// Fin modif FS le 03/09/2003
}
return (jump);
}
/*!
Compute the mean value \f$m_0\f$ of the signal. The mean value must be
computed before the jump is estimated on-line.
\param signal : Observed signal \f$ s(t) \f$.
*/
void vpHinkley::computeMean(double signal)
{
// Debut modif FS le 03/09/2003
// Lors d'une chute ou d'une remontée lente du signal, pariculièrement
// après un saut, la moyenne a tendance à "dériver". Pour réduire ces
// dérives de la moyenne, elle n'est remise à jour avec la valeur
// courante du signal que si un début de saut potentiel n'est pas détecté.
//if ( ((Mk-Sk) == 0) && ((Tk-Nk) == 0) )
if ( ( std::fabs(Mk-Sk) <= std::fabs(vpMath::maximum(Mk,Sk))*std::numeric_limits<double>::epsilon() )
&&
( std::fabs(Tk-Nk) <= std::fabs(vpMath::maximum(Tk,Nk))*std::numeric_limits<double>::epsilon() ) )
// Fin modif FS le 03/09/2003
// Mise a jour de la moyenne.
mean = (mean * (nsignal - 1) + signal) / (nsignal);
}
/*!
Compute \f$S_k = \sum_{t=0}^{k} (s(t) - m_0 + \frac{\delta}{2})\f$
\param signal : Observed signal \f$ s(t) \f$.
*/
void vpHinkley::computeSk(double signal)
{
// Calcul des variables cumulées
Sk += signal - mean + dmin2;
}
/*!
Compute \f$M_k\f$, the maximum value of \f$S_k\f$.
*/
void vpHinkley::computeMk()
{
if (Sk > Mk) Mk = Sk;
}
/*!
Compute \f$T_k = \sum_{t=0}^{k} (s(t) - m_0 - \frac{\delta}{2})\f$
\param signal : Observed signal \f$ s(t) \f$.
*/
void vpHinkley::computeTk(double signal)
{
// Calcul des variables cumulées
Tk += signal - mean - dmin2;
}
/*!
Compute \f$N_k\f$, the minimum value of \f$T_k\f$.
*/
void vpHinkley::computeNk()
{
if (Tk < Nk) Nk = Tk;
}
void vpHinkley::print(vpHinkley::vpHinkleyJumpType jump)
{
switch(jump)
{
case noJump :
std::cout << " No jump detected " << std::endl ;
break ;
case downwardJump :
std::cout << " Jump downward detected " << std::endl ;
break ;
case upwardJump :
std::cout << " Jump upward detected " << std::endl ;
break ;
default:
std::cout << " Jump detected " << std::endl ;
break ;
}
}
| thomas-moulard/visp-deb | src/math/misc/vpHinkley.cpp | C++ | gpl-2.0 | 9,567 |
<?php
/**
* The template for displaying all single posts.
*
* @package srh_framework
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'single' ); ?>
<?php the_post_navigation(); ?>
<?php
// If comments are open or we have at least one comment, load up the comment template
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
?>
<?php endwhile; // end of the loop. ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
| jamiebrwr/srh-theme-framework | single.php | PHP | gpl-2.0 | 678 |
//: containers/MapDataTest.java
package course.containers; /* Added by Eclipse.py */
import java.util.*;
import net.mindview.util.*;
import static net.mindview.util.Print.*;
class Letters implements Generator<Pair<Integer,String>>,
Iterable<Integer> {
private int size = 9;
private int number = 1;
private char letter = 'A';
public Pair<Integer,String> next() {
return new Pair<Integer,String>(
number++, "" + letter++);
}
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
public Integer next() { return number++; }
public boolean hasNext() { return number < size; }
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
public class MapDataTest {
public static void main(String[] args) {
// Pair Generator:
print(MapData.map(new Letters(), 11));
// Two separate generators:
print(MapData.map(new CountingGenerator.Character(),
new RandomGenerator.String(3), 8));
// A key Generator and a single value:
print(MapData.map(new CountingGenerator.Character(),
"Value", 6));
// An Iterable and a value Generator:
print(MapData.map(new Letters(),
new RandomGenerator.String(3)));
// An Iterable and a single value:
print(MapData.map(new Letters(), "Pop"));
}
} /* Output:
{1=A, 2=B, 3=C, 4=D, 5=E, 6=F, 7=G, 8=H, 9=I, 10=J, 11=K}
{a=YNz, b=brn, c=yGc, d=FOW, e=ZnT, f=cQr, g=Gse, h=GZM}
{a=Value, b=Value, c=Value, d=Value, e=Value, f=Value}
{1=mJM, 2=RoE, 3=suE, 4=cUO, 5=neO, 6=EdL, 7=smw, 8=HLG}
{1=Pop, 2=Pop, 3=Pop, 4=Pop, 5=Pop, 6=Pop, 7=Pop, 8=Pop}
*///:~
| fengzhongdege/TIJ4 | src/main/java/course/containers/MapDataTest.java | Java | gpl-2.0 | 1,677 |
<?php
class Listify_Template_Page_Templates {
public function __construct() {
add_filter( 'theme_page_templates', array( $this, 'visual_composer' ) );
}
public function visual_composer( $page_templates ) {
if ( listify_has_integration( 'visual-composer' ) ) {
return $page_templates;
}
unset( $page_templates[ 'page-templates/template-home-vc.php' ] );
return $page_templates;
}
}
| jfrankel-13/findlancer | wp-content/themes/listify/inc/template/class-template-page-templates.php | PHP | gpl-2.0 | 404 |
import socket
import threading
import time
def tcplink(sock, addr):
print 'Accept new connection from %s:%s...' % addr
sock.send('Welcome!')
while True:
data = sock.recv(1024)
time.sleep(1)
if data == 'exit' or not data:
break
sock.send('Hello, %s!' % data)
sock.close()
print 'Connection from %s:%s closed.' % addr
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('127.0.0.1', 8888))
s.listen(5)
print 'Waiting for connection...'
while True:
sock, addr = s.accept()
t = threading.Thread(target=tcplink, args=(sock, addr))
t.start()
| lovekun/Notebook | python/chatroomServer.py | Python | gpl-2.0 | 654 |
import os
import sys
import shutil
import binascii
import traceback
import subprocess
from win32com.client import Dispatch
LAUNCHER_PATH = "C:\\Program Files\\Augur"
DATA_PATH = os.path.join(os.path.expanduser('~'), 'AppData', 'Roaming', "Augur")
PASSFILE = os.path.join(DATA_PATH, "password.txt")
if getattr(sys, 'frozen', False):
# we are running in a |PyInstaller| bundle
BASEDIR = sys._MEIPASS
else:
# we are running in a normal Python environment
BASEDIR = os.path.dirname(os.path.abspath(__file__))
GETH_EXE = os.path.join(BASEDIR, 'geth.exe')
LAUNCHER_EXE = os.path.join(BASEDIR, 'augurlauncher.exe')
def main():
# first make all the appropriate directories
print("Making directories...")
for d in LAUNCHER_PATH, DATA_PATH:
print("Creating", d, end=" ", flush=True)
os.mkdir(d)
print("Success!")
print("Generating random password file...", end=" ", flush=True)
# then generate the password
password = binascii.b2a_hex(os.urandom(32))
passfile = open(PASSFILE, "w")
passfile.write(password.decode('ascii'))
passfile.close()
print("Success!")
# Then copy ".exe"s to the launcher path
exes = GETH_EXE, LAUNCHER_EXE
results = []
for exe in exes:
print("Copying", os.path.basename(exe), "to", LAUNCHER_PATH, "...", end=" ", flush=True)
results.append(shutil.copy(exe, LAUNCHER_PATH))
print("Sucess!")
print("Creating node account...", end=" ", flush=True)
# create account on node
p = subprocess.Popen([results[0],
"--password", PASSFILE,
"account", "new"])
p.wait()
print("Success!")
print("Creating shortcut...", end=" ", flush=True)
desktop = os.path.join(os.path.expanduser('~'), 'Desktop')
shortcut_path = os.path.join(desktop, "Augur Launcher.lnk")
wDir = LAUNCHER_PATH
shell = Dispatch('WScript.Shell')
shortcut = shell.CreateShortCut(shortcut_path)
shortcut.Targetpath = results[1]
shortcut.WorkingDirectory = wDir
shortcut.IconLocation = results[1]
shortcut.save()
print("Success!")
def uninstall():
paths = LAUNCHER_PATH, DATA_PATH
for p in paths:
print("Deleting", p, "...", end=" ", flush=True)
shutil.rmtree(p)
print("Success!")
print("Removing desktop shortcut...", end=" ", flush=True)
desktop = os.path.join(os.path.expanduser('~'), 'Desktop')
shortcut_path = os.path.join(desktop, "Augur Launcher.lnk")
os.remove(shortcut_path)
print("Success!")
if __name__ == '__main__':
try:
if len(sys.argv) == 2 and sys.argv[1] == 'uninstall':
uninstall()
elif len(sys.argv) == 1:
main()
else:
assert len(sys.argv) <= 2, "wrong number of arguements!"
except Exception as exc:
traceback.print_exc()
finally:
os.system("pause")
sys.exit(0)
| AugurProject/augur-launcher | Augur Installer.py | Python | gpl-2.0 | 2,932 |
<div class="twelve columns alpha">
<h3 class="headline">Descripción del Proyecto</h3><span class="line"></span><div class="clearfix"></div>
<p>O Parque Tecnológico Itaipu (conocido como PTI) tiene un sitio web que proporciona mucha información sobre las actividades y los proyectos de PTI.
<p>PTI ha identificado algunos problemas en su sitio, y presentado estas demandas a Celtab, para resolver estos problemas, así como mejorar el sitio en general, completamente en Drupal.
<p>Por lo tanto, al ser necesario el desarrollo de algunas mejoras en Drupal y crear "plugins" para ayudar a la publicación de noticias y edición.</p>
<p><strong>Investigadores:</strong> Cristhian Urunaga; Mario Villagra</p>
</div>
<!-- Job Description -->
<div class="four columns omega">
<h3 class="headline">Detalles del Proyecto</h3><span class="line"></span><div class="clearfix"></div>
<ul style="margin: 2px 0 18px 0;" class="list-3">
<li>PHP</li>
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
<li>CMS Drupal 7.x</li>
</ul>
<div class="clearfix"></div>
</div>
| IngCarlosColman/SiteCeltab | CONTENIDOS/espanol/Proyectos/Mejoras del Sitio PTI.php | PHP | gpl-2.0 | 1,129 |
var express = require('express'),
formidable = require('formidable'),
imgur = require('imgur'),
fs = require('fs'),
url = require('url'),
bodyParser = require('body-parser'),
router = express.Router(),
uuid = require('node-uuid'),
db = require('../lib/database'),
tools = require('../lib/functions');
var connection = db.connectdb();
router.post('/upload', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked'
});
var id = tools.makeid();
var owner = uuid.v1();
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form.uploadDir = 'tmp/';
form.on('field', function(field, value) {
fields.push(value);
});
form.on('file', function(field, file) {
files.push(file);
});
form.on('end', function() {
res.end('http://' + req.headers.host + '/' + id);
if (fields[0]) {
owner = fields[0];
}
files.forEach(function(file) {
imgur.uploadFile(file.path)
.then(function(json) {
fs.unlink(file.path);
connection.query("INSERT INTO `imgsnap`.`images` (`id`, `direct`, `timestamp`, `delete`, `owner`) VALUES ('" + connection.escape(id).replace(/'/g, '') + "', '" + connection.escape(json.data.link).replace(/'/g, '') + "', '" + connection.escape(json.data.datetime) + "', '" + connection.escape(json.data.deletehash).replace(/'/g, '') + "', '" + connection.escape(owner).replace(/'/g, '') + "')");
})
.catch(function(err) {
fs.unlink(file.path);
console.log(err);
});
});
});
form.parse(req);
});
router.get('/image/:id', function(req, res) {
var id = req.params.id;
connection.query('SELECT * FROM images WHERE id = ' + connection.escape(id), function(err, row, fields) {
if (!row[0]) {
res.json({
status: false
});
} else {
res.json({
status: true,
direct: row[0].direct,
timestamp: row[0].timestamp
});
}
});
});
router.get('/check', function(req, res) {
res.writeHead(200, {
'Content-Type': 'text/html',
'Transfer-Encoding': 'chunked'
});
res.end('Server Online');
});
module.exports = router; | luigiplr/imgSnap-backend | routes/api.js | JavaScript | gpl-2.0 | 2,487 |
# -*- coding: utf-8 -*-
def outfit():
collection = []
for _ in range(0, 5):
collection.append("Item{}".format(_))
return {
"data": collection,
}
api = [
('/outfit', 'outfit', outfit),
]
| Drachenfels/Game-yolo-archer | server/api/outfits.py | Python | gpl-2.0 | 228 |
var UniteNivoPro = new function() {
var t = this;
var containerID = "slider_container";
var container, arrow_left, arrow_right, bullets_container;
var caption_back, caption_text;
var bulletsRelativeY = "";
/**
* show slider view error, hide all the elements
*/
t.showSliderViewError = function(errorMessage) {
jQuery("#config-document").hide();
UniteAdmin.showErrorMessage(errorMessage);
}
/**
* main init of the object
*/
var init = function() {
container = jQuery("#" + containerID);
arrow_left = jQuery("#arrow_left");
arrow_right = jQuery("#arrow_right");
bullets_container = jQuery("#bullets_wrapper");
caption_back = jQuery("#caption_back");
caption_text = jQuery("#caption_text");
UniteAdmin.hideSystemMessageDelay();
}
/**
* init visual form width
*/
t.initSliderView = function() {
init(); //init the object - must call
//update menu event
jQuery("#visual").click(function() {
setTimeout("UniteNivoPro.initAfterDelay()", 300);
});
//update visual from fields
updateFromFields();
initSliderEvents();
initVisualTabs();
//update arrows fields ) if not set
setTimeout("UniteNivoPro.initAfterDelay()", 1000);
}
/* ===================== Item View Section =================== */
/**
* init item view
*/
t.initItemView = function() {
//operate on slide image change
var obj = document.getElementById("jform_params_image");
obj.addEvent('change', function() {
var urlImage = g_urlRoot + this.value;
//trace(urlImage);
jQuery("#image_preview_wrapper").show().css("background-image", "url(\"" + urlImage + "\")");
});
}
/* ===================== Item View End =================== */
/**
* on visual tab display event. update some fields
*/
t.onVisualDisplay = function() {
updateArrowPosFields();
bulletsAlignCenter();
}
/**
* init elements after delay
*/
t.initAfterDelay = function() {
updateArrowPosFields();
initBullets();
}
/**
* align the bullets to center
*/
var bulletsAlignCenter = function() {
var align = jQuery("#jform_visual_bullets_align").val();
if (align != "center")
return(true);
var data = getElementsData();
var bulletsX = Math.round((data.sliderWidth - data.bulletsWidth) / 2);
bullets_container.css("left", bulletsX + "px");
updateBulletFields("center");
}
/**
* set bullets position by relative.
*/
var bulletsSetRelativeYPos = function() {
var data = getElementsData();
if (data.bulletsWidth == 0)
return(true);
if (bulletsRelativeY == "")
return(true);
var bulletsPosY = data.sliderHeight + bulletsRelativeY;
bullets_container.css("top", bulletsPosY + "px");
updateBulletFields("relative");
}
/**
* do some actions on bullets align change
*/
var onBulletsAlignChange = function(align) {
switch (align) {
case "center":
bullets_container.draggable("option", "axis", "y");
bulletsAlignCenter();
UniteAdmin.hideFormField("jform_visual_bullets_xleft");
UniteAdmin.hideFormField("jform_visual_bullets_xright");
break;
case "left":
bullets_container.draggable("option", "axis", "");
UniteAdmin.showFormField("jform_visual_bullets_xleft");
UniteAdmin.hideFormField("jform_visual_bullets_xright");
jQuery("#jform_visual_bullets_xleft-lbl").css('display', 'inline');
break;
case "right":
bullets_container.draggable("option", "axis", "");
UniteAdmin.hideFormField("jform_visual_bullets_xleft");
UniteAdmin.showFormField("jform_visual_bullets_xright");
jQuery("#jform_visual_bullets_xright-lbl").css('display', 'inline');
break;
}
}
/**
* on bullets drag event, update fields.
*/
var onBulletsDrag = function() {
updateBulletFields("drag");
}
/**
* update relative y
*/
var updateBulletsRelativeY = function() {
var data = getElementsData();
bulletsRelativeY = data.bulletsY - data.sliderHeight;
}
/**
* init the bullets position
*/
var initBullets = function() {
var selectorBulletsAlign = "#jform_visual_bullets_align";
var selectorBulletReverse = "#jform_visual_reverse_bullets";
var align = jQuery(selectorBulletsAlign).val();
//set bullets draggable
var drag_options = {drag: onBulletsDrag};
if (align == "center") {
bulletsAlignCenter();
//set draggable only y axis
drag_options.axis = "y";
}
jQuery(selectorBulletReverse).change(function() {
reverse_bullets();
})
//set select event
jQuery(selectorBulletsAlign).change(function() {
onBulletsAlignChange(this.value);
});
//set draggable event
bullets_container.draggable(drag_options);
//show the bullets (if hidden)
bullets_container.removeClass("invisible");
updateBulletsRelativeY();
}
/**
* show some tab, set it selecetd class, and hide the others.
*/
var showVisualTab = function(linkID) {
var link = jQuery("#" + linkID);
if (!link.length)
return(false);
var tabID = link.data("tab");
//set togler selected
jQuery("#tabs_visual li a").removeClass("selected");
link.addClass("selected");
//show panel
jQuery(".visual_panel").removeClass("hidden").hide();
jQuery(tabID).show();
}
/**
* init visual tabs functionality
*/
var initVisualTabs = function() {
var hash = location.hash;
if (hash) {
var linkID = hash.replace("#tab-", "");
showVisualTab(linkID);
}
//set event
jQuery("#tabs_visual li a").click(function() {
showVisualTab(this.id);
});
}
/**
* on slider resize event. update all elements and fields accordingly
*/
var onSliderResize = function(event, ui) {
//update fields widht / height
if (event) { //only if came from event
jQuery("#jform_visual_width").val(container.width());
jQuery("#jform_visual_height").val(container.height());
}
checkArrowsConnection("arrow_left");
bulletsSetRelativeYPos();
bulletsAlignCenter();
}
/**
* init slider view onchange events
*/
var initSliderEvents = function() {
//set fields onchange events
var fields = "#visual_wrapper input";
jQuery(fields).blur(updateFromFields).click(updateFromFields);
jQuery(fields).keypress(function(event) {
if (event.keyCode == 13)
updateFromFields(this);
});
jQuery("#visual_wrapper select").change(updateFromFields);
//set resizible event:
container.resizable({resize: onSliderResize});
//set on color picker move event:
UniteAdmin.onColorPickerMove(function() {
updateFromFields();
});
//set arrows draggable
jQuery("#arrow_left,#arrow_right").draggable({
drag: onArrowsDrag
});
jQuery("#arrows_gocenter").click(arrowsToCenter);
}
/**
* get all element sizes and positions.
*/
var getElementsData = function() {
var data = {};
//slider data
data.sliderWidth = Number(jQuery("#jform_visual_width").val());
data.sliderHeight = Number(jQuery("#jform_visual_height").val());
//arrows data
var arrowLeftPos = arrow_left.position();
var arrowRightPos = arrow_right.position();
data.arrowLeftX = Math.round(arrowLeftPos.left);
data.arrowLeftY = Math.round(arrowLeftPos.top);
data.arrowRightX = Math.round(arrowRightPos.left);
data.arrowRightY = Math.round(arrowRightPos.top);
data.arrowLeftWidth = arrow_left.width();
data.arrowLeftHeight = arrow_left.height();
data.arrowRightWidth = arrow_right.width();
data.arrowRightHeight = arrow_right.height();
//bullets data:
var bulletsPos = bullets_container.position();
data.bulletsWidth = bullets_container.width();
data.bulletsHeight = bullets_container.height();
data.bulletsX = Math.round(bulletsPos.left);
data.bulletsY = Math.round(bulletsPos.top);
return(data);
}
/**
* get the arrows to center of the banner (y axes)
*/
var arrowsToCenter = function() {
var data = getElementsData();
var arrowsNewY = Math.round(data.sliderHeight - data.arrowLeftHeight) / 2;
arrow_right.css("top", arrowsNewY + "px");
arrow_left.css("top", arrowsNewY + "px");
//update position fields on the panel
updateArrowPosFields();
}
/**
* check arrows connection, and
*/
var checkArrowsConnection = function(arrowID) {
var freeDrag = jQuery("#jform_visual_arrows_free_drag").is(":checked");
if (freeDrag == true) {
updateArrowPosFields();
return(false);
}
var data = getElementsData();
if (arrowID == "arrow_left") { //left arrow is main.
var arrowRightNewX = data.sliderWidth - data.arrowLeftX - data.arrowRightWidth;
//set right arrow position
arrow_right.css({"top": data.arrowLeftY + "px",
"left": arrowRightNewX + "px"});
} else if (arrowID == "arrow_right") { //right arrow is main
var arrowLeftNewX = data.sliderWidth - data.arrowRightX - data.arrowRightWidth;
//set left arrow position
arrow_left.css({"top": data.arrowRightY + "px",
"left": arrowLeftNewX + "px"});
}
updateArrowPosFields();
}
/**
* on arrows drag event. update form fields, and operate arrow connections.
*/
var onArrowsDrag = function() {
var arrowID = this.id;
checkArrowsConnection(arrowID);
}
/**
*
* update bullets position from the bullets
*/
var updateBulletFields = function(fromWhere) {
//trace("update fields "+fromWhere);return(false);
if (bullets_container.is(":visible") == false)
return(true);
var data = getElementsData();
//update fields:
var bulletsRightX = data.sliderWidth - data.bulletsX - data.bulletsWidth;
jQuery("#jform_visual_bullets_y").val(data.bulletsY);
jQuery("#jform_visual_bullets_xleft").val(data.bulletsX);
jQuery("#jform_visual_bullets_xright").val(bulletsRightX);
//update relative option
updateBulletsRelativeY();
}
/**
* update arrows positions from the arrows
*/
var updateArrowPosFields = function() {
//don't update if the container not visible
if (container.is(':visible') == false)
return(true);
if (arrow_left.is(':visible') == false)
return(true);
var data = getElementsData();
//set values
jQuery("#jform_visual_arrow_left_x").val(data.arrowLeftX);
jQuery("#jform_visual_arrow_left_y").val(data.arrowLeftY);
jQuery("#jform_visual_arrow_right_x").val(data.arrowRightX);
jQuery("#jform_visual_arrow_right_y").val(data.arrowRightY);
}
/**
* hide arrows and disable panel elements
*/
var hideArrows = function() {
if (arrow_left.is(':visible') == false)
return(true);
arrow_left.hide();
arrow_right.hide();
//hide arrow fields
jQuery("#section_arrows").hide();
}
/**
* show arrows and enable panel elements
*/
var showArrows = function() {
if (arrow_left.is(':visible') == true)
return(true);
arrow_left.show();
arrow_right.show();
//show arrow fields
jQuery("#section_arrows").show();
}
/**
* update the container from fields.
*/
var updateFromFields = function(element) {
if (element == undefined || element.id == undefined)
element = this;
var elemID = null;
if (element.id != undefined)
elemID = element.id;
//---- update width / height
var width = jQuery("#jform_visual_width").val();
var height = jQuery("#jform_visual_height").val();
container.width(width).height(height);
//width / heigth event
switch (elemID) {
case "jform_visual_width":
case "jform_visual_height":
onSliderResize();
break;
}
//update border
updateFromFields_border();
//update shadow
updateFromFields_shadow();
//update arrows
updateFromFields_arrows(elemID);
//update bullets
updateFromFields_bullets(elemID);
//set the bullets according the resize
bulletsSetRelativeYPos();
//update captions
updateFromFields_caption(elemID);
//update caption text
updateFromFields_captionText();
}
/**
* update caption text
*/
var updateFromFields_captionText = function() {
var css = {};
if (caption_back.is(":visible") == false)
return(true);
//set color
var textColor = jQuery("#jform_visual_text_color").val();
css["color"] = textColor;
//set text align
var textAlign = jQuery("#jform_visual_text_align").val();
css["text-align"] = textAlign;
//set padding
var textPadding = jQuery("#jform_visual_text_padding").val();
css["padding"] = textPadding + "px";
var fontSize = jQuery("#jform_visual_font_size").val();
css["font-size"] = fontSize + "px";
//set the css
caption_text.css(css);
}
/**
* show the caption
*/
var showCaption = function() {
if (caption_back.is(":visible") == true)
return(false);
caption_back.show();
}
/**
* hide the caption
*/
var hideCaption = function() {
if (caption_back.is(":visible") == false)
return(false);
caption_back.hide();
}
/**
* update captions fields
*/
var updateFromFields_caption = function(elemID) {
var css = {};
if (elemID == "jform_visual_has_caption") {
var hasCaption = jQuery("#jform_visual_has_caption").is(":checked");
if (hasCaption == true)
showCaption();
else
hideCaption();
}
if (caption_back.is(":visible") == false)
return(true);
//set back color
var backColor = jQuery("#jform_visual_caption_back_color").val();
css["background-color"] = backColor;
//set alpha
var alpha = jQuery("#jform_visual_caption_back_alpha").val();
var alpha = Number(alpha) / 100;
caption_back.fadeTo(0, alpha);
//set position:
var position = jQuery("#jform_visual_caption_position").val();
if (position == "top") {
css["bottom"] = ""; //set to top
css["top"] = "0px";
} else {
css["bottom"] = "0px"; //set to bottom
css["top"] = "";
}
//set the css
caption_back.css(css);
}
/**
* hide the bullets
*/
var hideBullets = function() {
if (bullets_container.is(":visible") == false)
return(true);
//hide fields
jQuery("#section_bullets").hide();
//hide bullets
bullets_container.hide();
}
/**
* show the bullets
*/
var showBullets = function() {
if (bullets_container.is(":visible") == true)
return(true);
//show fields
jQuery("#section_bullets").show();
//show bullets
bullets_container.removeClass("invisible").show();
}
/**
* update bullets fields
*/
var reverse_bullets = function() {
var reverseChecked = jQuery("#jform_visual_reverse_bullets").is(":checked");
var normal = 'normal';
var active = 'active';
if (reverseChecked) {
normal = 'active';
active = 'normal';
}
jQuery("#bullets_wrapper img").each(function(index, value) {
if (index == 1) {
jQuery(this).attr('src', jQuery(this).attr('src').replace(normal, active));
} else {
jQuery(this).attr('src', jQuery(this).attr('src').replace(active, normal));
}
});
}
/**
* update bullets fields
*/
var updateFromFields_bullets = function(elemID) {
//trace("update bullets");return(false);
switch (elemID) {
case "jform_visual_has_bullets":
var showBulletsCheck = jQuery("#jform_visual_has_bullets").is(":checked");
if (showBulletsCheck)
showBullets();
else
hideBullets();
break;
}
//skip invisible container
if (bullets_container.is(':visible') == false)
return(true);
var bulletsY = jQuery("#jform_visual_bullets_y").val();
switch (elemID) {
default:
case "jform_visual_bullets_xleft":
var bulletsX = jQuery("#jform_visual_bullets_xleft").val();
break;
case "jform_visual_bullets_xright":
var data = getElementsData();
var bulletsRightX = jQuery("#jform_visual_bullets_xright").val();
var bulletsX = data.sliderWidth - data.bulletsWidth - bulletsRightX;
break;
case "jform_visual_bullets_spacing": //set spacing
var spacing = jQuery("#jform_visual_bullets_spacing").val();
bullets_container.find("ul li:not(:first-child)").css("margin-left", spacing + "px");
bulletsAlignCenter();
break;
}
bullets_container.css({"top": bulletsY + "px", "left": bulletsX + "px"});
updateBulletFields("fields");
}
/**
* update border
*/
var updateFromFields_border = function() {
var has_border = jQuery("#jform_visual_has_border").is(':checked');
if (has_border == true) {
var border_color = jQuery("#jform_visual_border_color").val();
var border_size = jQuery("#jform_visual_border_size").val();
container.css({"border-style": "solid",
"border-width": border_size + "px",
"border-color": border_color
});
} else
container.css({"border-style": "none"});
}
/**
* update shadow from fields
*/
var updateFromFields_shadow = function() {
//----update shadow:
var has_shadow = jQuery("#jform_visual_has_shadow").is(':checked');
if (has_shadow == true) {
var shadow_color = jQuery("#jform_visual_shadow_color").val();
var shadowProps = "0px 1px 5px 0px " + shadow_color;
container.css({"box-shadow": shadowProps,
"-moz-box-shadow": shadowProps,
"-webkit-box-shadow": shadowProps});
} else
container.css({"box-shadow": "none", "-moz-box-shadow": "none", "-webkit-box-shadow": "none"});
}
/**
* set arrows in the place of the fields
*/
var updateFromFields_arrows = function(elemID) {
var showArrows_check = jQuery("#jform_visual_has_arrows").is(":checked");
//check arrows hide / show
if (elemID == "jform_visual_has_arrows") {
if (showArrows_check == false)
hideArrows();
else
showArrows();
}
//position arrows
if (arrow_left.is(':visible') == false)
return(true);
var arrowLeftX = jQuery("#jform_visual_arrow_left_x").val();
var arrowLeftY = jQuery("#jform_visual_arrow_left_y").val();
var arrowRightX = jQuery("#jform_visual_arrow_right_x").val();
var arrowRightY = jQuery("#jform_visual_arrow_right_y").val();
arrow_left.css({"top": arrowLeftY + "px", "left": arrowLeftX + "px"});
arrow_right.css({"top": arrowRightY + "px", "left": arrowRightX + "px"});
//operate errors connection:
switch (elemID) {
case "jform_visual_has_arrows":
case "jform_visual_arrow_left_y":
case "jform_visual_arrow_left_x":
checkArrowsConnection("arrow_left");
break;
case "jform_visual_arrow_right_y":
case "jform_visual_arrow_right_x":
checkArrowsConnection("arrow_right");
break;
}
}
/**
* on arrows select event - update arrow pictures and change arrows set
*/
t.onArrowsSelect = function(data) {
jQuery("#arrow_left").attr("src", data.url_left);
jQuery("#arrow_right").attr("src", data.url_right);
jQuery("#jform_visual_arrows_set").val(data.arrowName);
//align arrows
setTimeout("UniteNivoPro.operationDelay('checkArrowsConnection')", 500);
}
/**
* on bullets select - take bullets html by ajax, and change the bullets.
*/
t.onBulletsSelect = function(setName) {
var data = {setName: setName};
UniteAdmin.ajaxRequest("get_bullets_html", data, function(response) {
jQuery("#bullets_wrapper").html(response.bullets_html);
jQuery("#jform_visual_bullets_set").val(setName);
//align center after delay
setTimeout("UniteNivoPro.operationDelay('bulletsAlignCenter')", 500);
bulletsAlignCenter();
reverse_bullets();
});
}
/**
* align center after delay function
*/
t.operationDelay = function(operation) {
switch (operation) {
case "bulletsAlignCenter":
bulletsAlignCenter();
break;
case "checkArrowsConnection":
checkArrowsConnection("arrow_left");
break;
}
}
}
| VS-Studio3/build | administrator/components/com_nivosliderpro/assets/nivopro.js | JavaScript | gpl-2.0 | 22,978 |
/*
* Copyright (C) 2013-2019 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public License
* version 2 and the aforementioned licenses.
*
* 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.
*/
package org.n52.series.spi.geo;
import org.locationtech.jts.geom.Geometry;
import org.n52.io.crs.CRSUtils;
import org.n52.io.request.IoParameters;
import org.n52.io.response.dataset.StationOutput;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TransformationService {
private static final Logger LOGGER = LoggerFactory.getLogger(TransformationService.class);
/**
* @param station
* the station to transform
* @param parameters
* the query containing CRS and how to handle axes order
*/
protected void transformInline(StationOutput station, IoParameters parameters) {
String crs = parameters.getCrs();
if (CRSUtils.DEFAULT_CRS.equals(crs)) {
// no need to transform
return;
}
Geometry geometry = transform(station.getGeometry(), parameters);
station.setValue(StationOutput.GEOMETRY, geometry, parameters, station::setGeometry);
}
public Geometry transform(Geometry geometry, IoParameters query) {
String crs = query.getCrs();
if (CRSUtils.DEFAULT_CRS.equals(crs)) {
// no need to transform
return geometry;
}
return transformGeometry(query, geometry, crs);
}
private Geometry transformGeometry(IoParameters query,
Geometry geometry,
String crs)
throws RuntimeException {
try {
CRSUtils crsUtils = query.isForceXY()
? CRSUtils.createEpsgForcedXYAxisOrder()
: CRSUtils.createEpsgStrictAxisOrder();
return geometry != null
? crsUtils.transformInnerToOuter(geometry, crs)
: geometry;
} catch (TransformException e) {
throwRuntimeException(crs, e);
} catch (FactoryException e) {
LOGGER.debug("Couldn't create geometry factory", e);
}
return geometry;
}
private void throwRuntimeException(String crs, TransformException e) throws RuntimeException {
throw new RuntimeException("Could not transform to requested CRS: " + crs, e);
}
}
| ridoo/series-rest-api | spi/src/main/java/org/n52/series/spi/geo/TransformationService.java | Java | gpl-2.0 | 3,637 |
<?php
/**
* ECSHOP 控制台首頁
* ============================================================================
* 版權所有 2005-2010 上海商派網絡科技有限公司,並保留所有權利。
* 網站地址: http://www.ecshop.com;
* ----------------------------------------------------------------------------
* 這不是一個自由軟件!您只能在不用於商業目的的前提下對程序代碼進行修改和
* 使用;不允許對程序代碼以任何形式任何目的的再發布。
* ============================================================================
* $Author: liuhui $
* $Id: index.php 17163 2010-05-20 10:13:23Z liuhui $
*/
define('IN_ECS', true);
require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . '/includes/lib_order.php');
/*------------------------------------------------------ */
//-- 框架
/*------------------------------------------------------ */
if ($_REQUEST['act'] == '')
{
$smarty->assign('shop_url', urlencode($ecs->url()));
$smarty->display('index.htm');
}
/*------------------------------------------------------ */
//-- 頂部框架的內容
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'top')
{
// 獲得管理員設置的菜單
$lst = array();
$nav = $db->GetOne('SELECT nav_list FROM ' . $ecs->table('admin_user') . " WHERE user_id = '" . $_SESSION['admin_id'] . "'");
if (!empty($nav))
{
$arr = explode(',', $nav);
foreach ($arr AS $val)
{
$tmp = explode('|', $val);
$lst[$tmp[1]] = $tmp[0];
}
}
// 獲得管理員設置的菜單
// 獲得管理員ID
$smarty->assign('send_mail_on',$_CFG['send_mail_on']);
$smarty->assign('nav_list', $lst);
$smarty->assign('admin_id', $_SESSION['admin_id']);
$smarty->assign('certi', $_CFG['certi']);
$smarty->display('top.htm');
}
/*------------------------------------------------------ */
//-- 計算器
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'calculator')
{
$smarty->display('calculator.htm');
}
/*------------------------------------------------------ */
//-- 左邊的框架
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'menu')
{
include_once('includes/inc_menu.php');
// 權限對照表
include_once('includes/inc_priv.php');
foreach ($modules AS $key => $value)
{
ksort($modules[$key]);
}
ksort($modules);
foreach ($modules AS $key => $val)
{
$menus[$key]['label'] = $_LANG[$key];
if (is_array($val))
{
foreach ($val AS $k => $v)
{
if ( isset($purview[$k]))
{
if (is_array($purview[$k]))
{
$boole = false;
foreach ($purview[$k] as $action)
{
$boole = $boole || admin_priv($action, '', false);
}
if (!$boole)
{
continue;
}
}
else
{
if (! admin_priv($purview[$k], '', false))
{
continue;
}
}
}
if ($k == 'ucenter_setup' && $_CFG['integrate_code'] != 'ucenter')
{
continue;
}
$menus[$key]['children'][$k]['label'] = $_LANG[$k];
$menus[$key]['children'][$k]['action'] = $v;
}
}
else
{
$menus[$key]['action'] = $val;
}
// 如果children的子元素長度為0則刪除該組
if(empty($menus[$key]['children']))
{
unset($menus[$key]);
}
}
$smarty->assign('menus', $menus);
$smarty->assign('no_help', $_LANG['no_help']);
$smarty->assign('help_lang', $_CFG['lang']);
$smarty->assign('charset', EC_CHARSET);
$smarty->assign('admin_id', $_SESSION['admin_id']);
$smarty->display('menu.htm');
}
/*------------------------------------------------------ */
//-- 清除緩存
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'clear_cache')
{
clear_all_files();
sys_msg($_LANG['caches_cleared']);
}
/*------------------------------------------------------ */
//-- 主窗口,起始頁
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'main')
{
//開店嚮導第一步
if(isset($_SESSION['shop_guide']) && $_SESSION['shop_guide'] === true)
{
unset($_SESSION['shop_guide']);//銷毀session
ecs_header("Location: ./index.php?act=first\n");
exit();
}
$gd = gd_version();
/* 檢查文件目錄屬性 */
$warning = array();
if ($_CFG['shop_closed'])
{
$warning[] = $_LANG['shop_closed_tips'];
}
if (file_exists('../install'))
{
$warning[] = $_LANG['remove_install'];
}
if (file_exists('../upgrade'))
{
$warning[] = $_LANG['remove_upgrade'];
}
if (file_exists('../demo'))
{
$warning[] = $_LANG['remove_demo'];
}
$open_basedir = ini_get('open_basedir');
if (!empty($open_basedir))
{
/* 如果 open_basedir 不為空,則檢查是否包含了 upload_tmp_dir */
$open_basedir = str_replace(array("\\", "\\\\"), array("/", "/"), $open_basedir);
$upload_tmp_dir = ini_get('upload_tmp_dir');
if (empty($upload_tmp_dir))
{
if (stristr(PHP_OS, 'win'))
{
$upload_tmp_dir = getenv('TEMP') ? getenv('TEMP') : getenv('TMP');
$upload_tmp_dir = str_replace(array("\\", "\\\\"), array("/", "/"), $upload_tmp_dir);
}
else
{
$upload_tmp_dir = getenv('TMPDIR') === false ? '/tmp' : getenv('TMPDIR');
}
}
if (!stristr($open_basedir, $upload_tmp_dir))
{
$warning[] = sprintf($_LANG['temp_dir_cannt_read'], $upload_tmp_dir);
}
}
$result = file_mode_info('../cert');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], 'cert', $_LANG['cert_cannt_write']);
}
$result = file_mode_info('../' . DATA_DIR);
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], 'data', $_LANG['data_cannt_write']);
}
else
{
$result = file_mode_info('../' . DATA_DIR . '/afficheimg');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/afficheimg', $_LANG['afficheimg_cannt_write']);
}
$result = file_mode_info('../' . DATA_DIR . '/brandlogo');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/brandlogo', $_LANG['brandlogo_cannt_write']);
}
$result = file_mode_info('../' . DATA_DIR . '/cardimg');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/cardimg', $_LANG['cardimg_cannt_write']);
}
$result = file_mode_info('../' . DATA_DIR . '/feedbackimg');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/feedbackimg', $_LANG['feedbackimg_cannt_write']);
}
$result = file_mode_info('../' . DATA_DIR . '/packimg');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], DATA_DIR . '/packimg', $_LANG['packimg_cannt_write']);
}
}
$result = file_mode_info('../images');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['images_cannt_write']);
}
else
{
$result = file_mode_info('../' . IMAGE_DIR . '/upload');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], IMAGE_DIR . '/upload', $_LANG['imagesupload_cannt_write']);
}
}
$result = file_mode_info('../temp');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_cannt_write']);
}
$result = file_mode_info('../temp/backup');
if ($result < 2)
{
$warning[] = sprintf($_LANG['not_writable'], 'images', $_LANG['tpl_backup_cannt_write']);
}
if (!is_writeable('../' . DATA_DIR . '/order_print.html'))
{
$warning[] = $_LANG['order_print_canntwrite'];
}
clearstatcache();
$smarty->assign('warning_arr', $warning);
/* 管理員留言信息 */
$sql = 'SELECT message_id, sender_id, receiver_id, sent_time, readed, deleted, title, message, user_name ' .
'FROM ' . $ecs->table('admin_message') . ' AS a, ' . $ecs->table('admin_user') . ' AS b ' .
"WHERE a.sender_id = b.user_id AND a.receiver_id = '$_SESSION[admin_id]' AND ".
"a.readed = 0 AND deleted = 0 ORDER BY a.sent_time DESC";
$admin_msg = $db->GetAll($sql);
$smarty->assign('admin_msg', $admin_msg);
/* 取得支持貨到付款和不支持貨到付款的支付方式 */
$ids = get_pay_ids();
/* 已完成的訂單 */
$order['finished'] = $db->GetOne('SELECT COUNT(*) FROM ' . $ecs->table('order_info').
" WHERE 1 " . order_query_sql('finished'));
$status['finished'] = CS_FINISHED;
/* 待發貨的訂單: */
$order['await_ship'] = $db->GetOne('SELECT COUNT(*)'.
' FROM ' .$ecs->table('order_info') .
" WHERE 1 " . order_query_sql('await_ship'));
$status['await_ship'] = CS_AWAIT_SHIP;
/* 待付款的訂單: */
$order['await_pay'] = $db->GetOne('SELECT COUNT(*)'.
' FROM ' .$ecs->table('order_info') .
" WHERE 1 " . order_query_sql('await_pay'));
$status['await_pay'] = CS_AWAIT_PAY;
/* “未確認”的訂單 */
$order['unconfirmed'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('order_info').
" WHERE 1 " . order_query_sql('unconfirmed'));
$status['unconfirmed'] = OS_UNCONFIRMED;
// $today_start = mktime(0,0,0,date('m'),date('d'),date('Y'));
$order['stats'] = $db->getRow('SELECT COUNT(*) AS oCount, IFNULL(SUM(order_amount), 0) AS oAmount' .
' FROM ' .$ecs->table('order_info'));
$smarty->assign('order', $order);
$smarty->assign('status', $status);
/* 商品信息 */
$goods['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real = 1');
$virtual_card['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real=0 AND extension_code=\'virtual_card\'');
$goods['new'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_new = 1 AND is_real = 1');
$virtual_card['new'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_new = 1 AND is_real=0 AND extension_code=\'virtual_card\'');
$goods['best'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_best = 1 AND is_real = 1');
$virtual_card['best'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_best = 1 AND is_real=0 AND extension_code=\'virtual_card\'');
$goods['hot'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_hot = 1 AND is_real = 1');
$virtual_card['hot'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_hot = 1 AND is_real=0 AND extension_code=\'virtual_card\'');
$time = gmtime();
$goods['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND promote_price>0' .
" AND promote_start_date <= '$time' AND promote_end_date >= '$time' AND is_real = 1");
$virtual_card['promote'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND promote_price>0' .
" AND promote_start_date <= '$time' AND promote_end_date >= '$time' AND is_real=0 AND extension_code='virtual_card'");
/* 缺貨商品 */
if ($_CFG['use_storage'])
{
$sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number AND is_real = 1';
$goods['warn'] = $db->GetOne($sql);
$sql = 'SELECT COUNT(*) FROM ' .$ecs->table('goods'). ' WHERE is_delete = 0 AND goods_number <= warn_number AND is_real=0 AND extension_code=\'virtual_card\'';
$virtual_card['warn'] = $db->GetOne($sql);
}
else
{
$goods['warn'] = 0;
$virtual_card['warn'] = 0;
}
$smarty->assign('goods', $goods);
$smarty->assign('virtual_card', $virtual_card);
/* 訪問統計信息 */
$today = local_getdate();
$sql = 'SELECT COUNT(*) FROM ' .$ecs->table('stats').
' WHERE access_time > ' . (mktime(0, 0, 0, $today['mon'], $today['mday'], $today['year']) - date('Z'));
$today_visit = $db->GetOne($sql);
$smarty->assign('today_visit', $today_visit);
$online_users = $sess->get_users_count();
$smarty->assign('online_users', $online_users);
/* 最近反饋 */
$sql = "SELECT COUNT(f.msg_id) ".
"FROM " . $ecs->table('feedback') . " AS f ".
"LEFT JOIN " . $ecs->table('feedback') . " AS r ON r.parent_id=f.msg_id " .
'WHERE f.parent_id=0 AND ISNULL(r.msg_id) ' ;
$smarty->assign('feedback_number', $db->GetOne($sql));
/* 未審核評論 */
$smarty->assign('comment_number', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('comment') .
' WHERE status = 0 AND parent_id = 0'));
$mysql_ver = $db->version(); // 獲得 MySQL 版本
/* 系統信息 */
$sys_info['os'] = PHP_OS;
$sys_info['ip'] = $_SERVER['SERVER_ADDR'];
$sys_info['web_server'] = $_SERVER['SERVER_SOFTWARE'];
$sys_info['php_ver'] = PHP_VERSION;
$sys_info['mysql_ver'] = $mysql_ver;
$sys_info['zlib'] = function_exists('gzclose') ? $_LANG['yes']:$_LANG['no'];
$sys_info['safe_mode'] = (boolean) ini_get('safe_mode') ? $_LANG['yes']:$_LANG['no'];
$sys_info['safe_mode_gid'] = (boolean) ini_get('safe_mode_gid') ? $_LANG['yes'] : $_LANG['no'];
$sys_info['timezone'] = function_exists("date_default_timezone_get") ? date_default_timezone_get() : $_LANG['no_timezone'];
$sys_info['socket'] = function_exists('fsockopen') ? $_LANG['yes'] : $_LANG['no'];
if ($gd == 0)
{
$sys_info['gd'] = 'N/A';
}
else
{
if ($gd == 1)
{
$sys_info['gd'] = 'GD1';
}
else
{
$sys_info['gd'] = 'GD2';
}
$sys_info['gd'] .= ' (';
/* 檢查系統支持的圖片類型 */
if ($gd && (imagetypes() & IMG_JPG) > 0)
{
$sys_info['gd'] .= ' JPEG';
}
if ($gd && (imagetypes() & IMG_GIF) > 0)
{
$sys_info['gd'] .= ' GIF';
}
if ($gd && (imagetypes() & IMG_PNG) > 0)
{
$sys_info['gd'] .= ' PNG';
}
$sys_info['gd'] .= ')';
}
/* IP庫版本 */
$sys_info['ip_version'] = ecs_geoip('255.255.255.0');
/* 允許上傳的最大文件大小 */
$sys_info['max_filesize'] = ini_get('upload_max_filesize');
$smarty->assign('sys_info', $sys_info);
/* 缺貨登記 */
$smarty->assign('booking_goods', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('booking_goods') . ' WHERE is_dispose = 0'));
/* 退款申請 */
$smarty->assign('new_repay', $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('user_account') . ' WHERE process_type = ' . SURPLUS_RETURN . ' AND is_paid = 0 '));
assign_query_info();
$smarty->assign('ecs_version', VERSION);
$smarty->assign('ecs_release', RELEASE);
$smarty->assign('ecs_lang', $_CFG['lang']);
$smarty->assign('ecs_charset', strtoupper(EC_CHARSET));
$smarty->assign('install_date', local_date($_CFG['date_format'], $_CFG['install_date']));
$smarty->display('start.htm');
}
elseif ($_REQUEST['act'] == 'main_api')
{
require_once(ROOT_PATH . '/includes/lib_base.php');
$data = read_static_cache('api_str');
if($data === false || API_TIME < date('Y-m-d H:i:s',time()-43200))
{
include_once(ROOT_PATH . 'includes/cls_transport.php');
$ecs_version = VERSION;
$ecs_lang = $_CFG['lang'];
$ecs_release = RELEASE;
$php_ver = PHP_VERSION;
$mysql_ver = $db->version();
$order['stats'] = $db->getRow('SELECT COUNT(*) AS oCount, IFNULL(SUM(order_amount), 0) AS oAmount' .
' FROM ' .$ecs->table('order_info'));
$ocount = $order['stats']['oCount'];
$oamount = $order['stats']['oAmount'];
$goods['total'] = $db->GetOne('SELECT COUNT(*) FROM ' .$ecs->table('goods').
' WHERE is_delete = 0 AND is_alone_sale = 1 AND is_real = 1');
$gcount = $goods['total'];
$ecs_charset = strtoupper(EC_CHARSET);
$ecs_user = $db->getOne('SELECT COUNT(*) FROM ' . $ecs->table('users'));
$ecs_template = $db->getOne('SELECT value FROM ' . $ecs->table('shop_config') . ' WHERE code = \'template\'');
$style = $db->getOne('SELECT value FROM ' . $ecs->table('shop_config') . ' WHERE code = \'stylename\'');
if($style == '')
{
$style = '0';
}
$ecs_style = $style;
$shop_url = urlencode($ecs->url());
$patch_file = file_get_contents(ROOT_PATH.ADMIN_PATH."/patch_num");
$apiget = "ver= $ecs_version &lang= $ecs_lang &release= $ecs_release &php_ver= $php_ver &mysql_ver= $mysql_ver &ocount= $ocount &oamount= $oamount &gcount= $gcount &charset= $ecs_charset &usecount= $ecs_user &template= $ecs_template &style= $ecs_style &url= $shop_url &patch= $patch_file ";
$t = new transport;
$api_comment = $t->request('http://api.ecshop.com/checkver.php', $apiget);
$api_str = $api_comment["body"];
echo $api_str;
$f=ROOT_PATH . 'data/config.php';
file_put_contents($f,str_replace("'API_TIME', '".API_TIME."'","'API_TIME', '".date('Y-m-d H:i:s',time())."'",file_get_contents($f)));
write_static_cache('api_str', $api_str);
}
else
{
echo $data;
}
}
/*------------------------------------------------------ */
//-- 開店嚮導第一步
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'first')
{
$smarty->assign('countries', get_regions());
$smarty->assign('provinces', get_regions(1, 1));
$smarty->assign('cities', get_regions(2, 2));
$sql = 'SELECT value from ' . $ecs->table('shop_config') . " WHERE code='shop_name'";
$shop_name = $db->getOne($sql);
$smarty->assign('shop_name', $shop_name);
$sql = 'SELECT value from ' . $ecs->table('shop_config') . " WHERE code='shop_title'";
$shop_title = $db->getOne($sql);
$smarty->assign('shop_title', $shop_title);
//獲取配送方式
// $modules = read_modules('../includes/modules/shipping');
$directory = ROOT_PATH . 'includes/modules/shipping';
$dir = @opendir($directory);
$set_modules = true;
$modules = array();
while (false !== ($file = @readdir($dir)))
{
if (preg_match("/^.*?\.php$/", $file))
{
if ($file != 'express.php')
{
include_once($directory. '/' .$file);
}
}
}
@closedir($dir);
unset($set_modules);
foreach ($modules AS $key => $value)
{
ksort($modules[$key]);
}
ksort($modules);
for ($i = 0; $i < count($modules); $i++)
{
$lang_file = ROOT_PATH.'languages/' .$_CFG['lang']. '/shipping/' .$modules[$i]['code']. '.php';
if (file_exists($lang_file))
{
include_once($lang_file);
}
$modules[$i]['name'] = $_LANG[$modules[$i]['code']];
$modules[$i]['desc'] = $_LANG[$modules[$i]['desc']];
$modules[$i]['insure_fee'] = empty($modules[$i]['insure'])? 0 : $modules[$i]['insure'];
$modules[$i]['cod'] = $modules[$i]['cod'];
$modules[$i]['install'] = 0;
}
$smarty->assign('modules', $modules);
unset($modules);
//獲取支付方式
$modules = read_modules('../includes/modules/payment');
for ($i = 0; $i < count($modules); $i++)
{
$code = $modules[$i]['code'];
$modules[$i]['name'] = $_LANG[$modules[$i]['code']];
if (!isset($modules[$i]['pay_fee']))
{
$modules[$i]['pay_fee'] = 0;
}
$modules[$i]['desc'] = $_LANG[$modules[$i]['desc']];
}
// $modules[$i]['install'] = '0';
$smarty->assign('modules_payment', $modules);
assign_query_info();
$smarty->assign('ur_here', $_LANG['ur_config']);
$smarty->display('setting_first.htm');
}
/*------------------------------------------------------ */
//-- 開店嚮導第二步
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'second')
{
admin_priv('shop_config');
$shop_name = empty($_POST['shop_name']) ? '' : $_POST['shop_name'] ;
$shop_title = empty($_POST['shop_title']) ? '' : $_POST['shop_title'] ;
$shop_country = empty($_POST['shop_country']) ? '' : intval($_POST['shop_country']);
$shop_province = empty($_POST['shop_province']) ? '' : intval($_POST['shop_province']);
$shop_city = empty($_POST['shop_city']) ? '' : intval($_POST['shop_city']);
$shop_address = empty($_POST['shop_address']) ? '' : $_POST['shop_address'] ;
$shipping = empty($_POST['shipping']) ? '' : $_POST['shipping'];
$payment = empty($_POST['payment']) ? '' : $_POST['payment'];
if(!empty($shop_name))
{
$sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_name' WHERE code = 'shop_name'";
$db->query($sql);
}
if(!empty($shop_title))
{
$sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_title' WHERE code = 'shop_title'";
$db->query($sql);
}
if(!empty($shop_address))
{
$sql = 'UPDATE ' . $ecs->table('shop_config') . " SET value = '$shop_address' WHERE code = 'shop_address'";
$db->query($sql);
}
if(!empty($shop_country))
{
$sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_country' WHERE code='shop_country'";
$db->query($sql);
}
if(!empty($shop_province))
{
$sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_province' WHERE code='shop_province'";
$db->query($sql);
}
if(!empty($shop_city))
{
$sql = 'UPDATE ' . $ecs->table('shop_config') . "SET value = '$shop_city' WHERE code='shop_city'";
$db->query($sql);
}
//設置配送方式
if(!empty($shipping))
{
$shop_add = read_modules('../includes/modules/shipping');
foreach ($shop_add as $val)
{
$mod_shop[] = $val['code'];
}
$mod_shop = implode(',',$mod_shop);
$set_modules = true;
if(strpos($mod_shop,$shipping) === false)
{
exit;
}
else
{
include_once(ROOT_PATH . 'includes/modules/shipping/' . $shipping . '.php');
}
$sql = "SELECT shipping_id FROM " .$ecs->table('shipping'). " WHERE shipping_code = '$shipping'";
$shipping_id = $db->GetOne($sql);
if($shipping_id <= 0)
{
$insure = empty($modules[0]['insure']) ? 0 : $modules[0]['insure'];
$sql = "INSERT INTO " . $ecs->table('shipping') . " (" .
"shipping_code, shipping_name, shipping_desc, insure, support_cod, enabled" .
") VALUES (" .
"'" . addslashes($modules[0]['code']). "', '" . addslashes($_LANG[$modules[0]['code']]) . "', '" .
addslashes($_LANG[$modules[0]['desc']]) . "', '$insure', '" . intval($modules[0]['cod']) . "', 1)";
$db->query($sql);
$shipping_id = $db->insert_Id();
}
//設置配送區域
$area_name = empty($_POST['area_name']) ? '' : $_POST['area_name'];
if(!empty($area_name))
{
$sql = "SELECT shipping_area_id FROM " .$ecs->table("shipping_area").
" WHERE shipping_id='$shipping_id' AND shipping_area_name='$area_name'";
$area_id = $db->getOne($sql);
if($area_id <= 0)
{
$config = array();
foreach ($modules[0]['configure'] AS $key => $val)
{
$config[$key]['name'] = $val['name'];
$config[$key]['value'] = $val['value'];
}
$count = count($config);
$config[$count]['name'] = 'free_money';
$config[$count]['value'] = 0;
/* 如果支持貨到付款,則允許設置貨到付款支付費用 */
if ($modules[0]['cod'])
{
$count++;
$config[$count]['name'] = 'pay_fee';
$config[$count]['value'] = make_semiangle(0);
}
$sql = "INSERT INTO " .$ecs->table('shipping_area').
" (shipping_area_name, shipping_id, configure) ".
"VALUES" . " ('$area_name', '$shipping_id', '" .serialize($config). "')";
$db->query($sql);
$area_id = $db->insert_Id();
}
$region_id = empty($_POST['shipping_country']) ? 1 : intval($_POST['shipping_country']);
$region_id = empty($_POST['shipping_province']) ? $region_id : intval($_POST['shipping_province']);
$region_id = empty($_POST['shipping_city']) ? $region_id : intval($_POST['shipping_city']);
$region_id = empty($_POST['shipping_district']) ? $region_id : intval($_POST['shipping_district']);
/* 添加選定的城市和地區 */
$sql = "REPLACE INTO ".$ecs->table('area_region')." (shipping_area_id, region_id) VALUES ('$area_id', '$region_id')";
$db->query($sql);
}
}
unset($modules);
if(!empty($payment))
{
/* 取相應插件信息 */
$set_modules = true;
include_once(ROOT_PATH.'includes/modules/payment/' . $payment . '.php');
$pay_config = array();
if (isset($_REQUEST['cfg_value']) && is_array($_REQUEST['cfg_value']))
{
for ($i = 0; $i < count($_POST['cfg_value']); $i++)
{
$pay_config[] = array('name' => trim($_POST['cfg_name'][$i]),
'type' => trim($_POST['cfg_type'][$i]),
'value' => trim($_POST['cfg_value'][$i])
);
}
}
$pay_config = serialize($pay_config);
/* 安裝,檢查該支付方式是否曾經安裝過 */
$sql = "SELECT COUNT(*) FROM " . $ecs->table('payment') . " WHERE pay_code = '$payment'";
if ($db->GetOne($sql) > 0)
{
$sql = "UPDATE " . $ecs->table('payment') .
" SET pay_config = '$pay_config'," .
" enabled = '1' " .
"WHERE pay_code = '$payment' LIMIT 1";
$db->query($sql);
}
else
{
// $modules = read_modules('../includes/modules/payment');
$payment_info = array();
$payment_info['name'] = $_LANG[$modules[0]['code']];
$payment_info['pay_fee'] = empty($modules[0]['pay_fee']) ? 0 : $modules[0]['pay_fee'];
$payment_info['desc'] = $_LANG[$modules[0]['desc']];
$sql = "INSERT INTO " . $ecs->table('payment') . " (pay_code, pay_name, pay_desc, pay_config, is_cod, pay_fee, enabled, is_online)" .
"VALUES ('$payment', '$payment_info[name]', '$payment_info[desc]', '$pay_config', '0', '$payment_info[pay_fee]', '1', '1')";
$db->query($sql);
}
}
clear_all_files();
assign_query_info();
$smarty->assign('ur_here', $_LANG['ur_add']);
$smarty->display('setting_second.htm');
}
/*------------------------------------------------------ */
//-- 開店嚮導第三步
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'third')
{
admin_priv('goods_manage');
$good_name = empty($_POST['good_name']) ? '' : $_POST['good_name'];
$good_number = empty($_POST['good_number']) ? '' : $_POST['good_number'];
$good_category = empty($_POST['good_category']) ? '' : $_POST['good_category'];
$good_brand = empty($_POST['good_brand']) ? '' : $_POST['good_brand'];
$good_price = empty($_POST['good_price']) ? 0 : $_POST['good_price'];
$good_name = empty($_POST['good_name']) ? '' : $_POST['good_name'];
$is_best = empty($_POST['is_best']) ? 0 : 1;
$is_new = empty($_POST['is_new']) ? 0 : 1;
$is_hot = empty($_POST['is_hot']) ? 0 :1;
$good_brief = empty($_POST['good_brief']) ? '' : $_POST['good_brief'];
$market_price = $good_price * 1.2;
if(!empty($good_category))
{
if (cat_exists($good_category, 0))
{
/* 同級別下不能有重複的分類名稱 */
$link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
sys_msg($_LANG['catname_exist'], 0, $link);
}
}
if(!empty($good_brand))
{
if (brand_exists($good_brand))
{
/* 同級別下不能有重複的品牌名稱 */
$link[] = array('text' => $_LANG['go_back'], 'href' => 'javascript:history.back(-1)');
sys_msg($_LANG['brand_name_exist'], 0, $link);
}
}
$brand_id = 0;
if(!empty($good_brand))
{
$sql = 'INSERT INTO ' . $ecs->table('brand') . " (brand_name, is_show)" .
" values('" . $good_brand . "', '1')";
$db->query($sql);
$brand_id = $db->insert_Id();
}
if(!empty($good_category))
{
$sql = 'INSERT INTO ' . $ecs->table('category') . " (cat_name, parent_id, is_show)" .
" values('" . $good_category . "', '0', '1')";
$db->query($sql);
$cat_id = $db->insert_Id();
//貨號
require_once(ROOT_PATH . ADMIN_PATH . '/includes/lib_goods.php');
$max_id = $db->getOne("SELECT MAX(goods_id) + 1 FROM ".$ecs->table('goods'));
$goods_sn = generate_goods_sn($max_id);
include_once(ROOT_PATH . 'includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
if(!empty($good_name))
{
/* 檢查圖片:如果有錯誤,檢查尺寸是否超過最大值;否則,檢查文件類型 */
if (isset($_FILES['goods_img']['error'])) // php 4.2 版本才支持 error
{
// 最大上傳文件大小
$php_maxsize = ini_get('upload_max_filesize');
$htm_maxsize = '2M';
// 商品圖片
if ($_FILES['goods_img']['error'] == 0)
{
if (!$image->check_img_type($_FILES['goods_img']['type']))
{
sys_msg($_LANG['invalid_goods_img'], 1, array(), false);
}
}
elseif ($_FILES['goods_img']['error'] == 1)
{
sys_msg(sprintf($_LANG['goods_img_too_big'], $php_maxsize), 1, array(), false);
}
elseif ($_FILES['goods_img']['error'] == 2)
{
sys_msg(sprintf($_LANG['goods_img_too_big'], $htm_maxsize), 1, array(), false);
}
}
/* 4。1版本 */
else
{
// 商品圖片
if ($_FILES['goods_img']['tmp_name'] != 'none')
{
if (!$image->check_img_type($_FILES['goods_img']['type']))
{
sys_msg($_LANG['invalid_goods_img'], 1, array(), false);
}
}
}
$goods_img = ''; // 初始化商品圖片
$goods_thumb = ''; // 初始化商品縮略圖
$original_img = ''; // 初始化原始圖片
$old_original_img = ''; // 初始化原始圖片舊圖
// 如果上傳了商品圖片,相應處理
if ($_FILES['goods_img']['tmp_name'] != '' && $_FILES['goods_img']['tmp_name'] != 'none')
{
$original_img = $image->upload_image($_FILES['goods_img']); // 原始圖片
if ($original_img === false)
{
sys_msg($image->error_msg(), 1, array(), false);
}
$goods_img = $original_img; // 商品圖片
/* 複製一份相冊圖片 */
$img = $original_img; // 相冊圖片
$pos = strpos(basename($img), '.');
$newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos);
if (!copy('../' . $img, '../' . $newname))
{
sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false);
}
$img = $newname;
$gallery_img = $img;
$gallery_thumb = $img;
// 如果系統支持GD,縮放商品圖片,且給商品圖片和相冊圖片加水印
if ($image->gd_version() > 0 && $image->check_img_function($_FILES['goods_img']['type']))
{
// 如果設置大小不為0,縮放圖片
if ($_CFG['image_width'] != 0 || $_CFG['image_height'] != 0)
{
$goods_img = $image->make_thumb('../'. $goods_img , $GLOBALS['_CFG']['image_width'], $GLOBALS['_CFG']['image_height']);
if ($goods_img === false)
{
sys_msg($image->error_msg(), 1, array(), false);
}
}
$newname = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos);
if (!copy('../' . $img, '../' . $newname))
{
sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false);
}
$gallery_img = $newname;
// 加水印
if (intval($_CFG['watermark_place']) > 0 && !empty($GLOBALS['_CFG']['watermark']))
{
if ($image->add_watermark('../'.$goods_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false)
{
sys_msg($image->error_msg(), 1, array(), false);
}
if ($image->add_watermark('../'. $gallery_img,'',$GLOBALS['_CFG']['watermark'], $GLOBALS['_CFG']['watermark_place'], $GLOBALS['_CFG']['watermark_alpha']) === false)
{
sys_msg($image->error_msg(), 1, array(), false);
}
}
// 相冊縮略圖
if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0)
{
$gallery_thumb = $image->make_thumb('../' . $img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']);
if ($gallery_thumb === false)
{
sys_msg($image->error_msg(), 1, array(), false);
}
}
}
else
{
/* 複製一份原圖 */
$pos = strpos(basename($img), '.');
$gallery_img = dirname($img) . '/' . $image->random_filename() . substr(basename($img), $pos);
if (!copy('../' . $img, '../' . $gallery_img))
{
sys_msg('fail to copy file: ' . realpath('../' . $img), 1, array(), false);
}
$gallery_thumb = '';
}
}
// 未上傳,如果自動選擇生成,且上傳了商品圖片,生成所略圖
if (!empty($original_img))
{
// 如果設置縮略圖大小不為0,生成縮略圖
if ($_CFG['thumb_width'] != 0 || $_CFG['thumb_height'] != 0)
{
$goods_thumb = $image->make_thumb('../' . $original_img, $GLOBALS['_CFG']['thumb_width'], $GLOBALS['_CFG']['thumb_height']);
if ($goods_thumb === false)
{
sys_msg($image->error_msg(), 1, array(), false);
}
}
else
{
$goods_thumb = $original_img;
}
}
$sql = 'INSERT INTO ' . $ecs->table('goods') . "(goods_name, goods_sn, goods_number, cat_id, brand_id, goods_brief, shop_price, market_price, goods_img, goods_thumb, original_img,add_time, last_update,
is_best, is_new, is_hot)" .
"VALUES('$good_name', '$goods_sn', '$good_number', '$cat_id', '$brand_id', '$good_brief', '$good_price'," .
" '$market_price', '$goods_img', '$goods_thumb', '$original_img','" . gmtime() . "', '". gmtime() . "', '$is_best', '$is_new', '$is_hot')";
$db->query($sql);
$good_id = $db->insert_id();
/* 如果有圖片,把商品圖片加入圖片相冊 */
if (isset($img))
{
$sql = "INSERT INTO " . $ecs->table('goods_gallery') . " (goods_id, img_url, img_desc, thumb_url, img_original) " .
"VALUES ('$good_id', '$gallery_img', '', '$gallery_thumb', '$img')";
$db->query($sql);
}
}
}
assign_query_info();
// $smarty->assign('ur_here', '開店嚮導-添加商品');
$smarty->display('setting_third.htm');
}
/*------------------------------------------------------ */
//-- 關於 ECSHOP
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'about_us')
{
assign_query_info();
$smarty->display('about_us.htm');
}
/*------------------------------------------------------ */
//-- 拖動的幀
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'drag')
{
$smarty->display('drag.htm');;
}
/*------------------------------------------------------ */
//-- 檢查訂單
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'check_order')
{
if (empty($_SESSION['last_check']))
{
$_SESSION['last_check'] = gmtime();
make_json_result('', '', array('new_orders' => 0, 'new_paid' => 0));
}
/* 新訂單 */
$sql = 'SELECT COUNT(*) FROM ' . $ecs->table('order_info').
" WHERE add_time >= '$_SESSION[last_check]'";
$arr['new_orders'] = $db->getOne($sql);
/* 新付款的訂單 */
$sql = 'SELECT COUNT(*) FROM '.$ecs->table('order_info').
' WHERE pay_time >= ' . $_SESSION['last_check'];
$arr['new_paid'] = $db->getOne($sql);
$_SESSION['last_check'] = gmtime();
if (!(is_numeric($arr['new_orders']) && is_numeric($arr['new_paid'])))
{
make_json_error($db->error());
}
else
{
make_json_result('', '', $arr);
}
}
/*------------------------------------------------------ */
//-- Totolist操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'save_todolist')
{
$content = json_str_iconv($_POST["content"]);
$sql = "UPDATE" .$GLOBALS['ecs']->table('admin_user'). " SET todolist='" . $content . "' WHERE user_id = " . $_SESSION['admin_id'];
$GLOBALS['db']->query($sql);
}
elseif ($_REQUEST['act'] == 'get_todolist')
{
$sql = "SELECT todolist FROM " .$GLOBALS['ecs']->table('admin_user'). " WHERE user_id = " . $_SESSION['admin_id'];
$content = $GLOBALS['db']->getOne($sql);
echo $content;
}
// 郵件群發處理
elseif ($_REQUEST['act'] == 'send_mail')
{
if ($_CFG['send_mail_on'] == 'off')
{
make_json_result('', $_LANG['send_mail_off'], 0);
exit();
}
$sql = "SELECT * FROM " . $ecs->table('email_sendlist') . " ORDER BY pri DESC, last_send ASC LIMIT 1";
$row = $db->getRow($sql);
//發送列表為空
if (empty($row['id']))
{
make_json_result('', $_LANG['mailsend_null'], 0);
}
//發送列表不為空,郵件地址為空
if (!empty($row['id']) && empty($row['email']))
{
$sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'";
$db->query($sql);
$count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist'));
make_json_result('', $_LANG['mailsend_skip'], array('count' => $count, 'goon' => 1));
}
//查詢相關模板
$sql = "SELECT * FROM " . $ecs->table('mail_templates') . " WHERE template_id = '$row[template_id]'";
$rt = $db->getRow($sql);
//如果是模板,則將已存入email_sendlist的內容作為郵件內容
//否則即是雜質,將mail_templates調出的內容作為郵件內容
if ($rt['type'] == 'template')
{
$rt['template_content'] = $row['email_content'];
}
if ($rt['template_id'] && $rt['template_content'])
{
if (send_mail('', $row['email'], $rt['template_subject'], $rt['template_content'], $rt['is_html']))
{
//發送成功
//從列表中刪除
$sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'";
$db->query($sql);
//剩餘列表數
$count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist'));
if($count > 0)
{
$msg = sprintf($_LANG['mailsend_ok'],$row['email'],$count);
}
else
{
$msg = sprintf($_LANG['mailsend_finished'],$row['email']);
}
make_json_result('', $msg, array('count' => $count));
}
else
{
//發送出錯
if ($row['error'] < 3)
{
$time = time();
$sql = "UPDATE " . $ecs->table('email_sendlist') . " SET error = error + 1, pri = 0, last_send = '$time' WHERE id = '$row[id]'";
}
else
{
//將出錯超次的紀錄刪除
$sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'";
}
$db->query($sql);
$count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist'));
make_json_result('', sprintf($_LANG['mailsend_fail'],$row['email']), array('count' => $count));
}
}
else
{
//無效的郵件隊列
$sql = "DELETE FROM " . $ecs->table('email_sendlist') . " WHERE id = '$row[id]'";
$db->query($sql);
$count = $db->getOne("SELECT COUNT(*) FROM " . $ecs->table('email_sendlist'));
make_json_result('', sprintf($_LANG['mailsend_fail'],$row['email']), array('count' => $count));
}
}
/*------------------------------------------------------ */
//-- license操作
/*------------------------------------------------------ */
elseif ($_REQUEST['act'] == 'license')
{
$is_ajax = $_GET['is_ajax'];
if (isset($is_ajax) && $is_ajax)
{
// license 檢查
include_once(ROOT_PATH . 'includes/cls_transport.php');
include_once(ROOT_PATH . 'includes/cls_json.php');
include_once(ROOT_PATH . 'includes/lib_main.php');
include_once(ROOT_PATH . 'includes/lib_license.php');
$license = license_check();
switch ($license['flag'])
{
case 'login_succ':
if (isset($license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str']) && $license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str'] != '')
{
make_json_result(process_login_license($license['request']['info']['service']['ecshop_b2c']['cert_auth']));
}
else
{
make_json_error(0);
}
break;
case 'login_fail':
case 'login_ping_fail':
make_json_error(0);
break;
case 'reg_succ':
$_license = license_check();
switch ($_license['flag'])
{
case 'login_succ':
if (isset($_license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str']) && $_license['request']['info']['service']['ecshop_b2c']['cert_auth']['auth_str'] != '')
{
make_json_result(process_login_license($license['request']['info']['service']['ecshop_b2c']['cert_auth']));
}
else
{
make_json_error(0);
}
break;
case 'login_fail':
case 'login_ping_fail':
make_json_error(0);
break;
}
break;
case 'reg_fail':
case 'reg_ping_fail':
make_json_error(0);
break;
}
}
else
{
make_json_error(0);
}
}
/**
* license check
* @return bool
*/
function license_check()
{
// return 返回數組
$return_array = array();
// 取出網店 license
$license = get_shop_license();
// 檢測網店 license
if (!empty($license['certificate_id']) && !empty($license['token']) && !empty($license['certi']))
{
// license(登錄)
$return_array = license_login();
}
else
{
// license(註冊)
$return_array = license_reg();
}
return $return_array;
}
?>
| Shallmay14/Qiandynasty | shop/admin/index.php | PHP | gpl-2.0 | 48,360 |